如何从基于类的视图中保存用户到Django模型中?

huangapple go评论56阅读模式
英文:

How do i save the user in django model from class based views

问题

我认为问题出在 save 方法中,你需要在这里保存用户到你的模型中。在函数式视图中,你可以通过 request.user 来获取用户,并将其保存为 post.author。在类视图中,你可以通过 self.request.user 来获取用户。

这是一个修改后的 save 方法的示例:

def save(self, *args, **kwargs):
    instance = super().save(commit=False)
    instance.author = self.request.user
    instance.save()
    return instance

在这个示例中,我们首先调用了父类的 save 方法,将 commit 设置为 False,以便我们可以在保存之前修改实例。然后,我们将 self.request.user 分配给 instance.author,最后保存实例并返回它。

这应该能够解决你在类视图中保存用户的问题。希望这对你有所帮助!

英文:

I'm moving across from function-based views to class-based views but am having some trouble saving the user in my database.

I managed to get it to work (after some trying!) in my function based view:

# 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)

but can't get it to work when doing classed based views.

CreatePostView:

class CreatePostView(CreateView):
    model = Post
    form_class = PostForm
    template_name = "create_post.html"

Post model:

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),))

Post Form:

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()

I think the problem lies in the save method, I don't really understand what I need to do here to save my user in my model. With the function based view I just grabbed the user with request.user and saved it as my post.author.

答案1

得分: 1

你可以重写.form_valid(...) [Django-doc]方法,在表单有效时运行,在表单保存和重定向之前运行:

class CreatePostView(CreateView):
    model = Post
    form_class = PostForm
    template_name = 'create_post.html'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

注意: 您可以使用LoginRequiredMixin mixin [Django-doc]来限制视图只对已认证的用户可见。

英文:

You can override <code>.form_valid(&hellip;)</code>&nbsp;<sup>[Django-doc]</sup> to run when the form is valid, and before the form is saved and a redirect is made:

<pre><code>class CreatePostView(CreateView):
model = Post
form_class = PostForm
template_name = 'create_post.html'

def form_valid(self, form):
    &lt;b&gt;form.instance.author = self.request.user&lt;/b&gt;
    return super().form_valid(form)&lt;/code&gt;&lt;/pre&gt;

> Note: You can limit views to a class-based view to authenticated users with the
> LoginRequiredMixin mixin&nbsp;<sup>[Django-doc]</sup>.

huangapple
  • 本文由 发表于 2023年7月7日 00:39:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定