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

查看:23
本文介绍了如何将用户对象传递给 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天全站免登陆