B
B
blackbb2015-11-18 19:17:46
Django
blackbb, 2015-11-18 19:17:46

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)
    ....

And the shape of the model:
class HotelsForm(forms.ModelForm):
    class Meta:
        model = Hotels
        ....

views.py
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})

How can I make the user field be filled in automatically, and not offer a choice of users?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
marazmiki, 2015-11-18
@blackbb

First, remove this field from the form

class HotelsForm(forms.ModelForm):
    class Meta:
        model = Hotels
        exclude = ['user']

Secondly, in the view, substitute the value:
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 question

Ask a Question

731 491 924 answers to any question