markdown Formulárioutilizando模型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Formulárioutilizando模型相关的知识,希望对你有一定的参考价值。

doc.: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms
### Formulário (forms.py)
```python
class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        # fields = '__all__'
        fields = ('address', 'address_complement', 'city', 'state', 'country')
        widgets = {
            'address': forms.TextInput(attrs={'class': 'form-control'}),
            'address_complement': forms.TextInput(attrs={'class': 'form-control'}),
            'city': forms.TextInput(attrs={'class': 'form-control'}),
            'state': forms.Select(attrs={'class': 'form-control'}),
            'country': forms.TextInput(attrs={'class': 'form-control'})
        }
```
### Método criação (views.py)
```python
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():
            # apenas hidrata o `address` sem salvar no banco
            address = form.save(commit=False) 
            # para podermos associar o user
            address.user = request.user
            address.save()
            return redirect('/addresses/')

    return render(request, 'my_app/address/create.html', 
      {'form': form, 'form_submitted': form_submitted}
    )
``` 
    
### Método atualização (views.py)
```python
def address_update(request, id):
    form_submitted = False
    address = Address.objects.get(id=id)
    if request.method == 'GET':
        form = AddressForm(instance=address)
    else:
        form_submitted = True
        form = AddressForm(request.POST, instance=address)
        if form.is_valid():
            address.save()
            return redirect('/addresses/')
    return render(request, 'my_app/address/update.html',
                  {'address': address, 'form': form, 'form_submitted': form_submitted})
  ```

以上是关于markdown Formulárioutilizando模型的主要内容,如果未能解决你的问题,请参考以下文章

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