如何将表单中的用户字段设置为当前登录的用户? [英] How do I set user field in form to the currently logged in user?

查看:76
本文介绍了如何将表单中的用户字段设置为当前登录的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个选举信息应用程序,我想允许当前登录的用户能够声明自己并且只有自己是选举中的候选人。

I'm making an election information app, and I want to allow the currently logged-in user to be able to declare himself and only himself as a candidate in an election.

我正在使用Django的内置ModelForm和CreateView。我的问题是,运行Office表单(即创建候选者表单)允许用户在数据库中选择任何个用户作为候选者。

I'm using Django's built-in ModelForm and CreateView. My problem is that the Run for Office form (in other words, the 'create candidate' form) allows the user to select any user in the database to make a candidate.

我希望运行Office中的用户字段自动设置为当前登录的用户,并且该值被隐藏,因此已登录用户无法将字段的值更改为其他人。

I want the user field in the Run for Office to be automatically set to the currently logged-in user, and for this value to be hidden, so the logged-in user cannot change the value of the field to someone else.

views.py

class CandidateCreateView(CreateView):
    model = Candidate
    form_class = CandidateForm
    template_name = 'candidate_create.html'

    def form_valid(self, form):
        f = form.save(commit=False)
        f.save()
        return super(CandidateCreateView, self).form_valid(form)

forms.py

class CandidateForm(forms.ModelForm):
    class Meta:
        model = Candidate

models.py

class Candidate(models.Model):
    user = models.ForeignKey(UserProfile)
    office = models.ForeignKey(Office)
    election = models.ForeignKey(Election)
    description = models.TextField()

    def __unicode__(self):
        return unicode(self.user)

    def get_absolute_url(self):
        return reverse('candidate_detail', kwargs={'pk': str(self.id)})


推荐答案


  1. 从呈现的表单中删除用户字段(使用排除字段 https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#selecting-the-fields-to-使用

class CandidateForm(forms.ModelForm):
    class Meta:
        model = Candidate
        exclude = ["user"]


  • 查找用户个人资料并设置

  • Find user profile and set user field in the create view.

    class CandidateCreateView(CreateView):
        ...
        def form_valid(self, form):
            candidate = form.save(commit=False)
            candidate.user = UserProfile.objects.get(user=self.request.user)  # use your own profile here
            candidate.save()
            return HttpResponseRedirect(self.get_success_url())
    


  • 这篇关于如何将表单中的用户字段设置为当前登录的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆