I am building a Django site to share code for Python games, but I'm running into trouble associating each game with a specific user. I'm trying to do this by using the user as the ForeignKey
, which I think is the right approach, but I can't get the user to actually get inserted into the database without using some weird hack (like passing the user as a string into a hidden user
field, which is totally insecure and causes other issues.)
My Game
class looks like this:
class Game(models.Model):
user = models.ForeignKey(User, blank=True)
title = models.CharField(max_length=256)
image = models.ImageField(upload_to='games')
description = models.CharField(max_length=256)
requirements = models.CharField(max_length=256)
code = models.CharField(max_length=256000)
def __unicode__(self):
return self.title
The form for adding a game:
class GameForm(forms.ModelForm):
image = forms.ImageField(required=False)
code = forms.CharField(widget=PagedownWidget(show_preview=True))
class Meta:
model = Game
fields = ('user','title','image','description','requirements','code')
User.game = property(lambda u: Game.objects.get_or_create(user=u)[0])
I create a custom version of this form in my addgame.html
template:
<form action="/userprofile/addGame/" method="post">{% csrf_token %}
{% for field in form.visible_fields %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}
<br>
{{ field }}
<br><br>
</div>
{% endfor %}
<input type="submit" value="Save">
</form>
My View looks like this:
@login_required
def add_game(request):
user = request.user
error_message = None
if request.method == 'POST':
form = GameForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.uploader = request.user
form.save()
return HttpResponseRedirect('/userprofile')
else:
error_message = "Invalid Input"
else:
form = GameForm()
args = {}
args.update(csrf(request))
args['user'] = user
args['form'] = form
args['error_message'] = error_message
return render_to_response('addgame.html', args)
However, I get the following error:
Cannot assign None: "Game.user" does not allow null values.
I realize that a User
instance has not been passed into the form, thus I am getting a 'shouldn't be null' error, but I have no idea how to properly pass in the User
instance to the form. I've looked at several questions on this exact issue, such as this, but I still haven't been able to get User
successfully passed in to the form.