8

我有一个自定义用户模型,除了电子邮件和密码之外,它还包含许多字段。一个字段是user_type设置为设计者或开发者。其他字段特定于一种或另一种类型。

我需要为每种用户类型创建一个单独的注册表单。

使用django-allauth可以轻松设置一个带有自定义字段的注册表单,因为我可以使用该ACCOUNT_SIGNUP_FORM_CLASS设置。我不确定如何设置多个。

4

2 回答 2

5

给出最后一个答案已经很长时间了,但希望这会对某人有所帮助。使用列“account_type”扩展用户。

表格.py

from django import forms

from allauth.account.forms import SignupForm


class AgentSignUpForm(SignupForm):

    first_name = forms.CharField(max_length=30, label='First name', required=False)
    last_name = forms.CharField(max_length=30, label='Last name', required=False)

    def save(self, request):
        user = super(AgentSignUpForm, self).save(request)
        user.account_type = 1
        user.save()
        return user

class CandidateSignUpForm(SignupForm):

    first_name = forms.CharField(max_length=30, label='First name', required=False)    
    last_name = forms.CharField(max_length=30, label='Last name', required=False)

    def save(self, request):
        user = super(CandidateSignUpForm, self).save(request)
        user.account_type = 2
        user.save()
        return user

视图.py

from django.shortcuts import render

from allauth.account.views import SignupView

from .forms import AgentSignUpForm
from .forms import CandidateSignUpForm


class AgentSignUp(SignupView):

    template_name = 'allauth/signup_agent.html'
    form_class = AgentSignUpForm
    redirect_field_name = 'next'
    view_name = 'agent_sign_up'

    def get_context_data(self, **kwargs):
        ret = super(AgentSignUp, self).get_context_data(**kwargs)
        ret.update(self.kwargs)
        return ret

class CandidateSignUp(SignupView):

    template_name = 'allauth/signup_candidate.html'
    form_class = CandidateSignUpForm
    redirect_field_name = 'next'
    view_name = 'candidate_sign_up'

    def get_context_data(self, **kwargs):
        ret = super(CandidateSignUp, self).get_context_data(**kwargs)
        ret.update(self.kwargs)
        return ret

网址.py

from django.conf.urls import url, include

from . import views

urlpatterns = [
    url(r'^agent-sign-up/', views.AgentSignUp.as_view(), name='agent-sign-up'),
    url(r'^candidate-sign-up/', views.CandidateSignUp.as_view(), name='candidate-sign-up'),
]

2个模板

#templates/allauth/signup_agent.html
<form method="post" action="{% url 'agent-sign-up' %}">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="ok" />
</form>

#templates/allauth/signup_candidate.html
<form method="post" action="{% url 'candidate-sign-up' %}">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="ok" />
</form>
于 2017-07-31T18:52:37.107 回答
-1

在我看来,您需要将这些放在单独的模型上。

为这些注册设计单独的视图和网址,您的视图可能看起来像这样

def register_account(request):
    template = 'shopper/register.html'
    if request.POST:
        form = UserprofileForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            password1 = form.cleaned_data['password1']
            u = User(username=username, email=email, last_name=last_name, first_name=first_name)
            u.set_password(password1)
            u.save()
    else:
        form = UserprofileForm()
    return render_to_response(template,
                          {'form': form}, context_instance=RequestContext(request))

和你的表格

class UserprofileForm(ModelForm):

required_css_class = 'required'

username = forms.RegexField(regex=r'^[\w.@+-]+$',
                            max_length=30,
                            label=_("Username"),
                            error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
def clean_username(self):
    """
    Validate that the username is alphanumeric and is not already
    in use.

    """
    existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
    if existing.exists():
        raise forms.ValidationError(_("A user with that username already exists."))
    else:
        return self.cleaned_data['username']


password1 = forms.CharField('Password', widget=forms.PasswordInput(), help_text='Password')
password2 = forms.CharField('Repeat Password', widget=forms.PasswordInput(), help_text='Repeat Password')

def clean_password2(self):
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')
    if not password1:
        raise forms.ValidationError("You must confirm your password")
    if password1 != password2:
        raise forms.ValidationError("Your passwords do not match")
    return password2
#town = forms.ModelChoiceField(queryset=Town.objects.all(), widget=forms.Select(attrs={'style': 'width: 100%;', 'data-placeholder': 'Select Town', 'tabindex': '2'}))
class Meta:
  model = Userprofile
  exclude = ()

从那里我确信你将能够锻炼 ret。

祝你好运

于 2015-11-16T04:55:11.790 回答