[英]How to save the form with posted user in the django models database
I have created the login,authenticate,logout system, now I want to add a post functionality that saves the data in the Tweet model.我已经创建了登录、验证、注销系统,现在我想添加一个帖子功能,将数据保存在 Tweet model 中。
views.py视图.py
from .models import NameForm
from django.shortcuts import render, redirect, get_object_or_404
def home(request):
if request.method == "POST":
form = NameForm(initial={'tweetedby':request.user.id}, datarequest.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = NameForm()
return render(request,'home.html',{"form":form} )
i am using the inbuild forms framework for the post request我正在使用内置 forms 框架进行发布请求
home.html主页.html
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
forms.html forms.html
from django.forms import ModelForm
from django import forms
from .models import Tweet
class NameForm(ModelForm):
tweet = forms.CharField(label="tweet",max_length="50")
def clean_tweet(self):
data = self.cleaned_data["tweet"]
return data
class Meta:
model = Tweet
fields = ("tweet",)
when the user tweets i am getting the tweet and and the datetime form the tweet.but i want to access the tweeted_by user from the post request,当用户发推文时,我得到推文和推文的日期时间。但我想从发布请求中访问 tweeted_by 用户,
model.py model.py
from django.db import models
from django.contrib.auth.models import User
class Tweet(models.Model):
tweet = models.CharField(max_length=50)
tweetedtime = models.DateTimeField(auto_now_add=True)
tweetedby = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.tweet
I get the error我得到错误
null value in column "tweetedby_id" violates not-null constraint DETAIL: Failing row contains (12, hi, 2020-06-07 09:55:20.482599+00, null) “tweetedby_id”列中的 null 值违反非空约束细节:失败行包含 (12, hi, 2020-06-07 09:55:20.482599+00, null)
The tweeted_by coloumb gets the null value without the USER id tweeted_by coloumb 获取没有 USER id 的 null 值
Simply set this in the view:只需在视图中设置:
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
if request.method == 'POST':
form = NameForm(request.POST, request.FILES)
if form.is_valid():
form.instance.tweetedby = request.user # set user
form.save()
return redirect('home')
else:
form = NameForm()
return render(request,'home.html', {'form':form})
The form should not contain any tweetedby
field:表单不应包含任何tweetedby
字段:
class NameForm(ModelForm):
tweet = forms.CharField(label='tweet', max_length=50)
class Meta:
model = Tweet
fields = ('tweet',)
in the model you can make the tweetedby
field non-editable,, such that it does not appear by default in the form:在 model 中,您可以使tweetedby
字段不可编辑,这样它就不会默认出现在表单中:
from django.conf import settings
from django.db import models
class Tweet(models.Model):
tweet = models.CharField(max_length=50)
tweetedtime = models.DateTimeField(auto_now_add=True)
tweetedby = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
editable=False
)
A tweet has a maximum length of 280 characters, so perhaps 50 is too low.一条推文的最大长度为 280 个字符,因此 50 个字符可能太短了。
Note : You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc] .注意:您可以使用@login_required
装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.