快速初學者 Django 問題,因為我無法找到直接解決我所追求的問題的答案,或者沒有添加一堆我不需要的過于復雜的功能及其答案。
我有一個基本的博客設定,帶有用戶及其相關帖子的模型,以及用于創建新帖子的表單。然而,我想要的是表單上的“作者”欄位自動填充當前登錄的用戶,而不是所有注冊用戶的下拉串列。我的型號:
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255)
site = models.CharField(max_length=255)
def __str__(self):
return self.title ' | ' str(self.author)
def get_absolute_url(self):
return reverse('home')
我的表格:
class PostForm(forms.ModelForm):
class Meta:
model=Post
fields = ('title', 'author', 'category', 'site', 'body')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.Select(attrs={'class': 'form-control' ,'readonly': 'readonly'}),
'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}),
'site': forms.Select(choices=site_choice_list,attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'})
}
我的觀點:
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
重申一下,我只是希望帖子中的“作者”欄位是只讀的,并填充當前登錄的用戶。而不是用戶能夠從用戶串列中進行選擇。
在此先感謝您,如果我能提供任何其他幫助您幫助我,請告訴我:)
uj5u.com熱心網友回復:
您應該禁用該欄位,而不僅僅是readonly向小部件添加屬性,因為“黑客”可以偽造將作者設定為另一個用戶的惡意 HTTP 請求:
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['author'].disabled = True
class Meta:
model = Post
fields = ('title', 'author', 'category', 'site', 'body')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'author': forms.Select(attrs={'class': 'form-control'}),
'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}),
'site': forms.Select(choices=site_choice_list,attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'})
}
然后我們可以在視圖中使用這個表單:
from django.contrib.auth.mixins import LoginRequiredMixin
class AddPostView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def get_initial(self):
return {'author': request.user}
的LoginRequiredMixin混入[Django的DOC]保證只有已登錄的用戶可以看到(和互動含)圖。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401845.html
標籤:Python 姜戈 django 模型 django-forms 博客
上一篇:如何一次讀取一個空格分隔的值?
下一篇:在用戶輸入后重復for回圈?
