In Django, how do you pass ForeignKey to a model instance?

I am writing an application in which "Works" are stored. They are defined as having ForeignKeys associated with the "User". I do not understand how to pass ForeignKey to the model when creating it. My model for work worked fine without ForeignKey, but now when I try to add users to the system, I can’t get the form for verification.

models.py:

from django.db import models from django import forms from django.contrib.auth.models import User class Job(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=50, blank=True) pub_date = models.DateTimeField('date published', auto_now_add=True) orig_image = models.ImageField('uploaded image', upload_to='origImageDB/', blank=True) clean_image = models.ImageField('clean image', upload_to='cleanImageDB/', blank=True) fullsize_image = models.ImageField('fullsize image', upload_to='fullsizeImageDB/') fullsize_clean_image = models.ImageField('fullsize clean image', upload_to='fullsizeCleanImageDB/') regions = models.TextField(blank=True) orig_regions = models.TextField(blank=True) class JobForm(forms.ModelForm): class Meta: model = Job 

In views.py, I created the objects as follows:

 if request.method == 'POST': form = JobForm(request.POST, request.FILES) if form.is_valid(): #Do something here 

I understand that this passes form data and uploaded files to the form. However, I do not understand how to transfer the user to be installed as ForeignKey.

Thanks in advance to everyone who can help.

+6
source share
2 answers

Typical template in Django:

  • exclude user field from model form
  • save form using commit=False
  • set job.user
  • save to database

In your case:

 class JobForm(forms.ModelForm): class Meta: model = Job exclude = ('user',) if request.method == 'POST': form = JobForm(request.POST, request.FILES) job = form.save(commit=False) job.user = request.user job.save() # the next line isn't necessary here, because we don't have any m2m fields form.save_m2m() 

See the Django docs in the form of the save() form for more information.

+7
source

Try:

 if request.method == 'POST': data = request.POST data['user'] = request.user form = JobForm(data, request.FILES) if form.is_valid(): #Do something here 
+1
source

Source: https://habr.com/ru/post/908725/


All Articles