Answer the question
In order to leave comments, you need to log in
How to make the user field default current user?
There is a model:
class Hotels(models.Model):
title = models.CharField(max_length=200, verbose_name="Название")
slug = models.SlugField(unique=True, verbose_name="URL")
category = models.ForeignKey(Category, verbose_name='Тип обьявления')
user = models.ForeignKey(User)
....
class HotelsForm(forms.ModelForm):
class Meta:
model = Hotels
....
def add_hotels(request):
if request.method == 'POST':
formset = HotelsForm(request.POST, request.FILES)
if formset.is_valid()
formset.save()
return redirect('/user/success')
else:
print formset.errors
else:
formset = HotelsForm()
return render(request, 'add_hotels.html', {'formset': formset})
Answer the question
In order to leave comments, you need to log in
First, remove this field from the form
class HotelsForm(forms.ModelForm):
class Meta:
model = Hotels
exclude = ['user']
def add_hotels(request):
if request.method == 'POST':
formset = HotelsForm(request.POST, request.FILES)
if formset.is_valid()
hotels = formset.save(commit=False) # Пока не записывать изменения в БД
hotels.user = request.user
hotels.save() # Теперь можно записать
return redirect('/user/success')
else:
print formset.errors
else:
formset = HotelsForm()
return render(request, 'add_hotels.html', {'formset': formset})
It is not clear why the usual form is called a formset. And why is the model named in the plural.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question