从子元素删除图像就是从父元素删除图像

时间:2019-03-17 02:06:59

标签: django python-3.x django-models django-views

我有2个模型发布和活动

下面是我的帖子模型

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/')

然后我有一个事件模型

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)

下面是我的活动的CreateView

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_
  

现在的问题是删除事件时。它正在删除post_image。为什么会这样呢?我该如何阻止这种情况发生

1 个答案:

答案 0 :(得分:1)

您的模型实际上违反了数据库规范化准则,因为您在EventPost之间有不必要的冗余。 Event已链接到Post,因此“同步”字段相同可能会导致许多完整性错误,例如您面临的错误。

处理此问题的最佳方法是从image中删除Event字段,并通过event_instance.post.post_image.url引用图像。

否则,您的孩子没有理由删除其父母图片unless you are using Django < 1.3。这是因为在旧版本中,如果删除了关联的模型实例,则Django会删除图像-并且由于您要将图像路径从一个模型复制到另一个模型,因此URL是相同的。