How to use ForeignKeys in Django Modelform

/ #Django


It's normal to have ForeignKeys field in ModelForm. And if this is a hidden field, the save function will crash.

In the last post on this blog, I showed you how to create a simple modelform. In this post, I'll show you how to add a field with a ForeignKey (not showing in the form).

Typical use for this is author for blog posts and similar.

Adding the field

Open up "product/models.py" from the previous post and add the following content:

# Import the user model
from django.contrib.auth.models import User

class Product(models.Model):
  # Add the user field
  user = models.ForeignKey(User, related_name='products', on_delete=models.CASCADE)

Now you need to run the makemigrations and migrate script before we continue.

Changing the view

We don't need to do any changes to the form, but we need some minor changes to the view.

def addproduct(request):
  if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():
      obj = form.save(commit=False)
      obj.user = request.user
      obj.save()

      return redirect('/')
  else:
    form = ProductForm()

  context = {
    'form': form
  }

  return render(request, 'addproduct.html', context)

And that's it actually. We just need to prevent the form from saving by creating a new instance and adding "commit=False". Then we add the user and save the object.


Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.