1

I was wondering about the best way to creating a model and having the request.user auto populate a field.

model.py

class Match(models.Model):
    match_name = models.CharField(max_length=100)
    player = models.CharField(max_length=100, choices=match_game, default=2)
    time_start = models.DateTimeField(blank=True, default=None, null=True)
    match_join = models.ForeignKey(User, default=None, blank=True, null=True)
    match_finished = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('match:details', kwargs={'pk': self.pk})

    def __str__(self):
        return self.match_name

views.py

class MatchCreate(CreateView):
    model = Match
    fields = ['match_name', 'player']

The idea is, when you create a match, you as a user automatically join that match.

C14L
  • 12,153
  • 4
  • 39
  • 52
Hobbs
  • 103
  • 1
  • 7
  • 2
    Possible duplicate of [How to set ForeignKey in CreateView?](http://stackoverflow.com/questions/10382838/how-to-set-foreignkey-in-createview). It's also covered in the [documentation](https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user). – solarissmoke Jun 03 '16 at 06:30
  • @solarissmoke Thanks! i was looking in the wrong part of the docs – Hobbs Jun 03 '16 at 07:11

1 Answers1

2

My python might be rusty, its been more than a year since I worked with Django.

As mentioned in the comments below by Daniel Roseman the request object is already available as a member on the view class.

You only need to grab the user from the request and feed that into the created instance before it is saved. This could be done in form_valid():

def form_valid(form):
    form.instance.match_join = self.request.user
    super(MatchCreate, self).form_valid(form)