在渲染之前将表单'author'字段设置为登录用户 [英] Set form 'author' field to logged in user before render

查看:124
本文介绍了在渲染之前将表单'author'字段设置为登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的表单作者字段(models.ForeignKey(User))的默认值设置为当前登录的用户。我想在保存条目之前做到这一点,所以当创建一个条目时,用户不必选择自己才能验证表单。

I want to set the default value of my forms 'author' field (models.ForeignKey(User)) to the currently logged in user. I want to do this before the entry is saved so when creating an entry the user does not have to select themselves in order for the form to validate.

我尝试在我的表单init函数中设置值,但是没有引用请求对象,所以似乎不可能?

I tried setting the value in my form init function, but there is not reference to the request object so it seems impossible?

我没有在这个应用程序中使用django管理面板。

I am not using the django admin panel for this application.

推荐答案

动态初始值适用于我,默认情况下为 Django表单视图

Dynamic initial values worked for me, for a default Django form view:

if request.method == 'POST': 
    form = ContactForm(request.POST) 
    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
    form = ContactForm(initial={'author': request.user }) 

return render_to_response('contact.html', {
    'form': form,

这将为作者下拉菜单设置未绑定表单的初始值,用户在编辑时仍然可以改变它。

This sets the initial value in the author drop-down for an unbound form, the user could still change it whilst editing.

这篇关于在渲染之前将表单'author'字段设置为登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆