Home > Enterprise >  OperationalError at / no such column: accounts_customer.user_id
OperationalError at / no such column: accounts_customer.user_id

Time:10-16

i have been following this tutorial I was going smoothly but i got an error .i am not sure how to resolve it .I added onetoone relationship to the customer with user model.And now got this user. `models.py

enter code here
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User

class customer(models.Model):
    user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
   
    name=models.CharField(max_length=200,null=True)
    phone_no=models.CharField(max_length=200, validators 
    [RegexValidator(r'^\d{1,10}$')],null=True)
    email=models.EmailField(max_length=200,null=True)

    def __str__(self):
        return self.name

class tag(models.Model):
    name=models.CharField(max_length=200,null=True)


    def __str__(self):
        return self.name

class products(models.Model):
   
    categories=[
    ('indoor','indoor'),
    ('outdoor','outdoor')
    ]
    name=models.CharField(max_length=200,null=True)
    price=models.FloatField(null=True)
    manufacturedate=models.DateTimeField(auto_now_add=True,null=True)
    description:models.TextField(null=True)
    categories=models.CharField(max_length=200,null=True,choices=categories)
    tag=models.ManyToManyField(tag)

    def __str__(self):
        return self.name


class order(models.Model):
    
    status=[
        ('pending','pending'),
        ('out of stock','out of stock',),
        ('Delivered',('Delivered'))
    ]
    ordered_date=models.DateTimeField(auto_now_add=True)
    status=models.CharField(max_length=200,null=True,choices=status)
    customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL)
    product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL)

    def __str__(self):
        return self.product.name

I am really confused . I am stuck here for a while.It was all fineuntil i added onetoone relationship.

views.py

enter code here from multiprocessing import context from django.shortcuts import render,redirect from django.contrib.auth.models import Group from .models import * from .forms import CreateCustomer,CreateOrder,CreateUser from .filters import FilterSearch

from django.contrib.auth import logout,login,authenticate
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .decorators import allowed_users,admin_only



def registeruser(request):
    if request.user.is_authenticated:
        return redirect('home')
    else :   
        form=CreateUser()
        if request.method=='POST':
            form=CreateUser(request.POST)
            if form.is_valid():
                user=form.save()
                
                group=Group.objects.get(name='customer')
                user.groups.add(group)

                login(request,user)

                return redirect('home')
        context={'form':form}
        return render(request,'accounts/registeruser.html',context)

    

def loginuser(request):
    if request.user.is_authenticated:
        return redirect('home')
    else :
        if request.method=='POST':
            username=request.POST.get('username')
            password=request.POST.get('password')
            user=authenticate(request,username=username,password=password)
            if user is not None:
                login(request,user)
                return redirect('home')
            else:
                messages.info(request,"Something went wrong!!")
    context={}
    return render(request,'accounts/login.html',context)

@login_required(login_url='login')
def logoutuser(request):
    logout(request)
    return redirect('login')

@login_required(login_url='login')  

@admin_only
def home(request): 
    customers=customer.objects.all()
    orders=order.objects.all()
    total_customers=customers.count()
    total_orders=orders.count()
    delivered=orders.filter(status='Delivered').count()
    pending=orders.filter(status='pending').count()



    context= {'customers':customers,'orders':orders,'total_customers':total_customers,
    'total_orders':total_orders,'delivered':delivered,
    'pending':pending }

    return render(request,'accounts/home.html',context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def userprofile(request):
    return render(request,'accounts/userprofile.html',context)

@login_required(login_url='login')
def product(request):

    return render(request,'accounts/products.html')

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def Customer(request,pk):
    Customer=customer.objects.get(id=pk)
    orders=Customer.order_set.all()
    if request.method=='GET':
        filterset=FilterSearch(request.GET,queryset=orders)
        orders=filterset.qs

    order_count=orders.count()
    context={'Customer':Customer,'orders':orders,'order_count':order_count 
    ,'filterset':filterset}
    return render(request,'accounts/customers.html',context)

@login_required(login_url='login') 
@allowed_users(allowed_roles=['customer'])  
def createcustomer(request):
    form=CreateCustomer()
    if request.method=='POST':
        form=CreateCustomer(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context={'form':form}
    return render(request,'accounts/customerform.html',context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def createorder(request):

    form=CreateOrder()
    if request.method=='POST':
    
        form=CreateOrder(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    context={'form':form}
    return render(request,'accounts/orderform.html',context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def updateOrder(request,pk):
    orders=order.objects.get(id=pk)
    form=CreateOrder(instance=orders)
    if request.method=='POST':
        form=CreateOrder(request.POST,instance=orders)
        if form.is_valid():
            form.save()
            return redirect('home')
    context={'form':form}
    return render(request,'accounts/orderform.html',context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def deleteOrder(request,pk):
    orders=order.objects.get(id=pk)
    if request.method=='POST':
        orders.delete()
        return redirect('home')
    context={'order':orders}

    return render(request,'accounts/deleteorder.html',context)

I would really appreciate your help

urls.py

enter code here
from django.urls import path

from . import views

urlpatterns=[
    path('registeruser/',views.registeruser,name="registeruser"),
    path('login/',views.loginuser,name="login"),
    path('user/',views.userprofile,name='userprofile'),
    path('logout/',views.logoutuser,name="logout"),
    path('',views.home,name="home"),
    path('products/',views.product,name='product'),
    path('customers/<str:pk>/',views.Customer,name='customer'),
    path('Createcustomers/',views.createcustomer,name='createcustomer'),
    path('Createorder/',views.createorder,name='createorder'),
    path('updateorder/<str:pk>/',views.updateOrder,name='updateorder'),
    path('deleteorder/<str:pk>/',views.deleteOrder,name='deleteorder'),
]

CodePudding user response:

Simply you delete all your migration folders and migrate manually by runing below command:

python manage.py makemigrations appname

python manage.py sqlmigrate appname 0001 

python manage.py migrate

Try above command and see if this is solves your error

CodePudding user response:

I understand what is an error. you check id using Customer=customer.objects.get(id=pk) in customer function in views.py.

But you write path('customers/<str:pk>/',views.Customer,name='customer')
in urls.py.

It means you check "Id (integer value)" in your customer function but you pass pk but as a string value. so python consider as a string value not a integer value.

so you should have change "customers/int:pk/" in urls.py file.

then run server and run it.

  • Related