1

I have 2 models Post and event

Below is my post model

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')   
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True, max_length=450)  
    message = models.TextField(max_length=3000)  
    post_image = models.ImageField(upload_to='post_images/')

and then I have a Events model

class Event(models.Model):
    user = models.ForeignKey(User, related_name='cook')
    post = models.ForeignKey(Post, related_name='recipe')      
    date = models.DateField()    
    image = models.ImageField(blank=True, null=True)

Now in below is the CreateView for my Event

class CreateEvent(IsVerifiedMixin, CreateView):
    model = Event
    form_class = EventForm
    template_name = 'event/event_form.html'
    def form_valid(self, form, *args, **kwargs):
        self.object = form.save(commit=False)
        event = self.object
        user = self.request.user
        today = datetime.date.today()
        if today + datetime.timedelta(days=3) <= event.date <= today + datetime.timedelta(days=30):
            event.user = user
            slug = self.kwargs['slug']
            post = get_object_or_404(Post, slug=slug)
            event.post = post
            event.image = post.post_image ###########THIS IS WHERE THE EVENT GETS ITS IMAGE           
            event.save()            
        else:
            form.add_error(field="date", error="The date has to be more than or equal to 3 days and less than 30 days")
            return super().form_invalid(form)

    def get_success_url(self, *args, **kwargs):
        slug = self.kwargs['slug']
        obj = get_object_or_404(Post, slug=slug)
        url_ = obj.get_absolute_url()
        user = self.request.user
        if user.is_authenticated():
            return url_

Now the problem is when I delete a event. It is deleting the post_image. Why is this happening. How Can I stop this from happening

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Samir Tendulkar
  • 1,151
  • 3
  • 19
  • 47

1 Answers1

1

Your model actually violates a guideline of database normalization, since you have an unnecessary redundancy between Event and Post. Event is linked to Post, so having the same field "in sync" can cause many integrity errors such as the one you are facing.

The best way to handle this is to remove the image field from Event, and reference the image instead via event_instance.post.post_image.url.

Otherwise, there is no reason why your child should be deleting its parents image, unless you are using Django < 1.3. This would be because in the older versions, Django would delete an image if the associated model instance was deleted - and since you are copying the image path from one model to another, the url is the same.

Hybrid
  • 6,741
  • 3
  • 25
  • 45