将初始值从先前的详细信息视图传递到表单字段中

时间:2018-11-22 01:12:11

标签: django forms

我有点困惑,我在用户详细信息页面上有一个“联系用户”按钮。我试图将电子邮件字段的初始表单值设置为用户从先前的详细信息页面视图发送的电子邮件,以使其预先填充。

我可以将user.email作为垃圾邮件传递到按钮URL中吗?

views.py

def Contact(request):
    form_class = ContactForm

    # 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', '')

            # Email the profile with the
            # contact information
            template = get_template('contact_template.txt')
            context = {
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content,
            }
            content = template.render(context)

            email = EmailMessage(
                "New contact form submission",
                content,
                "Your website" +'',
                ['youremail@gmail.com'],
                headers = {'Reply-To': contact_email }
            )
            email.send()
            return redirect('contact_form')


    return render(request, 'portal/contact_form.html', {
        'form': form_class,
    })

forms.py

from django import forms
class ContactForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True, initial='{ kwarg }')
    content = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

user_detail.html

<div class="col-lg-4 text-center p-5" style="padding-right:20px; border-right: 1px solid #e5e5e5;">
              <a href="{% url 'portal:contact_form' kwarg.user.email %}">
                <h1><i class="fa fa-2x fa-envelope-o text-success" aria-hidden="true"></i></h1>
                <p class="text-muted mt-3 ">Contact Customer</p>
              </a>
            </div>

1 个答案:

答案 0 :(得分:1)

有多种方法可以做到这一点。例如:

方法1:通过网址查询字符串发送

从先前的详细信息视图中,以url查询字符串发送电子邮件。例如:

$template->setCurrentBlock("SHOPPINGCART");

foreach ($_SESSION["cart_item"] as $item){
    $item_price = $item["quantity"]*$item["price"];
    $template->setVariable("item_image", $item['image']);
      $template->setVariable("item_name", $item['name']);
      $template->setVariable("item_id", $item['id']);
      $template->setVariable("item_quantity", $item['quantity']);
      $template->setVariable("item_price", $item['price']);
      $template->parseCurrentBlock();
    }

并在Next表单视图中捕获它:

 def DetailForm(request, *args, **kwargs):
      ... 
      if form.is_valid():
           # do some things
           user_email = form.cleaned_data.get('user_email')  # assuming its the form field you are using for catching user email

           redirect_url = "{}?user_email={}".format(self.get_success_url(), user_email)
           return HttpResponseRedirect(redirect_url)

方法2:存储在会话中。

它与上一种方法几乎相似,但是将数据存储在session中。

  def Contact(request):
     form_class = ContactForm(initial={'contact_email': request.GET.get('user_email')})
     ...

并在“下一步”表单视图中获取它:

def DetailForm(request, *args, **kwargs):
      ... 
      if form.is_valid():
           # do some things
           request.session['user_email'] = form.cleaned_data.get('user_email')  # Storing data in session

           # every other code

更新

如果您来自详细信息页面,则意味着您有权访问该对象。因此,在详细信息页面中,像这样更新 def Contact(request): form_class = ContactForm(initial={'contact_email': request.session.get('user_email')}) ... 按钮:

contact

在联系人视图中:

<a href="{% url 'portal:contact_form' object.email %}">contact</a>  // or user.email if you are passing user object as user in context