在django

时间:2017-09-17 12:05:24

标签: python django

我的django项目中有一个帖子和一个类别应用程序。我有用户身份验证,用户可以创建类别和帖子。我正处于一个我缺乏想法的地步,我将不胜感激。我希望用户只能引用自己的类别,并在其类别中创建帖子,而不是在其他人拥有的帖子中。也就是说,如果用户创建了更多的一个类别,他应该能够从他创建的类别的列表中进行选择,而不会看到另一个人拥有的类别。

类别模型

class Category(models.Model):
    name = models.CharField(max_length = 120)
    slug = models.SlugField(unique= True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

发布模型

class Post(models.Model):
     user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='posts_created') #blank=True, null=True)
     title = models.CharField(max_length = 120)
     slug = models.SlugField(unique= True)
     category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) 

将根据要求立即提供附加代码。感谢

发布应用中的View.py

def create(request):
    if not request.user.is_authenticated():
        messages.error(request, "Kindly confirm Your mail")
        #or raise Http404
    form = PostForm(request.POST or None, request.FILES or None)
    user = request.user
    categories = Category.objects.filter(category_created__user=user).distinct()
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        create_action(request.user, 'Posts', instance)
        messages.success(request, "Post created")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
        "categories": categories,
    }
    template = 'create.html'
    return render(request,template,context)

表格

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            "title",
            "content",
            "category",
        ]

HTML

{% if form %}

  <form method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
    {{ form|crispy|safe }}
      <input type="submit" name="submit" value="Publish">
  </form>
      {% endif %}

2 个答案:

答案 0 :(得分:1)

您可能希望列出用户在某个视图上贡献的所有类别。

您可以通过以下方式获取用户贡献的所有类别:

user = request.user  # assuming you're in a view
categories = Category.objects.filter(post__user=user).distinct()

答案 1 :(得分:0)

category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) 

related_name =&#39; category_created&#39;表示要从您需要使用的类别访问您的帖子&#39; category_created&#39;:

categories = Category.objects.filter(category_created__user=user).distinct()

或者您可以将其重命名为related_name =&#39; post&#39;然后迁移。

修改

后期应用中的View.py

def create(request):
    if not request.user.is_authenticated():
        messages.error(request, "Kindly confirm Your mail")
        #or raise Http404
    form = PostForm(request, request.POST or None, request.FILES or None, )
    user = request.user
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        create_action(request.user, 'Posts', instance)
        messages.success(request, "Post created")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
        "categories": categories,
    }
    template = 'create.html'
    return render(request,template,context)

forms.py

class PostForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super (PostForm,self ).__init__(*args,**kwargs) # populates the post
        self.fields['category'].queryset = Category.objects.filter(
            category_created__user=request.user
        ).distinct()