Jump to content

Recommended Posts

Posted

Boas!

Na minha aplicação estou a usar forms, neste caso JULGO que não convém usar forms baseados em Models pois não estou a passar todos os elementos para o form e nesse form "jogo" com mais do que um Modelo.

Eu tenho um Modelo de cidades com o seguinte formato:

class Country(models.Model):
    name = models.CharField(max_length=60)
    
    def __unicode__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length=60)
    country = models.ForeignKey(Country)
    
    def __unicode__(self):
        return u'%s - %s' % (self.name, self.country)

Eu quero usar o Modelo City a aparecer no formulário como combobox, mas não estou a conseguir fazer isso. Isto é o que tenho até ao momento relativo a isto:

from django import forms
from django.forms import ModelForm
from django.forms.util import ErrorList
from django.contrib.auth.models import User
from lafora.forum.models import City

class MemberForm(forms.Form):
    username = forms.CharField(max_length=30)
    password = forms.CharField(min_length=6, max_length=30, widget=forms.PasswordInput)
    dpassword = forms.CharField(min_length=6, max_length=30, widget=forms.PasswordInput)
    firstname = forms.CharField(max_length=30, required=False)
    lastname = forms.CharField(max_length=30, required=False)
    email = forms.EmailField()
    bdate = forms.DateField()
    city = forms.TypedChoiceField(City)
    
    def clean(self):
        cleaned_data = self.cleaned_data
        password = cleaned_data.get("password")
        dpassword = cleaned_data.get("dpassword")

        if password and dpassword:
            if password != dpassword:
                msg = u"As passwords têem de ser iguais."
                self._errors["dpassword"] = ErrorList([msg])

        return cleaned_data

E esta é a view:

from django.shortcuts import render_to_response
from django.forms.models import modelformset_factory
from lafora.accounts.forms import MemberForm
from lafora.forum.models import Member
from django.contrib.auth.models import User
    
def register(request):
    if request.method == 'POST': # If the form has been submitted...
        form = MemberForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            uname = form.cleaned_data['username']
            passwd = form.cleaned_data['password']
            fname = form.cleaned_data['firstname']
            lname = form.cleaned_data['lastname']
            e_mail = form.cleaned_data['email']
            userdata = User.objects.create_user(username=uname, first_name=fname, last_name=lname, email=e_mail, password=passwd, is_staff=False, is_active=False, is_superuser=False)
            return HttpResponseRedirect('/thanks/') # Redirect after POST

    else:
        form = MemberForm() # An unbound form

    return render_to_response('accounts/register.html', {
        'form': form,
    })

Alguma ideia de como resolver isto / comentários ao código já feito?

  • 2 weeks later...
Posted

Podes fazer assim:

na form do forms.py

city = forms.ModelMultipleChoiceField(queryset=City.objects.all())

Acho que não é exactamente o que queres, mas aproxima-se.

😄

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.