Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing request.user with Django ModelForm
    text
    copied!<p>I'm having a problem with logged users and a Django <code>ModelForm</code>. I have a class named <code>_Animal_</code> that has a <code>ForeignKey</code> to <code>User</code> and some data related to the animal like age, race, and so on.</p> <p>A user can add Animals to the db and I have to track the author of each animal, so I need to add the <strong>request.user</strong> that is logged when the user creates an animal instance.</p> <p><strong>models.py</strong></p> <pre><code>class Animal(models.Model): name = models.CharField(max_length=300) age = models.PositiveSmallIntegerField() race = models.ForeignKey(Race) ... publisher = models.ForeignKey(User) def __unicode__(self): return self.name class AnimalForm(ModelForm): class Meta: model = Animal </code></pre> <p>The main goal is hide the publisher field in the form, and submit the logged user when hitting save button.</p> <p>I can catch the current user in the view using <code>initial</code>, but what I also want is not display the field.</p> <p><strong>views.py</strong></p> <pre><code>@login_required def new_animal(request): if request.method == "POST": form = AnimalForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: variables = RequestContext(request, {'form': form}) return render_to_response('web/animal_form.html', variables) else: form = AnimalForm(initial={'publisher': request.user}) variables = RequestContext(request, {'form': form}) return render_to_response('web/animal_form.html', variables) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload