将 request.user 与 Django ModelForm 一起使用 [英] Using request.user with Django ModelForm
问题描述
我遇到了登录用户和 Django ModelForm
的问题.我有一个名为 _Animal_
的类,它有一个 ForeignKey
到 User
和一些与动物相关的数据,如年龄、种族等.
I'm having a problem with logged users and a Django ModelForm
. I have a class named _Animal_
that has a ForeignKey
to User
and some data related to the animal like age, race, and so on.
用户可以将动物添加到数据库中,我必须跟踪每个动物的作者,因此我需要添加在用户创建动物实例时记录的 request.user.
A user can add Animals to the db and I have to track the author of each animal, so I need to add the request.user that is logged when the user creates an animal instance.
models.py
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
主要目标是隐藏表单中的发布者字段,并在点击保存按钮时提交登录的用户.
The main goal is hide the publisher field in the form, and submit the logged user when hitting save button.
我可以使用 initial
在视图中捕获当前用户,但我还想要的是不显示该字段.
I can catch the current user in the view using initial
, but what I also want is not display the field.
views.py
@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)
推荐答案
你只需要从表单中排除它,然后在视图中设置即可.
You just need to exclude it from the form, then set it in the view.
class AnimalForm(ModelForm):
class Meta:
model = Animal
exclude = ('publisher',)
...并在视图中:
form = AnimalForm(request.POST)
if form.is_valid():
animal = form.save(commit=False)
animal.publisher = request.user
animal.save()
(还要注意第一个 else
子句 - 紧跟在重定向之后的行 - 是不必要的.如果你省略它,执行将下降到视图末尾的两行,它们是相同的.)
(Note also that the first else
clause - the lines immediately following the redirect - is unnecessary. If you leave it out, execution will fall through to the two lines at the end of the view, which are identical.)
这篇关于将 request.user 与 Django ModelForm 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!