So I sloved my problem with QuerySet - while creating the ModelForm 
instance, there should be passed instance argument, not only POST or 
GET, so that the ModelForm could "know" if there should be edition of 
existing model or creating a new one.

Regards,
Marek


Marek

Marek Wawrzyczek wrote:
> Hi,
> I've got the following class:
>
> CarForm(ModelForm):
>    def __init__(self,  *args, **kwargs):
>        super(CarForm, self).__init__(*args, **kwargs)
>        id = self.instance.id
>        qs = CarPhoto.objects.filter(car__id = id)
>        self.fields['main_image'] = forms.ModelChoiceField(qs)
>    class Meta:
>        model = Car
>
> I would like to allow user to choose the main photo for a car only 
> from photos assigned to this car. The code above doesn't work, but 
> when changed to:
>    qs = CarPhoto.objects.filter(car__id = 1)
> then the field "main_image" has only the photos associated with the 
> car which id is 1. The model classes are (simplified for clarify):
>
> class Car(models.Model):
>    main_image = models.ForeignKey('CarPhoto',  related_name = 
> 'car_main_image',  blank = True,  null = True)
>
>
>   class CarPhoto(models.Model):
>    image = models.ImageField( upload_to = 'car_photos/')
>    car = models.ForeignKey(Car)
>
> Another strange thing is that while trying (in form's __init__ method) do
>    print kwargs
> then
>    {'instance': <Car: Car object>}
> was printed. But while doing
>     print kwargs['instance']
> then "key error" was printed on a page, and the debugging message was:
> (...)
>      51.  print kwargs['instance'] ...
>        Local vars
>        (...)
>            kwargs {}
>        (...)
>
>
> How can I get the instance's id in the ModelForm's __init__ properly 
> so that the QuerySet would result only photo's associated with car id 
> equals to instance's id? Why the kwargs behaves so strange?
>
> Thanks in advance,
> Marek
>
>


--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to