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=120, choices=TYPE_CHOICES, validators=[
validate_propertyType], default='Villa',)
area = models.DecimalField(decimal_places=2, max_digits=20, null=True, blank=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_CHOICES, null=True, blank=True)
baths = models.SmallIntegerField(choices=BATHROOMS_CHOICES, null=True, blank=True)
garages = models.SmallIntegerField(choices=GARAGES_CHOICES, null=True, blank=True)
location = models.CharField(
max_length=120, null=True, help_text="Enter a Town/City where your Property is located.")
propertyStatus = models.CharField(
max_length=120, choices=STATUS_CHOICES, validators=[validate_propertyStatus], default='Sale')
amenities = models.TextField(null=True, blank=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=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
def get_image_filename(instance, filename):
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 = (600, 800)
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(LoginRequiredMixin, CreateView):
model = Post
fields = ['title','content', 'price', 'propertyImage', 'propertyType', 'area', 'bedrooms', 'baths', 'garages',
'location', 'propertyStatus', 'amenities']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title','content', 'price', 'propertyImage', 'propertyType', 'area', 'bedrooms', 'baths', 'garages',
'location', 'propertyStatus', 'amenities']
def form_valid(self, form):
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(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
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
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