Reputation: 45
I'm trying to make a web app that allows you to track Spikeball games in a blog like style.
I've tried setting the author of each game to be the current user then delegating with super to save the form when it's submitted but I'm still getting:
IntegrityError at /game/new/ NOT NULL constraint failed: spike_stats_game.creator_id
Here's my models:
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
Here's my Views:
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'})
Even with this fixed, I should still be getting a url error but I can't get past this roadblock. Apologies if any formatting/information or anything is wrong, I'm fairly new to Python and Stack Overflow in general.
Upvotes: 0
Views: 37
Reputation: 12869
You need to set the creator
value but it looks like you're trying to define author
.
To do this in a form_valid
do;
def form_valid(self, form):
game = form.save(commit=False)
game.creator = self.request.user
game.save()
# redirect or whatever you need to do
Upvotes: 2