Monday, August 30, 2010

filling model choices field according to language code

Hi,

In my django application i have a Ticket class at my model as below

class Ticket(models.Model):

...


faculty = models.SmallIntegerField(
_('Faculty'),
#edit begins
choices=((0,""),),
#edit begins
default=0,
blank=False,
null=True,
help_text=_('Faculty name of the ticket related with'),
)

....


The thing is, i want to fill the choices part dynamically. According to the language, i want to fill the string part so at the template the right human readable string will be seen. Because i couldn't visualize how i can do it, i tried to fix it at the view part as

if lang == "en":
form.fields['faculty'].choices = [(0, '--------')] + [[f.fakulte_id, f.faculty_name] for f in Faculty.objects.all()]
fak=Faculty.objects.get(fakulte_id=fak)
form.fields['department'].choices = [(0, '--------')] + [[d.bolum_id, d.dep_name] for d in fak.department_set.all()]
if lang == "tr":
form.fields['faculty'].choices = [(0, '--------')] + [[f.fakulte_id, f.fakulte_tr] for f in Faculty.objects.all()]
fak=Faculty.objects.get(fakulte_id=fak)
form.fields['department'].choices = [(0, '--------')] + [[d.bolum_id, d.bolum_tr] for d in fak.department_set.all()]
form.fields['problemcategory'].choices = [(0, '--------')] + [[p.id, p.category] for p in ProblemCategory.objects.all()]

As you can see i have problemcategory and department fields also. At the ticket edit issue, i have modelform as


class EditTicketForm(forms.ModelForm):
class Meta:
model = Ticket

And at the view

form = EditTicketForm(request.POST, instance=ticket)
lang=request.LANGUAGE_CODE
fak=int(request.POST["faculty"])

The rest continues as above lang part. When i tried

if form.is_valid():

i got errors saying that the values from the department, faculty and problemcategory fields are not valid. When i add a clean method for modelform as

def clean_faculty(self):
data = self.cleaned_data['faculty']
return 0

the error related with faculty is gone. So it seems modelform is creating the choices with (0, "") which is defined at the model. How can i fix it like at the view part so that i will fill the choices according to the language code?


--
Oguz Yarimtepe <comp.ogz@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment