Django:取决于州ChoiceField的省份选择字段

时间:2018-12-26 23:50:52

标签: python django

我有一个注册表格,要求用户选择他们的部门(例如美国),省和地区。西班牙语:“ departamento”,“ provincia”,“ distrito”。

我可以从我们的Peru表中填充这些信息,该表在三个不同的列中包含此信息。

但是我需要限制用户的选择,以便他们选择有效的组合。

enter image description here

但是,在最终形式中,用户可以选择“部门”,“省”和“分发”的无效组合。例如,以美国为例,用户可以选择:

-departamento:“加利福尼亚”。
-provincia:“达拉斯”。
-地区:“卡罗尔顿”。

enter image description here

models.py

### User Profile ###

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # birth_date = models.DateField(null=True, blank=True)
    dni = models.CharField(max_length=30, blank=True)
    # phone_number = models.CharField(max_length=15, blank=True)
    shipping_address1 = models.CharField(max_length=100, blank=False)
    shipping_address2 = models.CharField(max_length=100, blank=False)
    shipping_department = models.CharField(max_length=100, blank=False)
    shipping_province = models.CharField(max_length=100, blank=False)
    shipping_district = models.CharField(max_length=100, blank=False)




@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()


class Peru(models.Model):
    departamento = models.CharField(max_length=100, blank=False)
    provincia = models.CharField(max_length=100, blank=False)
    distrito = models.CharField(max_length=100, blank=False)

    def __str__(self):
        return self.departamento + " - " + self.provincia + " - " + self.distrito

forms.py

class ProfileForm(ModelForm):

    def __init__(self, district_list, province_list, department_list, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['shipping_district'] = forms.ChoiceField(choices=tuple([(name, name) for name in district_list]))
        self.fields['shipping_province'] = forms.ChoiceField(choices=tuple([(name, name) for name in province_list]))
        self.fields['shipping_department'] = forms.ChoiceField(choices=tuple([(name, name) for name in department_list]))

    dni = forms.CharField(label = 'DNI', max_length=100, required=True)
    email = forms.EmailField(label = 'Correo electrónico', max_length=254, widget=forms.TextInput(attrs={'placeholder': 'micorreo@correo.com'}))
    cellphone = forms.CharField(label = 'Celular o  teléfono', max_length=15, required=True)
    shipping_address1 = forms.CharField(label = 'Dirección de envío', max_length=100, required=True)
    shipping_address2 = forms.CharField(label = 'Dirección de envío 2 (opcional)', max_length=100, required=False)

    class Meta:
        model = Profile
        fields = ('dni',  'email', 'cellphone', 'shipping_address1',
                  'shipping_address2', 'shipping_department', 'shipping_province', 'shipping_district')

views.py

@transaction.atomic


def signupView(request):
    peru = Peru.objects.all()
    print(peru)
    department_list = set()
    province_list = set()
    district_list = set()
    for p in peru:
        department_list.add(p.departamento)
        province_list.add(p.provincia)
        district_list.add(p.distrito)

    if request.method == 'POST':
        user_form = SignUpForm(request.POST)
        profile_form = ProfileForm(district_list, province_list, department_list, request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            username = user_form.cleaned_data.get('username')
            signup_user = User.objects.get(username=username)
            customer_group = Group.objects.get(name='Clientes')
            customer_group.user_set.add(signup_user)
            raw_password = user_form.cleaned_data.get('password1')
            user.refresh_from_db()  # This will load the Profile created by the Signal
            profile_form = ProfileForm(district_list, province_list, department_list, request.POST, instance=user.profile)  # Reload the profile form with the profile instance
            profile_form.full_clean()  # Manually clean the form this time. It is implicitly called by "is_valid()" method
            profile_form.save()  # Gracefully save the form
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('cart:cart_detail')
    else:
        user_form = SignUpForm()

        profile_form = ProfileForm(district_list, province_list, department_list)
    return render(request, 'accounts/signup.html', {
        'user_form': user_form,
        'profile_form': profile_form
})

HTML:

{% extends 'base.html' %}

{% load staticfiles %}

{% load crispy_forms_tags %}

{% block metadescription %}
    Regístrate para que recibas las últimas novedades. Tenemos los mejores cojines de El Perú.
{% endblock %}
{% block title %}
    Crear una nueva cuenta - Perfect Cushion Store
{% endblock %}

{% block content %}

    <div>
        {% if not form.is_valid %}

            <div class="container">
                <h1 class="text-center my_title">
                    Crear una nueva cuenta
                </h1>
                <br>
                <div class="col-12 col-sm-12 col-md-12 col-lg-12 mx-auto-bg-light">
                    <br>
                    <p>Ingresa la siguiente información para crear una cuenta</p>


                    <form method="post">
                        {% csrf_token %}

                        <div class="row">

                            <div class="col-md-6">


                                <table>
                                    <tr>
                                        <th>{{ user_form.first_name.label_tag }}</th>
                                        <td>
                                            {{ user_form.first_name.errors }}
                                            {{ user_form.first_name }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ user_form.last_name.label_tag }}</th>
                                        <td>
                                            {{ user_form.last_name.errors }}
                                            {{ user_form.last_name }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ user_form.username.label_tag }}</th>
                                        <td>
                                            {{ user_form.username.errors }}
                                            {{ user_form.username }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.dni.label_tag }}</th>
                                        <td>{{ profile_form.dni }}</td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.email.label_tag }}</th>
                                        <td>{{ profile_form.email }}</td>
                                    </tr>
                                    <tr>
                                        <th>{{ user_form.password1.label_tag }}</th>
                                        <td>
                                            {{ user_form.password1.errors }}
                                            {{ user_form.password1 }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ user_form.password2.label_tag }}</th>
                                        <td>
                                            {{ user_form.password2.errors }}
                                            {{ user_form.password2 }}
                                        </td>
                                    </tr>
                                </table>

                            </div>

                            <div class="col-md-6">

                                <table>


                                    <tr>
                                        <th>{{ profile_form.cellphone.label_tag }}</th>
                                        <td>{{ profile_form.cellphone.errors }}
                                            {{ profile_form.cellphone }}
                                        </td>
                                    </tr>

                                    <tr>
                                        <th>{{ profile_form.shipping_address1.label_tag }}</th>
                                        <td>
                                            {{ profile_form.shipping_address1.errors }}
                                            {{ profile_form.shipping_address1 }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.shipping_address2.label_tag }}</th>
                                        <td>
                                            {{ profile_form.shipping_address2.errors }}
                                            {{ profile_form.shipping_address2 }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.shipping_department.label_tag }}</th>
                                        <td>
                                            {{ profile_form.shipping_department.errors }}
                                            {{ profile_form.shipping_department }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.shipping_province.label_tag }}</th>
                                        <td>
                                            {{ profile_form.shipping_province.errors }}
                                            {{ profile_form.shipping_province }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>{{ profile_form.shipping_district.label_tag }}</th>
                                        <td>
                                            {{ profile_form.shipping_district.errors }}
                                            {{ profile_form.shipping_district }}
                                        </td>
                                    </tr>



                                </table>

                            </div>

                        </div>

                        <br>
                        <br>

                        <div class="row">
                            <div class="col-md-6"></div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-6"></div>
                                    <div class="col-md-6">
                                        <button class="btn btn-secondary" type="submit">Registrarse</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <br>
                </div>
            </div>
        {% else %}
            <div class="container">
                <br>
                <h1 class="my_title text-center">
                    Tu cuenta ha sido creada exitosamente.
                </h1>
                <br>
                <div>
                    <p>
                        Estimado cliente,
                        <br>
                        <br>
                        Su cuenta ha sido creada y ya puede ser usada

                        <br>
                        <a href="{% url 'shop:allProdCat' %}">Seguir comprando</a> y disfruta de los mejores cojines
                    </p>
                </div>
            </div>
        {% endif %}
    </div>
    <br>
{% endblock %}

0 个答案:

没有答案