django视图创建模型对象

时间:2019-02-23 09:31:07

标签: python django

我的网站使用评级功能,用户可以创建对新类别的请求,此后至少有100个用户必须对此请求进行评级,如果100/100个用户对该请求的评级为positiv,则该类别应获得已创建,但在评分达到100/100肯定票后,我不知道如何创建类别模型实例。

views.py

def category_request_up_vote (request, pk):
    category_request = get_object_or_404(CategoryRequests, pk=pk)
    try:
        if request.method == 'GET':
            if category_request.author == request.user:
                messages.error(request, 'You are trying to vote a request you created by your own. Thats not possible (Transmision ignored).')
                return redirect('category_request_detail', pk=category_request.pk)
            if CategoryRequests_Vote.objects.filter(voter=request.user, voted=category_request).exists():
                messages.error(request, 'You already Voted this request. Double votes are not allowed (Transmision ignored).')
                return redirect('category_request_detail', pk=category_request.pk)
            else:
                if category_request.up_vote == 100:
                    print("So what should i do now?")
                else:
                    category_request.up_vote = F('up_vote') + 1
                    category_request.save()
                    CategoryRequests_Vote.objects.create(voter=request.user, voted=category_request)
                    messages.success(request, 'You have successfully Provided an Up-Vote for this Request.')
                    return redirect('category_request_detail', pk=category_request.pk)
        else:
            messages.error(request, 'Uuups, something went wrong, please try again.')
            return redirect('category_request_detail', pk=category_request.pk)
    except:
        messages.error(request, 'Uuups, something went wrong, please try again.')
        return redirect('category_request_detail', pk=category_request.pk)

models.py

class Category(models.Model):
    title = models.CharField(max_length=30, verbose_name="Title")
    description = models.TextField(max_length=200, null=True, blank=False)
    cover = fields.ImageField(blank=False,
                              null=False,
                              upload_to=get_file_path_static_glued,
                              validators=[default_image_size, file_extension_category_cover],
                              dependencies=[FileDependency(
                                  processor=ImageProcessor(format='PNG', quality=99, scale={
                                      'max_width': 700, 'max_height': 700}))])

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.post = None
        self.post_sell_multiple = None


    def __str__(self):
        return self.title

    @classmethod
    def get_indexable(cls):
        return cls.objects.all()

    @classmethod
    def configure_mapping(cls, mapping):
        # mapping is an elasticsearch_dsl Mapping object
        mapping.field('title', 'string')
        return mapping


class CategoryRequests(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=20, verbose_name="Title")
    description = models.TextField(max_length=200, null=True, blank=True)
    cover = fields.ImageField(
                              null=True,
                              blank=True,
                              upload_to=get_file_path_user_uploads,
                              validators=[default_image_size, default_image_file_extension],
                              dependencies=[FileDependency(processor=ImageProcessor(
                                  format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))])
    published_date = models.DateField(auto_now_add=True, null=True)
    status = StatusField(default='Waiting')
    STATUS = Choices('Waiting', 'Rejected', 'Accepted')
    up_vote = models.IntegerField(default=0)
    down_vote = models.IntegerField(default=0)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    class Meta:
        verbose_name = "Category Request"
        verbose_name_plural = "Category Request(s)"
        ordering = ['title']

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:1)

CategoryRequest模型具有Category模型所需的字段,例如标题,说明等。

为此,请在您的if category_request.up_vote == 100:内部使用简单的django ORM 您可以写,

category=Category.objects.create(title=category_request.title,description=category_request.description)

添加类别模型需要的其他字段  并在下一行category.save()中。因此,现在创建了类别。