我正在从基于函数的视图转移到基于类的视图,但在数据库中保存user
时遇到了一些问题.
我设法让它在我的基于函数的视图中工作(经过一些try !):
# def create_post(request, *args, **kwargs): #function based view for creating a post - this works
# if request.method == "POST":
# form = PostForm(request.POST)
# if form.is_valid():
# post = form.save(commit=False)
# post.author = request.user
# post.save()
# messages.success(request, "Post submitted!")
# form = PostForm()
# else:
# form = PostForm()
#
# context = {
# 'form': form
# }
# return render(request, "create_post.html", context)
但在执行基于类的视图时无法使其工作.
创建后视图:
class CreatePostView(CreateView):
model = Post
form_class = PostForm
template_name = "create_post.html"
POST模型:
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True)
title = models.CharField(max_length=100)
slug = models.SlugField()
description = models.TextField(max_length=500)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:post_detail", args=(str(self.id),))
张贴表格:
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['title'].label = ""
self.fields['description'].label = ""
class Meta:
model = Post
fields = ['title', 'description']
widgets = {
'title': forms.TextInput(attrs={'class': "title w-full bg-gray-100 border border-gray-300 p-2 mb-4 outline-none",
'spellcheck': "false", 'placeholder': "Title", 'type': "text"}),
'description': forms.Textarea(attrs={'class': "description w-full bg-gray-100 sec p-3 h-60 border border-gray-300 outline-none",
'spellcheck': "false", 'placeholder': "Describe everything about this post here", 'type': "text"}),
}
def save(self, *args, **kwargs):
obj = form.save(commit=False)
obj.user = request.user
obj.save()
我认为问题出在save
方法中,我真的不明白我需要在这里做些什么才能将我的用户保存在我的模型中.使用基于函数的视图,我只需抓取用户的request.user
并将其保存为我的post.author
.