簡體   English   中英

Django-為什么會出現此IntegrityError:NOT Null約束失敗:Restaurants_restaurantlocation.owner_id?

[英]Django - Why am I getting this IntegrityError: NOT Null constraint failed: restaurants_restaurantlocation.owner_id?

我正在嘗試建立一個網站,使人們可以根據他們的選擇來查找餐館和菜單項。 當前,我正在嘗試這樣做,因此當我通過表單將其添加到餐廳時,將其與用戶相關聯,但是當我提交表單時,出現此錯誤:IntegrityError NOT Null約束失敗:Restaurants_restaurantlocation.owner_id

這是我的forms.py:

from django import forms

from .models import RestaurantLocation

from .validators import validate_category

class RestaurantCreateForm(forms.Form):
name            = forms.CharField()
location        = forms.CharField(required = False)
category        = forms.CharField(required = False)


def clean_name(self):
    name = self.cleaned_data.get("name")
    if name == "Hello":
        raise forms.ValidationError("This is an invalid name. You stubid boy.")
    return name



class RestaurantLocationCreateForm(forms.ModelForm):
#email = forms.EmailField()
#category = forms.CharField(validators = [validate_category], required = False)
class Meta:
    model = RestaurantLocation
    fields = [
        "name",
        "location",
        "category"
    ]

def clean_name(self):
    name = self.cleaned_data.get("name")
    if name == "Hello":
        raise forms.ValidationError("This is an invalid name. You stubid boy.")
    return name

我的models.py:

from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save

from .utils import unique_slug_generator

from .validators import validate_category

# Create your models here.

User = settings.AUTH_USER_MODEL

class RestaurantLocation(models.Model):
    owner           = models.ForeignKey(User)
    name            = models.CharField(max_length=120)
    location        = models.CharField(max_length=120, null=True, blank=True)
    category        = models.CharField(max_length=120, null=True, blank=True, validators= [validate_category])
    slug            = models.SlugField(null=True, blank=True)
    timestamp       = models.DateTimeField(auto_now_add=True)
    updated         = models.DateTimeField(auto_now=True)
    def __str__(self):
    return self.name


@property
def title(self):
    return self.name #obj.title
def rl_pre_save_reciever(sender, instance, *args, **kwargs):
instance.category = instance.category.capitalize()
if not instance.slug:
    instance.slug = unique_slug_generator(instance)
pre_save.connect(rl_pre_save_reciever, sender=RestaurantLocation)

我的views.py:

from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect 
from django.shortcuts import render, get_object_or_404
from django.views import View 
from django.views.generic import TemplateView, ListView, DetailView, CreateView
from django.utils.datastructures import MultiValueDictKeyError

from .forms import RestaurantCreateForm, RestaurantLocationCreateForm

from .models import RestaurantLocation
# Create your views here

def restaurant_createview(request):
    form = RestaurantLocationCreateForm(request.POST or None)
    errors = None
    if form.is_valid():
        # customise
        # like a pre save    
        form.save()
        # like a post save
        return HttpResponseRedirect("/restaurants/")
    if form.errors:
        errors = form.errors

    template_name = "restaurants/form.html"
    context = {"form" : form, "errors" : errors}
    return render(request, template_name, context)

def restaurant_listview(request):
    template_name = "restaurants/restaurants_list.html"
    queryset = RestaurantLocation.objects.all()
    context = {
        "object_list": queryset
    }
    return render(request, template_name, context)

class RestaurantListView(ListView):
    def get_queryset(self):
        slug = self.kwargs.get("slug")
        if slug:
            queryset = RestaurantLocation.objects.filter(
                Q(category__iexact = slug) |
                Q(category__icontains = slug)
            )
       else:
            queryset = RestaurantLocation.objects.all()
       return queryset 

class RestaurantDetailView(DetailView):
    queryset = RestaurantLocation.objects.all() 


class RestaurantCreateView(CreateView):
    form_class = RestaurantLocationCreateForm
    template_name = "restaurants/form.html"
    success_url = "/restaurants/"

如果您需要任何其他代碼,請詢問,謝謝

查看您的RestaurantLocation模型,您在User表中有一個外鍵:

class RestaurantLocation(models.Model):
    owner = models.ForeignKey(User)

默認情況下,它不能為空(這就是“非空約束”的含義)。 確實看起來您的表單沒有做任何事情來填補餐館老板,因此,當您嘗試提交時,您將收到數據庫約束錯誤。

“這是一個無效的名字。你這個笨蛋。”

對您的用戶說的不是很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM