[Answered ]-Django: How to autopopulate foreign key with the corresponding model class instance

1πŸ‘

βœ…

I think this might solve your problem:

  1. Add decision field in the voting form. This will display an option to select for which decision you need to save this Vote for.
    If you don’t want to allow users to change the Decision, you can mark the field as disabled. See this issue for more details on how to do that. Another alternative is to completely hide the field.
class VotingForm(forms.ModelForm):
    class Meta:
        model = Votes
        fields = ['vote', 'decision']
  1. Add initial value of the decision when instantiating the VotingForm. This will automatically set which decision is selected when displaying the form.
class VoteForm(LoginRequiredMixin, CreateView):
    model = Votes
    form_class = VotingForm
    template_name = 'users/vote_form.html'

    # Use this to pass 'pk' to your context in the template
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({'pk': self.kwargs['pk'})

        return context

    def get_initial(self):
        initial = super().get_initial()
        initial.update({'decision': self.kwargs['pk']})

        return initial

    def get_success_url():
        # Import reverse from django.urls
        return reverse('users:vote_list')

Also, your form should probably be displayed like this in the HTML template: {% crispy form %}. This way all defined fields from the VotingForm class are rendered automatically.

<form method="post" action="{% url 'users:vote_form' pk %}">
     {% crispy form %}
</form>
πŸ‘€vinkomlacic

Leave a comment