smilebomb smilebomb - 4 months ago 35
Python Question

django add foreign key value after form submit

After a

ModelForm
has been submitted, how can I add a foreign key relation so that it validates?

models.py


class Comment(models.Model):
id = models.AutoField(primary_key=True)
activity = models.ForeignKey(Activity)
submitter = models.ForeignKey(User)

creation_date = models.DateTimeField(auto_now_add=True)
content = models.TextField()


forms.py


class CommentForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)

class Meta:
model = Comment


views.py


def index(request, id=None):
activity_instance = Activity.objects.get(pk=1)
submitter_instance = User.objects.get(id=1)

newComment = CommentForm(request.POST)
newComment.activity = activity_instance
newComment.submitter = submitter_instance

if newComment.is_valid(): # <-- false, which is the problem

Answer

I think you are mixing up form instance with model instance. your newComment is a form, assigning other objects as a form attribute will not make the form saving the foreign key(not sure where did you find this usage), because all form data is saved in form.data, which is a dict like data structure.

I'm not sure what does your form look like because you didn't exclude the foreign keys so they should be rendered as dropdowns and you could select them. If you don't want the user to select the foreign key but choose to assign the values as you currently do, you should exclude them in the form so form.is_valid() would pass:

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Comment
        exclude = ('activity', 'submitter')

views.py

def index(request, id=None):
    activity_instance = Activity.objects.get(pk=1)
    submitter_instance = User.objects.get(id=1)

    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        new_comment = comment_form.save(commit=False)
        new_comment.activity = activity_instance
        new_comment.submitter = submitter_instance
        new_comment.save()

Django doc about save() method.