markdown Formuláriifroizizandóorientaçãoaobjetos do Django
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Formuláriifroizizandóorientaçãoaobjetos do Django相关的知识,希望对你有一定的参考价值。
Doc.: https://docs.djangoproject.com/en/2.1/topics/forms/
### Configuração do formulário (forms.py)
```python
class AddressForm(forms.Form):
address = forms.CharField(
max_length=255,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
address_complement = forms.CharField(
max_length=255,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
city = forms.CharField(
max_length=255,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
state = forms.ChoiceField(
choices=STATE_CHOICES,
widget=forms.Select(attrs={'class': 'form-control'})
)
country = forms.CharField(
max_length=255,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
```
### Método de criação a recebimento da request (views.py)
```python
@login_required(login_url='/login/')
def address_create(request):
form_submitted = False
if request.method == 'GET':
form = AddressForm()
else:
form_submitted = True
form = AddressForm(request.POST)
if form.is_valid():
Address.objects.create(
address=form.cleaned_data['address'],
address_complement=form.cleaned_data['address_complement'],
city=form.cleaned_data['city'],
state=form.cleaned_data['state'],
country=form.cleaned_data['country'],
user=request.user
)
return redirect('/addresses/')
return render(request, 'my_app/address/create.html', {'form': form, 'form_submitted': form_submitted})
```
### Formulário (create.html)
```python
<form action="/addresses/create/" method="post" {% if form_submitted %}class="was-validated"{% endif %}>
{% csrf_token %}
<div class="form-group">
{{ form.address.label_tag }}
{{ form.address }}
<div class="invalid-feedback">
{{ form.address.errors }}
</div>
</div>
<div class="form-group">
{{ form.address_complement.label_tag }}
{{ form.address_complement }}
<div class="invalid-feedback">
{{ form.address_complement.errors }}
</div>
</div>
<div class="form-group">
{{ form.city.label_tag }}
{{ form.city }}
<div class="invalid-feedback">
{{ form.city.errors }}
</div>
</div>
<div class="form-group">
{{ form.state.label_tag }}
{{ form.state }}
<div class="invalid-feedback">
{{ form.state.errors }}
</div>
</div>
<div class="form-group">
{{ form.country.label_tag }}
{{ form.country }}
<div class="invalid-feedback">
{{ form.country.errors }}
</div>
</div>
</form>
```
以上是关于markdown Formuláriifroizizandóorientaçãoaobjetos do Django的主要内容,如果未能解决你的问题,请参考以下文章
javascript Vymazáníformulářovýchprvků/重置表单字段
javascript Formulářjakoobjekt - můjvýtvor
markdown haránposiblelautilizacióndeimágenescomobordes de los elementos delapági
markdown melhorespráticas - node
markdown Pasarparámetrosdesde纸质按钮
markdown Exemplos detestesunitários