0

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.

category model

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)

post model

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 in post app

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)

Form

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 %}
King
  • 1,885
  • 3
  • 27
  • 84
  • Please share full traceback. – Sachin Sep 18 '17 at 10:15
  • that is the full trace back which I shared based on @pablo Verges answer. but chnaging `post__user` to `category_created_user` I get no error but the the purpose of the category is defeated because a user sees ever categories of other users – King Sep 18 '17 at 10:18
  • You can see the SQL query it forms by importing `connection` from `django.db` and print `connection.queries`. I believe the query will be right and maybe, the user you're trying to filter all categories that are created. You can always create a new user and give him a totally different category and then test for that user. – Sachin Sep 18 '17 at 10:28
  • users are created. A user should be able to creat categories and post in his own categories by selecting the one he wants to post into from the create post form – King Sep 18 '17 at 10:30
  • Yes. Check for a user that does not have all categories. And do print SQL query of `Category.objects.filter(category_created__user=user).distinct()` here. – Sachin Sep 18 '17 at 10:32
  • yes I did that but instead I still got all the categories – King Sep 18 '17 at 10:33
  • show your html and form please – Brown Bear Sep 18 '17 at 10:42
  • Done Bear Brown – King Sep 18 '17 at 10:47
  • Hi kindly help with this question https://stackoverflow.com/questions/46348817/django-polls-with-autentication thanks – King Sep 21 '17 at 16:48
  • Hi kindly assist with this question. been there for about a week but still now answer. https://stackoverflow.com/questions/46379478/django-database-migration?noredirect=1#comment79717746_46379478 – King Sep 30 '17 at 09:32

2 Answers2

1

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()
Pablo Vergés
  • 319
  • 2
  • 8
  • I got the error `global name 'user' is not defined` – King Sep 17 '17 at 20:19
  • the user is stored in the request, otherwise you'll need to get the right user with `User.objects.filter(...)` – Pablo Vergés Sep 17 '17 at 20:25
  • still the same thing – King Sep 17 '17 at 20:26
  • do you have any other suggested way? I could update my question with my default view – King Sep 17 '17 at 20:28
  • can you add the whole `Cannot resolve keyword` error please? – Pablo Vergés Sep 17 '17 at 20:46
  • `Cannot resolve keyword 'posts' into field. Choices are: category_created, id, name, slug, timestamp, user, user_id` – King Sep 17 '17 at 20:47
  • Could you add the whole traceback? – Pablo Vergés Sep 17 '17 at 20:50
  • kindly check and responde – King Sep 17 '17 at 21:41
  • if I change it to `categories = Category.objects.filter(category_created__user=user).distinct()` it works but still displays every category – King Sep 17 '17 at 22:30
  • You had to set `category_created` instead of `post` because of the related name. I don't understand why there is a `user` field in Category. – Pablo Vergés Sep 18 '17 at 03:28
  • read the question well. each category is associated to a user. so users can create there own distinctive categories and only the category would appear for the user when he wants to create a post. – King Sep 18 '17 at 08:23
  • Hi kindly help with this question https://stackoverflow.com/questions/46348817/django-polls-with-autentication thanks – King Sep 21 '17 at 16:48
  • Hi kindly assist with this question. been there for about a week but still now answer. https://stackoverflow.com/questions/46379478/django-database-migration?noredirect=1#comment79717746_46379478 – King Sep 30 '17 at 09:31
0
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) 

related_name='category_created' means that to access your post from a category you need to use 'category_created':

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

or you can rename it to related_name='post' and then migrate.

Edit

View.py in post app

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()
user2021091
  • 561
  • 2
  • 11
  • yes. it appears but I am getting all the categories in the create form instead of the categories a user created – King Sep 18 '17 at 15:16
  • You have a default to user with 1, are you using user 1 ? – user2021091 Sep 18 '17 at 15:17
  • I want users to be able to see only their own categories. the one they created should show up for selection when they want to create a post. – King Sep 18 '17 at 15:17
  • I am not using the default user. – King Sep 18 '17 at 15:19
  • and I can not use `"categories": categories` that is in the context in my template because I am using `form|as_p` – King Sep 18 '17 at 15:21
  • and I really appreciate you coming to respond to my question. Thank you – King Sep 18 '17 at 15:25
  • Well this is another question, but the answer to your error is the one I gave you. Post your form and view in another question and you'll get a quick answer. – user2021091 Sep 18 '17 at 15:27
  • or check this https://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform – user2021091 Sep 18 '17 at 15:28
  • I can edit this question so that I dont get flagged for repeated question – King Sep 18 '17 at 15:33
  • I have edited the question. You can review and post your answer . Thank you – King Sep 18 '17 at 15:39
  • redefined the question here. https://stackoverflow.com/questions/46305102/create-a-distinct-model-option-in-a-dropdown-using-django kindly check it out – King Sep 19 '17 at 16:14
  • Hi kindly help with this question https://stackoverflow.com/questions/46348817/django-polls-with-autentication thanks – King Sep 21 '17 at 16:48
  • Hi @user2021091 kindly assist with this question. been there for about a week but still now answer. https://stackoverflow.com/questions/46379478/django-database-migration?noredirect=1#comment79717746_46379478 – King Sep 30 '17 at 09:31