Search code examples
djangodjango-modelsdjango-formsforeign-keysdjango-viewflow

How to set default for the foreignkey when using a form?


Scenario: I want to make an app that has servers(500+) as a model and another model that has posts as a foreign key to the server model to log what we did on each server.So as I said I have two models the server and the posts.


Solution

  • One way to do approach this is you can remove the cluster_code altogether in your form:

    class PostForm(ModelForm):
    
        class Meta:
    
            model = Post
            fields = ['name','time','cluster_log']
    

    and just add it to the post before saving to the database:

            form = PostForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                post.cluster_code = cluster_code
                post.save()
                redirect('view-post')