+ 1

Django save object - best practice?

I have a model (Event): title = models.Charfield() user = mmodels.ForeignKey(django.contrib.auth.models.User) ... and a form for the model. Now I want the user to input "title", but when the form is saved, I want to add "user" by calling: user = request.user. I think there are some ways to do that, but what is "best practice" (or your best practice)? My ideas are: Override form.save()? Check if form.is_valid(), pass the cleaned data to Event.objects.create() and override this method? Create my own save/create method, like my_save(form_data, request)? In forms or in models.py?

9th Jul 2021, 7:27 AM
Fu Foy
Fu Foy - avatar
3 odpowiedzi
+ 1
I found that way simplest. I think we could not implement this in models.py or forms.py because "request.user" is stored in server session and we can't access this in models.py or forms.py. So only way left is that get cleaned_data then verify and then objects.create
10th Jul 2021, 2:41 PM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 1
I am also searching for the solution. But currently I achieved this by using ``` #In views.py model_name.objects.create(user=request.user, title=request.POST['title']) Or model_name(user=request.user, title=request.POST['title']) ``` If you do like this then don't forget to exclude 'user' field in forms.py
10th Jul 2021, 8:29 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 1
I did this: eForm = EventForm(request.POST) if eForm.is_valid(): event = eForm.save(commit=False) if request.user.is_authenticated: event.user = request.user event.save() But I would still like to put this in the form.save() itself. I like your idea. I could get cleaned_data and then objects.create
10th Jul 2021, 12:33 PM
Fu Foy
Fu Foy - avatar