我正在尝试制作一个网络应用程序,使您可以在博客(如样式)中跟踪Spikeball游戏。
我尝试将每个游戏的作者设置为当前用户,然后委托super来保存表单,但提交后仍然存在:
/ game / new /中的IntegrityError NOT NULL约束失败:spike_stats_game.creator_id
这是我的模特:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Game(models.Model):
game = models.CharField(max_length=100, blank=True,null=True)
score = models.CharField(max_length=10, blank=True,null=True)
winner = models.CharField(max_length=20, default=None, blank=True,null=True)
date_played = models.DateField(default=timezone.now)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
player1 = models.CharField(max_length=20, blank=True,null=True)
player2 = models.CharField(max_length=20, blank=True,null=True)
player3 = models.CharField(max_length=20, blank=True,null=True)
player4 = models.CharField(max_length=20, blank=True,null=True)
def __str__(self):
return self.game
这是我的观点
from django.shortcuts import render
from django.views.generic import (
ListView,
DetailView,
CreateView
)
from .models import Game
def home(request):
context = {
'games': Game.objects.all()
}
return render(request, 'spike_stats/home.html', context)
class GameListView(ListView):
model = Game
template_name = 'spike_stats/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'games'
ordering = ['-date_played'] # minus sign orders from newest to oldest
class GameDetailView(DetailView):
model = Game
class GameCreateView(CreateView):
model = Game
fields = ['game', 'score', 'winner',
'player1', 'player2', 'player3', 'player4']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def about(request):
return render(request, 'spike_stats/about.html',
{'game': 'Game 1 about'})
即使已解决此问题,我仍然应该遇到url错误,但无法克服此障碍。抱歉,如果有任何格式/信息或任何错误,我一般对Python和Stack Overflow还是陌生的。
答案 0 :(得分:2)
您需要设置creator
值,但是您似乎正在尝试定义author
。
要在form_valid
中进行;
def form_valid(self, form):
game = form.save(commit=False)
game.creator = self.request.user
game.save()
# redirect or whatever you need to do