I have a model called Event
in my Django project:
from django.db import models
from django.contrib.auth.models import User
class Event(models.Model):
organizer = models.CharField(blank=False, max_length=200) # TODO
author = models.ForeignKey(User)
This model also has a form attached:
from django import forms from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['organizer',
]
(there are other fields, but they are irrelevant)
What is the best practice if I want to automatically populate the author
field? At the moment, the view that saves the model saves it like so:
def event_created(request):
form = EventForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.save()
This works, but I am worried because it means that when some other view will save this, it will have to jump through the same loop. Is there some way to tell the model itself "when I save you, set user to current user"? The problem is that the model does not know which request is triggering its save, and if I provide the request from the view, that, again, seems like code duplication...