【问题标题】:Django Multiple Form Processing in same View同一视图中的 Django 多表单处理
【发布时间】:2021-04-14 18:00:31
【问题描述】:

我正在为 django 表单处理的两个方面寻求帮助。

  1. 我有一个覆盖post 的类视图,并检查request.POST 中的表单名称以确定已提交的表单。根据提交的表单,我对该表单执行适当的操作并保存到模型中。那部分工作正常。我没有使用模型表单,只是在模板中创建的带有输入字段的自定义 html 表单。请参阅下面的视图和 html 以供参考。这是处理此问题的正确方法,还是我应该遵循使用模型表单的最佳实践?代码对我来说似乎有点沉重且不标准化,好像应该有更好的方法......

  2. 由于我没有使用模型表单,错误处理让我有些困惑。您如何处理不使用 django 模型表单的普通 html 表单上的错误处理?请参阅下面的代码中标记为# ERROR HANDLING FOR FORM NEEDED 的视图,特别是在模型级别上唯一且经过验证的用户名字段。

views.py

 class ProfileView(View):

   def get(self, request, *args, **kwargs):
        if request.method == "GET":
            # load profile data...
    
   def post(self, request, *args, **kwargs):
        
        if request.method == "POST":

            # check if profile_form submitted
            if 'profile_form' in request.POST:
                # get user form data
                profile_data = request.POST.dict()
                # get current user profile
                user_profile = Profile.objects.get(my_user=request.user)
                # check username entry against current
                if user_profile.username == profile_data['username']:
                    user_profile.country = profile_data['country']
                    user_profile.display_location = profile_data['display_location']
                    user_profile.organization_name = profile_data['organization']
                    user_profile.save(update_fields=['country', 'display_location','organization_name'])
                    #send success message to page
                    messages.success(request, "Success: Profile was updated.")
                else:
                    try:
                        user_profile.username = profile_data['username']
                        user_profile.country = profile_data['country']
                        user_profile.display_location = profile_data['display_location']
                        user_profile.organization_name = profile_data['organization']
                        user_profile.save(update_fields=['username', 'country', 'display_location','organization_name'])
                        #send success message to page
                        messages.success(request, "Success: Profile was updated.")
                    except:
                        # unique constraint error on username
                        # ERROR HANDLING FOR FORM NEEDED


            # check if user_name_form submitted
            if 'user_name_form' in request.POST:
                # get user form data
                user_data = request.POST.dict()
                # get current user
                user = MyUser.objects.get(email=request.user)
                user.first_name = user_data['first_name']
                user.last_name = user_data['last_name']
                user.save(update_fields=['first_name', 'last_name'])
                # send success message to page
                messages.success(request, "Success: Name was updated.")
            
        # Return Profile page view with updated data
        return HttpResponseRedirect(reverse('profile'))

html

<!--form-->
                <form id="profile" class="small" method="POST" action="{% url 'profile' %}">
                {% csrf_token %}
                    <!--Username-->
                    <label for="username">Username <span style="font-style: italic;">(create a unique display name that will appear to other users on the site)</span></label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="username">@</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="username" name="username" value="{% if profile and profile.username is not None %}{{ profile.username }}{% endif %}">
                    </div>
                    <hr>
                    <p>Tell us where you are from!</p>
                    <!--Country State/Province City Select-->
                    <div class="form-group">
                        <select name="country" class="form-control mb-3" id="country">
                            <option value="">Select Country...</option>
                            {% for country in countries %}
                                {% if profile.country == country.name %}
                                    <option value="{{ country.name }}" id="{{ country.code }}" selected>{{ country.name }}</option>
                                {% else %}
                                    <option value="{{ country.name }}" id="{{ country.code }}">{{ country.name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                    <hr>
                    <p>Enter your profile display location <i>(ie. City, State, Province, Region...)</i></p>
                    <input type="text" class="form-control" id="display_location" name="display_location" placeholder="Based in..." value="{% if profile and profile.display_location is not None %}{{ profile.display_location }}{% endif %}">
                    <hr>
                    <p>Do you belong to an organization?</p>
                    <input type="text" class="form-control" id="organization" name="organization" placeholder="Organization Name" value="{% if profile and profile.organization_name is not None %}{{ profile.organization_name }}{% endif %}">
                    <hr>
                    <button type="submit" class="btn btn-primary" name="profile_form" value="profile_form">Save</button>
                </form>

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    作为我能够解决的这个问题的解决方案,请参阅帖子 here,了解一种无需第三方应用即可解决此问题的方法。

    【讨论】:

      【解决方案2】:

      这可能很难做到,所以几年前在 DjangoCon 上,我们构建了一个 Django 应用程序来提供帮助。看看:

      https://github.com/kennethlove/django-shapeshifter

      【讨论】:

      • 感谢您的参考。在阅读该项目的文档时,该应用程序似乎生成了多个表单,这些表单必须在一个表单标签内一起提交。这对我上面的问题没有帮助,这涉及在同一视图中单独的表单验证和提交。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2022-01-04
      • 2020-06-30
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      相关资源
      最近更新 更多