Django表单集设置当前用户

发布于 2024-10-25 22:58:55 字数 3195 浏览 1 评论 0原文

这个问题相关,但对其进行扩展 - 我将如何使用这种技术在表单集中?

我想在表单中使用当前登录的用户,但我在表单集中使用该表单。单个表单参考的解决方案是将 request.user 传递给表单并在 init 中处理。如何为表单集中的每个表单添加 kwargs?

我的代码中的示例:

在 forms.py 中

class NewStudentForm (forms.Form):
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
        error_message = _("This value must contain only letters, numbers and underscores."))
    first_name = forms.CharField(label=_('first name'), max_length=30 )
    last_name = forms.CharField(label=_('last name'), max_length=30, )
    email = forms.EmailField(label=_('e-mail address') )
    password = forms.CharField(label=_('password'), max_length=64, )

    class Meta:
        model = User
        fields = ("username","first_name", "last_name", "email", "password")

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(NewStudentForm, self).__init__(*args, **kwargs)


    def save(self, commit=True):
        user = super(NewStudentForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
            profile = Profile.objects.create_profile(user)
            profile.activiation_key = profile.ACTIVATED_KEY
            profile.authorized = True
            profile.save()
            user.is_active=True
            user.save()
            student = models.Student()
            student.user = user
            student.teacher = self._user
            student.plaintext_pwd = self.cleaned_data["password"]
            student.save()
        return UserWarning

,然后在views.py 中

@login_required
def new_student(request):
    from django.forms.formsets import formset_factory
    try:
        if request.method == 'GET':
            newStudentFormset = formset_factory(forms.NewStudentForm, extra=2)
            formset = newStudentFormset()
            return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username })
        elif request.method == 'POST':
            if LOGIN_FORM_KEY in request.POST:
                return _handle_login(request)
            data = request.POST.copy()
            newStudentFormset = formset_factory(forms.NewStudentForm)
            formset = newStudentFormset(data) ### Pass current user to formset? ###
            if formset.is_valid():
                formset.save()
                request.user.message_set.create(message="Save successful.")
                return shortcuts.redirect(student)
            else:
                return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username, 'error_message':formset.errors})
        return http.HttpResponseNotAllowed(['GET', 'POST'])
    except models.Student.DoesNotExist:
        return http.HttpResponseNotFound('<h1>Requested Student not found</h1>')

Related to this question, but expanding on it - How would I use this technique in a formset?

I'd like to use the current logged in user in a form, but I'm using the form in a formset. The referenced solution for a single form is to pass request.user to the form and process in init. How do I add to the kwargs for each form in the formset?

Example in my code:

in forms.py

class NewStudentForm (forms.Form):
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+

then in views.py

@login_required
def new_student(request):
    from django.forms.formsets import formset_factory
    try:
        if request.method == 'GET':
            newStudentFormset = formset_factory(forms.NewStudentForm, extra=2)
            formset = newStudentFormset()
            return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username })
        elif request.method == 'POST':
            if LOGIN_FORM_KEY in request.POST:
                return _handle_login(request)
            data = request.POST.copy()
            newStudentFormset = formset_factory(forms.NewStudentForm)
            formset = newStudentFormset(data) ### Pass current user to formset? ###
            if formset.is_valid():
                formset.save()
                request.user.message_set.create(message="Save successful.")
                return shortcuts.redirect(student)
            else:
                return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username, 'error_message':formset.errors})
        return http.HttpResponseNotAllowed(['GET', 'POST'])
    except models.Student.DoesNotExist:
        return http.HttpResponseNotFound('<h1>Requested Student not found</h1>')
, help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), error_message = _("This value must contain only letters, numbers and underscores.")) first_name = forms.CharField(label=_('first name'), max_length=30 ) last_name = forms.CharField(label=_('last name'), max_length=30, ) email = forms.EmailField(label=_('e-mail address') ) password = forms.CharField(label=_('password'), max_length=64, ) class Meta: model = User fields = ("username","first_name", "last_name", "email", "password") def __init__(self, *args, **kwargs): self._user = kwargs.pop('user') super(NewStudentForm, self).__init__(*args, **kwargs) def save(self, commit=True): user = super(NewStudentForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() profile = Profile.objects.create_profile(user) profile.activiation_key = profile.ACTIVATED_KEY profile.authorized = True profile.save() user.is_active=True user.save() student = models.Student() student.user = user student.teacher = self._user student.plaintext_pwd = self.cleaned_data["password"] student.save() return UserWarning

then in views.py

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

孤独陪着我 2024-11-01 22:58:55

通过添加扩展BaseFormSet 的类,您可以添加自定义代码以将参数传递到表单。

forms.py 中:

class NewStudentFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(NewStudentFormSet, self).__init__(*args, **kwargs)

    def _construct_forms(self): 
        self.forms = []
        for i in xrange(self.total_form_count()):
            self.forms.append(self._construct_form(i, user=self.user))

然后在 views.py 中:

# ...

data = request.POST.copy()
newStudentFormset = formset_factory(forms.NewStudentForm, formset=forms.NewStudentFormSet)
formset = newStudentFormset(data, user=request.user)

# ...

感谢 Ashok Raavi

By adding a class that extends BaseFormSet you can add custom code to pass a parameter to the form.

in forms.py:

class NewStudentFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(NewStudentFormSet, self).__init__(*args, **kwargs)

    def _construct_forms(self): 
        self.forms = []
        for i in xrange(self.total_form_count()):
            self.forms.append(self._construct_form(i, user=self.user))

Then in views.py:

# ...

data = request.POST.copy()
newStudentFormset = formset_factory(forms.NewStudentForm, formset=forms.NewStudentFormSet)
formset = newStudentFormset(data, user=request.user)

# ...

Thanks to Ashok Raavi.

舂唻埖巳落 2024-11-01 22:58:55

我宁愿直接在视图中迭代表单:

for form in formset.forms:
    form.user = request.user
    formset.save()
  • 它避免创建不必要的 BaseFormSet
  • 它更干净

I rather to iterate forms directly in the view:

for form in formset.forms:
    form.user = request.user
    formset.save()
  • It avoid creating unecessary BaseFormSet
  • It is cleaner
神经暖 2024-11-01 22:58:55

基于 Paulo Check 的答案(这对我的案例并没有真正起作用)。

我喜欢不编写自定义 BaseFormSet 继承类的想法。

if formset.is_valid():
    new_instances = formset.save(commit=False)
    for new_instance in new_instances:
        new_instance.user = request.user
        new_instance.save()

Based on Paulo Cheque answer (which didn't really work for my case).

I loved the idea of not writing a custom BaseFormSet inherited class.

if formset.is_valid():
    new_instances = formset.save(commit=False)
    for new_instance in new_instances:
        new_instance.user = request.user
        new_instance.save()
自控 2024-11-01 22:58:55

我尝试了 selfsimilar 的解决方案,但 BaseFormSet 在我的 Django 1.6 中不起作用。

我按照以下步骤操作: https://code.djangoproject.com/ticket/17478 和对我有用的方法是:

class NewStudentFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            self.user = kwargs.pop('user',None)
            super(NewStudentFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False

        def _construct_forms(self):
            if hasattr(self,"_forms"):
                return self._forms
            self._forms = []
            for i in xrange(self.total_form_count()):
                self._forms.append(self._construct_form(i, user=self.user))

            return self._forms

        forms = property(_construct_forms)

I tried the solution of selfsimilar but the BaseFormSet didn't work in my Django 1.6.

I followed the steps in: https://code.djangoproject.com/ticket/17478 and the way that worked for me is:

class NewStudentFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            self.user = kwargs.pop('user',None)
            super(NewStudentFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False

        def _construct_forms(self):
            if hasattr(self,"_forms"):
                return self._forms
            self._forms = []
            for i in xrange(self.total_form_count()):
                self._forms.append(self._construct_form(i, user=self.user))

            return self._forms

        forms = property(_construct_forms)
玩套路吗 2024-11-01 22:58:55

这是关于将表单参数传递到表单集的类似问题:

Django Passing Custom FormParameters to Formset

我个人而言,我喜欢关于在函数中动态构建表单类的第二个答案,因为它实现起来非常快并且易于理解。

Here is a similar question about passing form parameters to a formset:

Django Passing Custom Form Parameters to Formset

Personally, I like the second answer on there about building the form class dynamically in a function because it is very fast to implement and easy to understand.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文