Django - 为什么我得到这个IntegrityError:NOT Null约束失败:restaurants_restaurantlocation.owner_id?

时间:2017-10-20 18:26:45

标签: python django django-models django-forms django-views

我正在努力建立一个人们可以根据他们的挑剔找到餐馆和菜单项目的网站。目前我正在尝试这样做,所以当我通过表格向餐馆添加一些内容时,我将其与用户相关联,但当我提交表单时,我收到此错误: 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/"

如果您需要任何其他代码,请询问,谢谢

1 个答案:

答案 0 :(得分:1)

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

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

默认情况下,这不能为空(这是“非空约束”的含义)。事实上,您的表单看起来没有任何东西可以填写餐馆老板,因此当您尝试提交时,您将收到数据库约束错误。

  

“这是一个无效的名字。你这个顽固的男孩。”

对您的用户说不是一件好事。