Friday, September 27, 2019

Uploading at least 3 images per Post

Hello,
With these models of Post and Images, I want to display and edit/delete the images along with the fields of the post. I have just added the Images model so I can have its fields in a Formset but the implementation of Model Formsets has challenged me.

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    price = models.IntegerField(validators=[MinValueValidator(10), MaxValueValidator(10000000)], default=10,
                                help_text="Enter in Dollars, $.")
    featured       = models.BooleanField(default=False)
    active         = models.BooleanField(default=True)
    propertyType   = models.CharField(max_length=120choices=TYPE_CHOICESvalidators=[
                                    validate_propertyType], default='Villa',)
    area           = models.DecimalField(decimal_places=2max_digits=20null=Trueblank=True,
                               help_text="Enter in Acres. Hint: 100 decimals = 1 acre = 0.405 hectares, 1 Sq. mile = 640 Acres, 1 decimal = 436 sq. feet = 40.5 sq. metres = 0.001 acres.")
    bedrooms       = models.SmallIntegerField(choices=BEDROOMS_CHOICESnull=Trueblank=True)
    baths          = models.SmallIntegerField(choices=BATHROOMS_CHOICESnull=Trueblank=True)
    garages        = models.SmallIntegerField(choices=GARAGES_CHOICESnull=Trueblank=True)
    location       = models.CharField(
        max_length=120null=Truehelp_text="Enter a Town/City where your Property is located.")
    propertyStatus = models.CharField(
        max_length=120choices=STATUS_CHOICESvalidators=[validate_propertyStatus], default='Sale')
    amenities      = models.TextField(null=Trueblank=True,
                                 help_text="Enter separating with commas, e.g: Parking, Balcony, Swimming Pool, Tennis Courts, Outdoor Kitchen, Internet, Cable T.V, Concrete Flooring, ...")
    slug           = models.SlugField(null=Trueblank=True)

    def __str__(self):
        return self.title
    
    def get_absolute_url(self):
        return reverse('post-detail'kwargs={'pk'self.pk})

def get_image_filename(instancefilename):
    title = instance.post.title
    slug = slugify(title)
    return "properties_pics/%s-%s" % (slug, filename)

class Images(models.Model):
    post            = models.ForeignKey(Post, on_delete=models.CASCADE,default=None)
    propertyImages  = models.ImageField(
        default="default.jpg"upload_to=get_image_filename, 
        help_text=" We must provide a clear Picture, preferably Landscape, not Portrait!")
    
    def save(self*args**kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.propertyImages.path)

        if img.height > 800 or img.width > 600:
            output_size = (600800)
            img.thumbnail(output_size)
            img.save(self.propertyImages.path)

Here is my Views.py, works well before the Formsets;

class PostListView(ListView):
    model = Post
    template_name = "maproperty/home.html"  # <app>/<model>_<viewtype>.html
    context_object_name = "posts"
    odering = ["date_posted"]
    paginate_by = 5

class UserPostListView(ListView):
    model = Post
    template_name = "maproperty/user_posts.html"  # <app>/<model>_<viewtype>.html
    context_object_name = "posts"
    paginate_by = 6

    #filter a post from a certain user, modify the querry set by overidding this method
    def get_queryset(self):
        #get user associated with the username we gonna get from the url. 
        user =get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')


class SaleListView(ListView):
    model = Post

class RentListView(ListView):
    model = Post

class BookingListView(ListView):
    model = Post


class PostDetailView(DetailView):
    model = Post

class PostCreateView(LoginRequiredMixinCreateView):
    model = Post
    fields = ['title','content''price''propertyImage''propertyType''area''bedrooms''baths''garages'
    'location''propertyStatus''amenities']

    def form_valid(selfform):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixinUserPassesTestMixinUpdateView):
    model = Post
    fields = ['title','content''price''propertyImage''propertyType''area''bedrooms''baths''garages'
    'location''propertyStatus''amenities']

    def form_valid(selfform):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixinUserPassesTestMixinDeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


def about(request):
    return render(request, "maproperty/about.html", {"title""About"})

def contact(request):
    return render(request, "maproperty/contact_page.html", {"title""Contact"})

Thank you.

Richard Dick Balwane
Mobiles:        +256 755 442248,
                        +256 781 493558.
Twiter:           @RBalwane
WhatsApp:   +256 755 442248

Balwane Holding Inc.



Virus-free. www.avg.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAjYwK80PJ%3DajVBomp3VfHs5kRpYA5Hcvu8cteP6MxXk161c0Q%40mail.gmail.com.

No comments:

Post a Comment