Django表单以模型形式作为登录用户动态获取作者 [英] Django forms dynamic getting author as a logged in user in model forms

查看:85
本文介绍了Django表单以模型形式作为登录用户动态获取作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一些表格,允许用户添加,删除或编辑对象,但是我一直坚持使用模型作者之类的东西。假设我们有一个模型Shot,其中有字段

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)

因为我已经创建了自定义用户模型,以便按需要的某些字段扩展用户,然后我们创建modelForm,创建视图等,最后得到表单。当我们尝试提交此表单时,它不会将此表单中提交的对象添加到db中,因为表单没有填写的字段作者作者,这意味着该字段== Null,这就是为什么它不会将其添加到db中的原因。所以我的问题是如何使其动态化,例如,当昵称为 thebestuser的用户尝试添加此modelForm时,它将起作用并将作者标记为 thebestuser?我可以添加到表单域作者中,但是我认为这是最糟糕的方式,每个用户都可以随后添加对象,例如,以另一个用户的身份添加,例如,昵称为 anothernick的用户可以添加表单为

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

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)


推荐答案

您需要o在您看来。将表单传递 commit = False 保存到保存方法时,添加用户,然后保存返回的实例。

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()

此处记录: https://docs.djangoproject.com/zh-CN/2.1/topics/表格/模型表格/#the-save-method

这篇关于Django表单以模型形式作为登录用户动态获取作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆