[英]How to add the logged in user's username with django
我正在使用 Django 构建一个基本的博客网站,目前要求作者在制作博客时定义他/她的名字。 但是,我希望站点自动将登录用户的用户名放入模型的author
字段中。
这是我的views.py
( AddPostView
应该是相关的类):
class HomeView(ListView):
model = Post
template_name = 'community.html'
ordering = ['-id']
class ArticleDetailView(DetailView):
model = Post
template_name = 'articles_details.html'
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
#fields = '__all__'
这是我的forms.py
:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','author', 'body', 'image']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
和models.py
:
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, null=True)
#author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(null=True, blank=True, upload_to='images/qpics')
def __str__(self):
return self.title + ' - ' + self.author
def get_absolute_url(self):
return reverse('community')
我确实知道我必须从forms.py
中删除author
,并将其相应地更改为models.py
并在views.py
中编写代码,但我找不到解决我的问题的有效解决方案。 大多数在线答案都是针对基于 class 的视图,对我不起作用。
一点帮助将不胜感激。 谢谢!
不知道为什么您将author
字段注释为 FK,但您可以这样做:
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs['name'] = self.request.user.username
return kwargs
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','author', 'body', 'image']
def __init__(self, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.field['author'].widget.attrs.update({'class': 'form-control',
'value': f'{name}'})
<form method="POST">
{{ form.author }}
</form>
另一种简短的方法是在模板内手动呈现表单输入
<form method="POST">
<input type="text" id="id_author" name="author" maxlength="255" value="{{user.username}}" class="form-control">
</form>
我认为你在正确的轨道上。 您希望您的Post.author成为用户model 的ForeignKey 。 在视图的form_valid()方法中设置此值,以确保在表单呈现期间它不会被不良参与者篡改。
模型.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(null=True, blank=True, upload_to='images/qpics')
def __str__(self):
return self.title + ' - ' + self.author
def get_absolute_url(self):
return reverse('community')
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'author', 'body', 'image']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
# Hide the author field in the form, we'll overwrite it later
'author': forms.HiddenInput(),
'body': forms.Textarea(attrs={'class': 'form-control'}),
}
视图.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def form_valid(self, form):
# Set the form's author to the submitter if the form is valid
form.instance.author = self.request.user
super().form_valid(form)
对于奖励积分,您还可以使用类似的方法在 Django Admin 中设置作者:
管理员.py
@admin.register(Post)
class PostAdmin(admin.ModelAdmin)
form = PostForm
def save_model(self, request, obj, form, change):
obj.author = request.user
super().save_model(request, obj, form, change)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.