如何在Django中将用户对象传递给表单 [英] How to pass user object to forms in Django

查看:109
本文介绍了如何在Django中将用户对象传递给表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将用户对象或请求传递给表单以将其用作输入文本框的初始值?

How would I pass a user object or a request to my form for using it as an initial value for input textbox?

例如,我有以下表单:

class ContactForm(forms.Form):
contact_name = forms.CharField(required=True, initial="???")
contact_email = forms.EmailField(required=True)
subjects = forms.ChoiceField(choices=emailsubjects)
content = forms.CharField(
    required=True,
    widget=forms.Textarea
)

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop("request")
    super(ContactForm, self).__init__(*args, **kwargs)
    self.fields['contact_name'].label = "Your name:"
    self.fields['contact_email'].label = "Your email:"
    self.fields['content'].label = "What do you want to say?"
    self.fields['subjects'].label = "Please, select the subject of your message"

我希望将user.first_name用作contact_name字段的默认值。

Where i want my user.first_name to be as a default value for contact_name field.

这是我的views.py,在这里我要求使用表单:

Here is my views.py, where i call for form:

def ContactsView(request):
form_class = ContactForm(request=request)
# new logic!
if request.method == 'POST':
    form = form_class(data=request.POST)

    if form.is_valid():
        contact_name = request.POST.get(
            'contact_name'
            , '')
        contact_email = request.POST.get(
            'contact_email'
            , '')
        form_content = request.POST.get('content', '')
        subjects = form.cleaned_data['subjects']
        subjects = dict(form.fields['subjects'].choices)[subjects]
        # Email the profile with the
        # contact information
        template = get_template('threeD/email/contact_template.txt')
        context = Context({
            'contact_name': contact_name,
            'subjects': subjects,
            'contact_email': contact_email,
            'form_content': form_content,
        })
        content = template.render(context)

        email = EmailMessage(
            "New message from " + contact_name,
            content,
            "Message - " + subjects + ' ',
            ['smart.3d.printing.facility@gmail.com'],
            headers={'Reply-To': contact_email}
        )
        email.send()
        messages.success(request, "Thank you for your message.")
        return redirect('/index/contacts/')


return render(request, 'threeD/contacts.html', {
    'form': form_class,
})

任何帮助将不胜感激

推荐答案

您已将表单更改为采用请求对象。因此,您可以在表单的方法内访问 self.request.user

You have changed your form to take the request object. Therefore you can access self.request.user inside your form's methods:

class ContactForm(forms.Form):
    ...
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = "Your name:"
        self.fields['contact_name'].initial = self.request.user.first_name

您还必须更新视图以通过请求对象。记住要更新GET和POST请求的代码。

You also have to update your view to pass the request object. Remember to update the code for GET and POST requests.

if request.method == 'POST':
    form = ContactForm(data=request.POST, request=request)
    ...
else:
    # GET request
    form = ContactForm(request=request)

最后,通过将请求传递给表单,您已将其紧密耦合到视图。最好将 user 传递给表单。这样可以更轻松地与视图分开测试表单。如果您更改表单,请记住也要更新视图。

Finally, by passing the request to the form, you have tightly coupled it to the view. It might be better to pass the user to the form instead. This would make it easier to test the form separately from the view. If you change the form, remember to update the view as well.

这篇关于如何在Django中将用户对象传递给表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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