Jump to content
Sign in to follow this  
HecKel

[django] Combobox a partir de BD

Recommended Posts

HecKel

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?

Share this post


Link to post
Share on other sites
joana

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.

:D

Share this post


Link to post
Share on other sites
HecKel

Mas é que é exactamente isso que eu quero :D

Porreirissimo :P Resultou :D

Agora só tenho de enviar para o email o pedido de activação e afins, mas isso faço depois :D

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • 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.