1

Не создается объект пользователя при регистрации(нет его в админке джанго в итоге). Сама регистрация проходит. views.py

from django.contrib.auth import authenticate
from django.shortcuts import render
from django.shortcuts import HttpResponse, HttpResponseRedirect, reverse, redirect
from django.views.generic import DetailView, ListView
from django.views.generic.edit import FormView,CreateView
from .models import User, UserManager
from .forms import RegisterForm
def register(request):
    args = {}
    args['form'] = RegisterForm()
    if request.method == 'POST':
        newuser_form = RegisterForm(data=request.POST)
        if newuser_form.is_valid:
            user = newuser_form.save()
            newuser = authenticate (username = newuser_form.cleaned_data['username'],
            password = newuser_form.cleaned_data['password1'])
            login(request, user)
        else:
            args['form'] = newuser_form
    return render(request, 'registration.html', args)

forms.py

    # *-* coding:utf-8 *-*
    from django import forms
    from django.contrib.auth.forms import UserCreationForm
    from .models import User



   class RegisterForm(UserCreationForm):

    class Meta:
    model = User
    fields = ('username',
             'email',
             'firstname',
             'lastname',
             'middlename',
             'date_of_birth',
             'avatar',)


    def save(self, commit = True):
        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        first_name, last_name = self.cleaned_data["fullname"].split()
        user.first_name = first_name
        user.last_name = last_name
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
    return user

urls.py

from django.conf.urls import url
from .views import *
from django.contrib import admin
from django.contrib.auth.views import login, logout
from django.contrib.auth.decorators import login_required

urlpatterns = [
    url(r'^$', home, name = 'main'),
    url(r'^users/$', UserList.as_view(), name = 'users'),
    url(r'^users/user/(?P<slug>\w+)/', AccountView.as_view(), name = 'user'),
    url(r'^blogs/blog/(?P<slug>\w+)/', BlogView.as_view(), name = 'blog'),
    url(r'^login/', login, {'template_name': 'login.html'}, name = 'login'),
    url(r'^registration/', register, name = 'registration'),
    ]

registration.html

{% extends 'base.html' %}
{% block title %} Регистрация {% endblock %}
{% block content %}
{% if user.is_anonymous %}
<h1> Регистрация </h1>
<form action="/login/" method = "post" ecntype = "multipart/form-data"> 
    {% csrf_token %}
    {{ form.as_p }}
    <button type = "submit"> Зарегистрироваться </button>
</form>
{% endif %}
{% endblock %}

1 ответ 1

1

А как создавался модель User? наследуется ли от AbstractBaseUser? если нет, то нужно сделать примерно так

from django.contrib.auth.models import BaseUserManager, AbstractBaseUser

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        ...
    def create_user(self, email=None, password=None, **extra_fields):
        ...
    def create_superuser(self, email, password, **extra_fields):
        ...

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True, db_index=True)
    first_name = models.CharField(_(u'Имя'), max_length=30, blank=True)
    last_name = models.CharField(_(u'Фамилия'), max_length=30, blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False)
    is_active = models.BooleanField(_('active'), default=False)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    username = models.CharField(_('username'), max_length=200, null=True, blank=True, db_index=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    class Meta:
        verbose_name = u'пользователя'
        verbose_name_plural = u'пользователей'

    def __unicode__(self):
        return u'%s' % self.get_full_name()

и в settings.py указать эту модель

AUTH_USER_MODEL = 'app_name.User

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.