Django forms dynamic getting author as a logged in user in model forms

给你一囗甜甜゛ 提交于 2020-07-10 09:26:27

问题


I'm trying to make some forms that will allow users to add some objects, delete them or edit but I've stucked with thing like author of model. Let's say we got model Shot which got field

author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Because I've created custom user model to expand user by some fields that I want, and then we creating modelForm, creating views etc. and finally got form. When we will try to submit this form, it won't add this object submited in form to db because form has no filled field author author which means this field == Null and that's why it won't add this to db. So my question is how to get it dynamic, for example when user with nick "thebestuser" will try to add this modelForm it will work and mark author as "thebestuser"? Ofc I could add to form field author, but it's the worst way in my opinion and every user would be allowed then to add object for example as a another user, let's say user with nick "anothernick" could add form as a user with "thebestuser" which is In my opinion not acceptable.

models.py

from django.db import models
from django.contrib.auth.models import User
from streamers.models import Streamer
from django.conf import settings
from django.utils import timezone


class Shot(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=70)
    url = models.CharField(max_length=100)
    streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE)
    published_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

forms.py

from django import forms
from .models import Shot

class AddShot(forms.ModelForm):
    class Meta:
        model = Shot
        fields = [
            'title',
            'url',
            'streamer',
        ]
views.py
@login_required
def add_shot(request):
    form = AddShot(request.POST or None)
    if form.is_valid():
        form.save()
        instance = form.save(commit=False)
        instance.published_date = request.published_date
        instance.author = request.user
        instance.save()

    context = {
        'form': form
    }

    return render(request, 'shots/add_shot.html', context)

回答1:


You'll need to do it in your view. When you save your form pass commit=False to your save method, add your user, then save the returned instance.

def my_view(request):
  form = AddShot(request.POST)
  instance = form.save(commit=False)
  instance.author = request.user
  instance.save()

Documented here: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method



来源:https://stackoverflow.com/questions/55352836/django-forms-dynamic-getting-author-as-a-logged-in-user-in-model-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!