Django - проблема с ограничением Not Null
Здравствуйте, в моей программе я продолжаю получать вышеуказанное исключение и не знаю, почему. Проблема возникает, когда мой метод requestLessons_view пытается сохранить форму.
Views.py
def requestLessons_view(request):
if request.method == 'POST':
form = RequestLessonsForm(request.POST)
if form.is_valid() & request.user.is_authenticated:
user = request.user
form.save(user)
return redirect('login')
else:
form = RequestLessonsForm()
return render(request, 'RequestLessonsPage.html', {'form': form})
forms.py
class RequestLessonsForm(forms.ModelForm):
class Meta:
model = Request
fields = ['availability', 'num_of_lessons', 'interval_between_lessons', 'duration_of_lesson','further_information']
widgets = {'further_information' : forms.Textarea()}
def save(self, user):
super().save(commit=False)
request = Request.objects.create(
student = user,
availability=self.cleaned_data.get('availability'),
num_of_lessons=self.cleaned_data.get('num_of_lessons'),
interval_between_lessons=self.cleaned_data.get('interval_between_lessons'),
duration_of_lesson=self.cleaned_data.get('duration_of_lesson'),
further_information=self.cleaned_data.get('further_information'),
)
return request
models.py
class Request(models.Model):
student = models.ForeignKey(
User,
on_delete=models.CASCADE
)
availability=models.CharField(blank=False, max_length=5)
num_of_lessons=models.CharField(blank=False,max_length=40)
interval_between_lessons=models.CharField(blank=False,max_length=30)
duration_of_lesson=models.CharField(blank=False,max_length=60)
further_information=models.CharField(blank=False,max_length=300)
is_fulfilled=models.BooleanField(default=False)
Ошибка, которую я получаю: IntegrityError at /request_lessons/ NOT NULL constraint failed: lessons_request.student_id
Ваш метод .save()
определен на классе Meta
, а не на form
, отсюда и ошибка. Я бы посоветовал позволить форме модели обрабатывать логику: ModelForm
может использоваться как для создания, так и для обновления элементов, поэтому, выполняя логику сохранения самостоятельно, вы, по сути, делаете форму менее эффективной. Вы можете переписать это следующим образом:
class RequestLessonsForm(forms.ModelForm):
class Meta:
model = Request
fields = [
'availability',
'num_of_lessons',
'interval_between_lessons',
'duration_of_lesson',
'further_information',
]
widgets = {'further_information': forms.Textarea}
def save(self, user, *args, **kwargs):
self.instance.student = user
return super().save(*args, **kwargs)
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc].