Таблица services_parceiros не имеет столбца с именем user_id, DJANGO - PullRequest
0 голосов
/ 14 февраля 2020

спасибо за ваше время. Я пытался установить модель для его создателя. хотя я получаю эту ошибку и хотел бы знать, если я делаю что-то неправильно, прежде чем попробовать AbstractUser. я бы добавил свое пользовательское приложение только в forms.py, я не знаю, в этом ли причина.

Ошибка: в таблице services_parceiros нет столбца с именем user_id

accounts / forms.py:

from django import forms
from django.contrib.auth import get_user_model, authenticate

User = get_user_model()

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput())

    def clean (self, *args, **kwargs):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:         
                raise forms.ValidationError('usuario não encontrado')
            if not user.check_password(password):
                raise forms.ValidationError('senha incorreta')
            if not user.is_active:
                raise forms.ValidationError('usuario desativado')
            return super(LoginForm, self).clean(*args, **kwargs)


class RegisterForm(forms.ModelForm):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    email = forms.EmailField(label='Email address')
    email2 = forms.EmailField(label='Confirm Email')
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = [
            'first_name',
            'last_name',
            'username',
            'email',
            'email2',
            'password'
        ]

    def clean(self, *args, **kwargs):
        email = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email != email2:
            raise forms.ValidationError("Emails must match")
        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError(
                "This email has already been registered")
        return super(RegisterForm, self).clean(*args, **kwargs)

services / models.py:

from django.db import models
from phone_field import PhoneField
from datetime import datetime
from django.contrib.auth import get_user_model
from django.template.defaultfilters import slugify
from accounts.forms import User

get_user_model = User

class Parceiros (models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    nome = models.CharField(max_length=200)
    endereco = models.TextField(max_length=400, blank=True)
    responsavel = models.CharField(max_length=100)
    tel = PhoneField(max_length=12)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True, blank=True)
    ativo = models.BooleanField(default=False)

    def __str__(self):
        return '%s %s' % (self.user, self.nome)

и services / views.py:

from django.shortcuts import render, redirect
from .models import Servicos, Parceiros, Imagens
from django.views.generic import UpdateView, DetailView, ListView
from .forms import ParceirosForm, ServicosForm, ImagensForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.context_processors import auth



def home_view(request):
    serv = Servicos.objects.all()
    context = {'serv': serv }
    return render (request, 'home.html', context)


@login_required
def parceiros_create(request):
    if request.method == 'POST':
        form = ParceirosForm(request.POST)
        if form.is_valid():
            parceiro = form.save(commit=False)
            parceiro.user = request.user  # assuming user is a FK field on Parceiros#
            parceiro.save()
            return redirect('home2')
    else:
        form = ParceirosForm()
    context = {
        'form': form,
    }
    return render (request, 'parceiroform.html', context)

    def get_queryset(self):
        return super().get_queryset().filter(parceiro__user=self.request.user)

services / forms.py: если я укажу пользователя в полях моего ParceirosForm я получу отображаемое поле и все равно получаю ту же ошибку при отправке.


from django import forms
from .models import Servicos, Imagens, Parceiros
from phone_field import PhoneField

class ParceirosForm(forms.ModelForm):
    nome = forms.CharField(max_length=200)
    endereco = forms.TextInput()
    responsavel = forms.CharField(max_length=100)    
    tel = PhoneField(max_length=12)

    class Meta:
        prefix = 'parceiro'
        model = Parceiros
        fields = ['nome', 'endereco', 'responsavel', 'tel']

0001_initial.py:


from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import phone_field.models
import services.models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Parceiros',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('nome', models.CharField(max_length=200)),
                ('endereco', models.TextField(blank=True, max_length=400)),
                ('responsavel', models.CharField(max_length=100)),
                ('tel', phone_field.models.PhoneField(max_length=12)),
                ('created_at', models.DateTimeField(auto_now=True)),
                ('updated_at', models.DateTimeField(auto_now_add=True)),
                ('ativo', models.BooleanField(default=False)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
...