如何在一个视图上使用两个模型表单

时间:2018-06-12 18:56:19

标签: python django web

我还是django的新手,我正在开展一个项目,我需要用户输入他们想要出租房屋的一些信息。我希望用户上传至少6张图片,根据我收集的内容,在django上执行此操作的最佳方法是使用两个模型,一个收集有关房屋的基本信息,另一个存储房屋的图像。我该怎么编码views.py。我一直都没有尝试过。

forms.py

class MyHouseEditForm(forms.ModelForm):    
    class Meta:        
        model = Myhouses        
        fields = ('name_of_accomodation', 
                  'type_of_apartment','Number_of_rooms', 'house_rent', 
                  'availability', 'location', 'nearest_institution', 
                  'description',) 


class ImageForm(forms.ModelForm):  
    class Meta:
        model = Image
        fields = ('__all__' )

models.py

class Myhouses(models.Model):

    Available = 'A'
    Not_Available = 'NA'
    Availability = (
        (Available, 'Available'),
        (Not_Available, 'Not_Available'),
    )

    Flat = 'F'
    Self_contained = 's'
    Bungalow = 'b'
    Mini_flat = 's'
    Duplex = 'D'
    Room = (
        (Flat, 'Flat'),
        (Self_contained, 'Self_contained'),
        (Bungalow, 'Bungalow'),
        (Mini_flat, 'Mini_flat'),
        (Duplex, 'Duplex'),
    )

    time = models.DateTimeField(default = datetime.now, blank = True)
    name_of_accomodation = models.CharField(max_length=20)
    type_of_apartment = models.CharField(max_length=2, choices=Room, )
    Number_of_rooms = house_rent = models.IntegerField()
    house_rent = models.IntegerField()
    availability = models.CharField(max_length=2, choices=Availability, default=Available,)
    location = models.CharField(max_length=200)
    nearest_institution = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='author')

    def __str__(self):
        return self.name_of_accomodation

    def get_absolute_url(self):
        return reverse('search-detail', args=[str(self.id)])

    class Meta:
        ordering = ["-time"]

class Image(models.Model):
    myhouses = models.ForeignKey(Myhouses, related_name='images', on_delete=models.PROTECT)
    image = models.ImageField(upload_to='documents/')

views.py

def addlisting(request):    
    if request.method == 'POST': 
        Hform = MyHouseEditForm(request.POST, files=request.FILES, )
        Iform = ImageForm(request.POST, request.FILES, )
        if Hform.is_valid() and Iform.is_valid():    
            Houses = Hform.save(commit=False)
            Houses.author=request.user
            Houses.save()

            image = iform.save(commit=False)
            Houses.image.myhouses = myhouses
            Houses.save()
            messages.success(request, 'Listing Created Succesfully successfully')
            return redirect('addlisting')           
    else:        
        Hform = MyHouseEditForm()
        Iform = ImageForm()

    return render(request, 'houses/addlisting.html', {'Hform':Hform, 'Iform': Iform},  )

0 个答案:

没有答案