简体   繁体   English

如何使用 django 添加登录用户的用户名

[英]How to add the logged in user's username with django

I am building a basic blog site with Django which currently asks for the writer to define his/her name when making blog.我正在使用 Django 构建一个基本的博客网站,目前要求作者在制作博客时定义他/她的名字。 However, I would want the site to automatically put in the logged in user's username in the author field of my models.但是,我希望站点自动将登录用户的用户名放入模型的author字段中。

Here's my views.py ( AddPostView should be the relevant class):这是我的views.pyAddPostView应该是相关的类):

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__'

And here's my forms.py :这是我的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'}),
        }

And models.py :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')

I do get that I have to remove the author from forms.py and change it accordingly into models.py and write a code in views.py but i can't find a working solution to my problem.我确实知道我必须从forms.py中删除author ,并将其相应地更改为models.py并在views.py中编写代码,但我找不到解决我的问题的有效解决方案。 Most of the answers online are for class based views and do not work for me.大多数在线答案都是针对基于 class 的视图,对我不起作用。

Little help will be appreciated.一点帮助将不胜感激。 THANKS!谢谢!

not sure why you commented out the author field as FK but you can do it this way:不知道为什么您将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>

another short way is to render form input manually inside template另一种简短的方法是在模板内手动呈现表单输入

<form method="POST">
    <input type="text" id="id_author" name="author" maxlength="255" value="{{user.username}}" class="form-control">
</form>

I think you're on the right track.我认为你在正确的轨道上。 You'll want to have your Post.author be a ForeignKey to the User model.您希望您的Post.author成为用户model 的ForeignKey Set this value in the view's form_valid() method to ensure that it doesn't get tampered with by a bad actor during form presentation.在视图的form_valid()方法中设置此值,以确保在表单呈现期间它不会被不良参与者篡改。

models.py模型.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 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'}),
        }

views.py视图.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)

For bonus points, you can also set the author within Django Admin using a similar approach:对于奖励积分,您还可以使用类似的方法在 Django Admin 中设置作者:

admin.py管理员.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM