在Django中创建两个应用之间的关系

在Django中创建两个应用之间的关系

本文介绍了在Django中创建两个应用之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django项目中有一个帖子和一个类别应用程序。我具有用户身份验证,用户可以创建类别和帖子。我的想法和帮助将不胜感激。我希望用户只能引用自己的类别,而不能在其他人自己的类别中创建帖子。就是说,如果用户创建了一个以上的类别,则他应该能够从其创建的类别的列表中进行选择,而不会看到其他人拥有的。

I have a post and a category app in my django project. I have user authentication and users can create categories as well as posts. I am at a point where I am out of ideas and help would be appreciated. I want users to be able to reference only their own category and create posts in their categories not in another persons own. That is if a user creates more that one category he should be able to select from the list of his created category and not see another persons own.

类别模型

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)

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

addition codes would be provided immediately on request. Thanks

后应用程序中的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 %}


推荐答案

想要列出某个视图中用户已添加的所有类别。

You probably want to list all the Categories to which a user has contributed on some view.

您可以通过以下方式获取用户已添加的所有类别:

You can get all the Categories to which a user contributed in the following way:

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

这篇关于在Django中创建两个应用之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 05:33