【问题标题】:How to update data in specific form field in UpdateView Django如何在 UpdateView Django 中更新特定表单字段中的数据
【发布时间】:2020-04-08 18:39:54
【问题描述】:

由于我是 Django 新手,如何更新 django 中的特定表单字段?当我在模板中执行{{ form.as_p }} 时,它可以工作,但是有些表单字段不需要在另一个表单上显示,但有些需要。所以我所做的就是将它们称为仅在某些表单上更新所需的填充。

这是我的更新视图:

class SettingsProfileView(UpdateView):
    model               = UserInfoModel
    template_name       = 'site/views/settingsprofile.html'
    form_class          = UserInfoForm
    success_url         = '/'

    def get_object(self, queryset = None):
        if queryset is None:
            queryset = self.get_queryset()
        return get_object_or_404(queryset, users_id = self.kwargs['pk'])

此类通用视图实际上在 {{ form.as_p }} 上工作 但是有些表单字段我不想显示在该表单上。

对于那些想要查看我的 html 模板的人: 在这里 ->

{% extends 'roots/site.html' %}

{% block content %}
<div class="card col-lg-12">
    <div class="card-body">
        <div class="card-title"><h3>Personal Information Settings</h3></div>
        <form action="" method="post">
            {% csrf_token %}
            <div class="form-group">
                {{ form.firstname.label_tag }}
                {{ form.firstname }}
            </div>
            <div class="form-group">
                {{ form.lastname.label_tag }}
                {{ form.lastname }}
            </div>
            <h4>Birthdate: </h4>
            <table>
                <tr>
                    <td>{{ form.birthdate_month.label_tag }}</td>
                    <td>{{ form.birthdate_day.label_tag }}</td>
                    <td>{{ form.birthdate_year.label_tag }}</td>
                </tr>
                <tr>
                    <td>{{ form.birthdate_month }}</td>
                    <td>{{ form.birthdate_day }}</td>
                    <td>{{ form.birthdate_year }}</td>
                </tr>
            </table>
            <div class="form-group">
                {{ form.gender.label_tag }}
                {{ form.gender }}
            </div>
            <button type="submit" class="btn btn-primary col-lg-12">Update</button>
        </form>
    </div>
</div>
{% endblock %}

所以我的表格是:

class UserInfoForm(forms.ModelForm):
    year  = {}
    days  = {}
    month = {
        '': '---------',
        'Jan': 'January', 'Feb': 'February', 'Mar': 'March',
        'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July',
        'Aug': 'August', 'Sep': 'September', 'Oct': 'October',
        'Nov': 'November', 'Dec': 'December'
    }
    gender = {
        'Male': 'Male', 'Female': 'Female',
        'Not Specify': 'Not Specify'
    }

    year[''] = '---------'
    days[''] = '---------'

    from datetime import datetime

    for i in range((int(datetime.now().strftime('%Y'))), (1920 - 1), -1):
        year[i] = i

    for i in range(1, (31 + 1)):
        if i < 10:
            days[f'0{i}'] = f'0{i}'
        else:
            days[i] = i

    password = forms.CharField(label = 'Password', widget = forms.PasswordInput(
        attrs = {
            'id': 'id_signup_password',
            'class': 'form-control',
            'placeholder': 'Password'
        }
    ), required = True)
    email = forms.EmailField(label = 'Email', widget = forms.EmailInput(
        attrs = {
            'id': 'id_signup_email',
            'class': 'form-control',
            'placeholder': 'Email',
            'autocomplete': 'off'
        }
    ), required = True)
    firstname = forms.CharField(label = 'Firstname', widget = forms.TextInput(
        attrs = {
            'id': 'id_signup_firstname',
            'class': 'form-control',
            'placeholder': 'Firstname',
            'autocomplete': 'off'
        }
    ), required = True)
    lastname = forms.CharField(label = 'Lastname', widget = forms.TextInput(
        attrs = {
            'id': 'id_signup_lastname',
            'class': 'form-control',
            'placeholder': 'Lastname',
            'autocomplete': 'off'
        }
    ), required = True)
    gender = forms.ChoiceField(label = 'Gender', widget = forms.Select(
        attrs = {
            'id': 'id_signup_gender',
            'class': 'form-control',
        }
    ), choices = list(gender.items()), required = False)
    birthdate_year = forms.ChoiceField(label = 'Year', widget = forms.Select(
        attrs = {
            'id': 'id_signup_birthyear',
            'class': 'form-control',
        }
    ), choices = list(year.items()), required = True)
    birthdate_day = forms.ChoiceField(label = 'Day', widget = forms.Select(
        attrs = {
            'id': 'id_signup_day',
            'class': 'form-control',
        }
    ), choices = list(days.items()), required = True)
    birthdate_month = forms.ChoiceField(label = 'Month', widget = forms.Select(
        attrs = {
            'id': 'id_signup_month',
            'class': 'form-control',
        }
    ), choices = list(month.items()), required = True)

    class Meta:
        model   = UserInfoModel
        fields  = ['firstname', 'lastname', 'gender', 'birthdate_year', 'birthdate_month', 'birthdate_day']

我只是不想在用户更新个人信息时使用/显示emailpassword

【问题讨论】:

    标签: django


    【解决方案1】:

    在您的UserInfoForm 中,您可以使用字段指定您想要的字段。例如:

    class UserInfoForm(models.ModelForm):
        class Meta:
            model = UserInfoModel
            fields = ('first_name', 'last_name', 'birthdate', 'gender')

    因此它不会定义其他字段。此外,如果用户使用额外的键值对创建恶意 POST 请求,则表单将不会更新未在表单中列出的请求。

    【讨论】:

    • 我的表单已经有一个类元,并且已经定义了这些字段,但是当我在模板视图上执行{{ form.as_p }} 时,它一直显示其他字段。好的说清楚,这个UserInfoForm 有用户名和密码字段,当用户想要更新他们的个人资料信息时,我不希望它们被包括在内,这就是为什么我正在寻找关于如何不包括的解决方案模板上的那些字段,只需更新必要的字段。
    • @KimNicoleSabordo:但是如果不在模板上渲染它,它将无法工作,因为 POST 请求不会将此数据传递给表单,因此表单将无效。关键是表单需要知道哪些字段存在,哪些存在。如果你在其他地方使用这个表单,你可以多写一个UserInfoForm(例如UpdateUserInfoForm,从而指定不同的字段)。
    • 所以这意味着我已经不能重复使用表单了?相反,我会再做一个更新?
    • @KimNicoleSabordo:好吧,除非这些字段不是必需的,否则不会。但即使是这种情况,最好还是分开制作,以确保如果您以后改变主意,表格不会以某种方式更新并且不再有效。
    • 好吧,如果这是解决方案。我之前尝试过,它有效,我只是不想多余。但如果没有其他办法,那就坚持那个解决方案。嘿,您能否将您的帖子答案更新为正确的答案,以便我可以将其标记为答案。谢谢。
    猜你喜欢
    • 2013-08-22
    • 2020-12-15
    • 2023-03-17
    • 2020-05-08
    • 1970-01-01
    • 2021-03-04
    • 2021-09-25
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多