[英]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.