如何在Django中创建个人资料注册表单? [英] How to create a profile registration form in Django?

查看:53
本文介绍了如何在Django中创建个人资料注册表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自定义注册表单,但由于要将默认的django注册与新模型连接起来,因此我真的不知道该怎么办.

I am trying to create a custom registration form, but I don't really know how to do it since I am trying to connect the default django registration with a new model.

这是它的外观,可能是错误的,但是我在想这样的事情.

here is what it looks like, it might be wrong but I am thinking to something like this.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=20, blank=True, null=True)
    description = models.TextField(max_length=400)

views.py

def register_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/user/')
    else:
        if request.method == 'POST':
            form = MyRegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/user/')

        context = {'profil':Profile.objects.all()}
        context.update(csrf(request))
        context['form'] = MyRegistrationForm()

        return render(request, 'register.html', context)

forms.py

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = {'username', 'password1', 'password2', 'email'}

    def save(self, commit=True):

        my_user = super(MyRegistrationForm, self).save(commit=False)
        my_user.email = self.cleaned_data['email']

        new_profile = Profile(user=my_user, name="John", description="a person")

        if commit:
            new_profile.save()

        return new_profile

register.py

<form action="/user/register/" method="post" id="register" autocomplete="off">
{% csrf_token %}
<div class="fieldWrapper">
  {{ form.username.errors }}
  {{ form.username.label_tag }}
  {{ form.username }}
</div>
[... other fiels ...]
<input type="submit" value="Register"/>
</form>

我正在尝试将模型与表单联系起来,所以当有人注册时以及当我在模板中键入他的名字时,如下所示: {{user.name}} 应该是"John.

I'm trying to connect the model with the form, so when someone register and when I type his name in the template like this : {{user.name}} It should be "John".

我如何实现这个目标?

推荐答案

此外,为了在模板中获取名称,您还必须像 {{user.profile.name}} 那样访问它名称保存在配置文件模型中

Also in order to get the name in the template you have to access it like {{ user.profile.name }} since name is saved in the Profile Model

但是但是,如果您想为个人资料模型创建表单,可以这样做

But if you want to create a form for your Profile model you can do it like this

class ProfileForm(forms.ModelForm):
    class Meta:
         model = Profile
         fields = ("name", "description")

此外,如果您打算在同一HTML表单中同时使用UserCreationForm和ProfileForm,则应向它们添加前缀,以了解哪些数据属于哪种表单,请在此处查找操作方法 https://docs.djangoproject.com/en/1.9/ref/forms/api/#prefixes-for-forms

Also if you plan to use both the UserCreationForm and the ProfileForm both in the same HTML Form you should add a prefix to them to know which data belongs to which form, look how to do it here https://docs.djangoproject.com/en/1.9/ref/forms/api/#prefixes-for-forms

修改

def register_user(request):
    #...
    if request.method == "POST":
        user_form = UserCreationForm(request.POST, prefix="user")
        profile_form = ProfileForm(request.POST, prefix="profile")
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/')
    else:
        user_form = UserCreationForm(prefix="user")
        profile_form = ProfileForm(prefix="profile")
    context = {
        "user_form": user_form,
        "profile_form": profile_form
    }
    return render(request, 'register.html', context)

然后在模板中

<form action="/user/register/" method="post" id="register" autocomplete="off">
{% csrf_token %}
<div class="fieldWrapper">
    {{ user_form }}
    {{ profile_form }}
</div>
<input type="submit" value="Register"/>

这篇关于如何在Django中创建个人资料注册表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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