如何在Django-registration 1.0中添加额外的(自定义)字段

Iqb*_*bal 7 django django-registration

我一直在阅读很多关于此的问题和答案,但仍然没有好运.例如,是一个很好的答案,但很可能不适用于django-registration 1.0.

我的目标是在注册表单中添加两个自定义字段,即组织职位. 注意:我使用registration.backend.simple提供的一步式django 注册.

nic*_*ius 0

由于您还没有答案,因此我提供这个答案,尽管这并不完全是您所要求的。我认为无论如何它可能对你有帮助,但......

这就是我在使用 django-registration 1.0、Python 2.7 和 Django 1.6 的几个项目中完成的方法。在本例中,我仅使用username,emailpassword进行注册,然后用户可以在注册后添加个人资料字段。修改它以接受注册时的字段应该不会太困难。

我使用 Twitter Bootstrap 进行样式设置,因此我的模板可能对您有帮助,也可能没有帮助。在这种情况下我把它们排除在外。

我创建了几个名为accounts和的应用程序authentication来保存我的模型、表单和视图:

账户.模型.用户配置文件

from django.db import models

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    title = models.CharField(max_length=100)
    company = models.CharField(max_length=250)
Run Code Online (Sandbox Code Playgroud)

authentication.forms.EditUserProfileForm

from django.forms import ModelForm

class EditUserProfileForm(ModelForm):**
    . . .
    title = forms.CharField(widget=forms.TextInput())
    company = forms.CharField(widget=forms.TextInput())
    . . .
Run Code Online (Sandbox Code Playgroud)

account.views.EditUserProfileView

from django.views.generic.base import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect

from .models import UserProfile
from .forms import EditUserProfileForm

class EditUserProfileView(View):

    form_class = EditUserProfileForm
    template_name = 'accounts/profile_edit.html'

    @method_decorator(login_required)
    def get(self, request, *args, **kwargs):

        profile = get_object_or_404(UserProfile, user=request.user)

        form_dict = {
            'title': profile.title,
            'company': profile.company,
        }

        form = self.form_class(form_dict)

        return render(request, self.template_name, {
            'form': form,
            'profile': profile,
        })

    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):

        profile = get_object_or_404(UserProfile, user=request.user)

        form = self.form_class(request.POST, instance=profile)

        if form.is_valid():

            company = form.cleaned_data['company']
            title = form.cleaned_data['title']

            title.company = title
            profile.company = company

            # you might need to save user too, depending on what fields
            request.user.save()
            profile.save()

            return HttpResponseRedirect('/dashboard/')

        return render(request, self.template_name, {'form': form})
Run Code Online (Sandbox Code Playgroud)

项目.url

url(r'^accounts/profile/edit/', EditUserProfileView.as_view(),  name='edit_user_profile_view'),
Run Code Online (Sandbox Code Playgroud)