Reputation: 111
I'm new to django. I'm trying to create a sports betting game as my first django app. I have form, using which I'm able to save home goals and away goals for particular game to database, but I can't find a way to insert a username there. Hope you can help!
Here is my view:
@login_required
def group_games(request, groupname):
games = Match.objects.filter(groupname=groupname)
template = loader.get_template('C:\djangoenvs\\typer\\typer\\templates\group_games.html')
username = User.get_username()
for game in games:
game_id = get_object_or_404(Match, pk=game)
form = BetForm(request.POST or None)
if form.is_valid():
print ('valid form')
form.save()
else:
print ('invalid form')
print (BetForm.errors)
context = {
'games': games,
'groupname': groupname,
'form': form,
}
User.get_username() raises the following error:
get_username() missing 1 required positional argument: 'self'
I tried to change it to User.get_username(self) but then:
name 'self' is not defined
Thanks for every answer!
Upvotes: 0
Views: 1409
Reputation: 5496
User.get_username()
User
represents the complete table, not the record. This is why you get an error.
So remove:
username = User.get_username()
A user might be able to change their username in your application, you can save a foreign key to the user instead. When you save the form do this:
if form.is_valid():
print ('valid form')
bet = form.save(commit=False) # the bet isn't saved just yet
bet.user = request.user # you add the user here
print bet.user.username
bet.save() # finally save the bet in the database
In your Bet model, you need to add a field to record the user. For example:
class Bet(models.Model):
...
user = models.ForeignKey(to=User, related_name="bets", blank=True, null=True)
...
Upvotes: 1