0

I'm newb to python django. I am making a small web page. Here is a piece of code i'm running. I want to make cumtom user model and use it to resigter with music genre, instrumet and nickname. But with this code, even i did all the migrations, doesn't work well. After the email input, an error is keep occuring. The error is <django.db.utils.OperationalError: no such column: accounts_user.genre>. Please help....

<models.py>

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

class UserManager(BaseUserManager):
    def create_user(self, email, genre, nickname,instrument, name, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            email=self.normalize_email(email),
            genre=genre,
            nickname=nickname,
            instrument=instrument,
            name=name,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self,nickname, email,password):
        user = self.create_user(
            email,
            password=password,
            nickname=nickname,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email',
        max_length=255,
        unique=True,
    )
    objects = UserManager()
    genre=models.CharField(max_length=100)
    instrument=models.CharField(max_length=10, default='')
    nickname = models.CharField(max_length=100, default='')
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['instrument']
    def __str__(self):
        return self.email
    def has_perm(self, perm, obj=None):
        return True
    def has_module_perms(self, app_label):
        return True
    @property
    def is_staff(self):
        return self.is_admin

and here is my views.py <views.py>

from django.shortcuts import render, redirect
from .models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password1'] == request.POST['password2']:
            user=User.objects.create_user(request.POST['username'], password=request.POST['password1'])
            auth.login(request, user)
            return redirect('melody')
    return render(request, 'signup.html')
def create(request):
    new_user=User()
    new_user.email=request.POST['email']
    new_user.nickname=request.POST['nickname']
    new_user.genre=request.POST['genre']
    new_user.instrument=request.POST['instrument']
    new_user.save()
def login(request):
    if request.method == "POST":
        username=request.POST['username']
        password=request.POST['password']
        user=auth.authenticate(request, username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('melody')
        else:
            return render(request, 'login.html', {'error': 'username or password is incorrect'})
    else:
        return render(request, 'login.html')

<admin.py>

from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserChangeForm, UserCreationForm
from .models import User

class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    list_display = ('email', 'instrument', 'genre','nickname', 'instrument', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('instrument', 'nickname','genre')},),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'instrument', 'genre','nickname','password1', 'password2')}
         ),
    )
    search_fields = ('email','nickname','genre','instrument',)
    ordering = ('email',)
    filter_horizontal = ()

admin.site.register(User, UserAdmin)
admin.site.unregister(Group)

<forms.py>

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(
        label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email', 'instrument','nickname', 'genre','instrument')

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2
    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()
    class Meta:
        model = User
        fields = ('email', 'password', 'instrument', 'genre','nickname','is_active', 'is_admin')
    def clean_password(self):
        return self.initial["password"]
Sangwon
  • 1
  • 1
  • Don't really have time right now to go through all this code and work out the issue, but this is probably the best tutorial on the different ways to extend the user model : https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html. Only thing I wondered was whether you'd run migrations _prior_ ti changing the model then running them again ... zapping all your migrations and running from scratch may help if so. – michjnich Aug 11 '21 at 09:41
  • Thanks! Think this will help :) – Sangwon Aug 11 '21 at 11:34

0 Answers0