Django如何从模板传递值来查看

时间:2015-03-31 08:34:12

标签: python django templates view

我想要这个功能。用户输入电子邮件地址,并以某种方式将其传递给我的views.py文件,这样我就可以通过电子邮件向用户发送他已成功注册的信息。

这是我的模板文件:

{% extends "base.html" %}

{% block content %}

<section>
<h2 style="text-align: center">Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}

<ul>
{{form.as_ul}}
</ul>
<input type="submit" value="Register" onclick="validateForm()"/>

</form>

</section>
{% endblock %}

这是我的forms.py文件:

class MyRegistrationForm(UserCreationForm):
    #kokie fields bus displayed html form
    email = forms.EmailField(required=True)
    firstname = forms.CharField(required=True)
    lastname = forms.CharField(required=True)
    whoinvitedyou = forms.CharField(required=True)
    phone = forms.CharField(required=True)
    workplace = forms.CharField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2', 'firstname', 'lastname', 'whoinvitedyou', 'phone', 'workplace')

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data["password1"])
#more fields for name last name
        user.firstname = self.cleaned_data['firstname']
        user.lastname = self.cleaned_data['lastname']
        user.whoinvitedyou = self.cleaned_data['whoinvitedyou']
        user.phone = self.cleaned_data['phone']
        user.workplace = self.cleaned_data['workplace']

        if commit:
            user.save()

        return user

这是我的views.py:

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
        else:
            return render_to_response('invalid_reg.html')

    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()
    print args
    return render_to_response('register.html', args)

我如何传递该值以便以后可以使用它?也许有人可以帮我这个......

2 个答案:

答案 0 :(得分:1)

在您的观看中,form.is_valid()来电后,电子邮件地址将在form.cleaned_data['email']中提供。您可以使用它在form.save()之后发送电子邮件。

此外,您可能希望查看现有的第三方库,例如django-registration,因为它已经完成了您想要的功能(通过电子邮件发送刚刚注册的用户)。

答案 1 :(得分:0)

要发送电子邮件,您不一定需要将值发送到views.py中的视图。 您可以使用post_save信号发送电子邮件。您可以将代码放在任何位置,但我通常会将其放在models.py

有关信号的信息:https://docs.djangoproject.com/en/1.7/topics/signals/

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail

@receiver(post_save, sender=User)
def my_handler(sender, instance, *args, **kwargs):
    send_mail('Subject of email', 'Message body.', 'from@example.com', [instance.email], fail_silently=False)

请注意,instance.email是您刚刚保存的用户的电子邮件地址,您可以访问instance来检索更多信息,例如:名称,以便您可以将"dear "+instance.name放在正文的开头,例如