Я пытаюсь создать форму загрузки изображения с полем выбора автомобиля, которое необходимо сделать на автомобилях текущего дилера
модели :
class Photo(BaseDateAuditModel):
image = models.ImageField(upload_to='photos/')
position = models.SmallIntegerField(default=1, validators=[MinValueValidator(limit_value=1)])
car = models.ForeignKey('cars.Car', on_delete=models.CASCADE, related_name='photos')
class Dealer(User):
city = models.ForeignKey('City', on_delete=models.SET_NULL, null=True, blank=False)
class Car(BaseDateAuditModel):
properties = models.ManyToManyField(Property)
objects = CarManager.from_queryset(CarQuerySet)()
views = models.PositiveIntegerField(default=0, editable=False)
slug = models.SlugField(max_length=75)
number = models.CharField(max_length=16, unique=True)
dealer = models.ForeignKey("dealers.Dealer", on_delete=models.CASCADE, related_name='cars', null=True, blank=False)
model = models.ForeignKey('CarModel', on_delete=models.SET_NULL, null=True, blank=False)
color = models.ForeignKey('Color', on_delete=models.SET_NULL, null=True, blank=False)
Форма:
class ImageForm(forms.ModelForm):
class Meta:
model = Photo
fields = ['image', 'car']
widgets = {
'image': forms.ClearableFileInput(attrs={'multiple': True}),
}
Просмотр:
class UpdateImageView(FormView):
model = Photo
form_class = ImageForm
template_name = 'image-update.html'
def get_success_url(self):
return reverse('cars:cars-list')
def form_valid(self, form):
form.save()
return super().form_valid(form) # 1st way, get list all car, not only for current user
def get_queryset(self):
'''
return a list of cars of the current user
for example: my current dealer(user) have one car and this
method return:
Car.objects.filter(id__in=car_list) == <CarQuerySet [<Car: Audi >]>
'''
user = self.request.user
car_list = Dealer.objects.filter(username=user).values_list('cars', flat=True)
return Car.objects.filter(id__in=car_list)
Я думал о def save()
и get_initial
в представлениях и get_initial_for_field
в форме, но не понимаю, как их реализовать.
Я новичок в python, и ваша помощь будет очень признательна.