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

487 Views Asked by At

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.

2

There are 2 best solutions below

0
Brian Destura On BEST ANSWER

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')
0
incrediblegiant On

Since you pass the cluster_code to forms, you can write a init method in your PostForm where you can save the value.