0

I have created this application but the problem I face now is one that has kept me up all night. I want users to be able to see and select only their own categories when they want to create a post. This is part of my codes and additional codes would be provided on request

category model

class Category(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='categories_created')
    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,
    }
    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
  • It looks like you need to add a field to your Category model so it's associated with a specific user. If that doesn't help you may need to provide more information as to what is going wrong in your view. – J. Owens Sep 19 '17 at 16:13
  • Can you share the code that renders the actual form view. It looks like the view you shared is the POST handler. – amacf Sep 19 '17 at 16:15
  • I added a user field in my category model but it still shows all the categories irrespective of the logged in user – King Sep 19 '17 at 16:16
  • @amacf I added it and updated the question. Kindly check it out – King Sep 19 '17 at 16:18
  • What happens if you change `Category.objects.filter(category_created__user=user)` to `Category.objects.filter(user=user)`? – J. Owens Sep 19 '17 at 16:24
  • it is still the same thing. `categories = Category.objects.filter(user=user)` is not referenced in the form. That is where I think the problem is coming from but I dont get it – King Sep 19 '17 at 16:28
  • Thanks it has been solved – King Sep 19 '17 at 16:50

1 Answers1

1

What you need to do is well-described here. Basically, you are using ModelForm which generates the form from your model. Your model doesn't know anything about filtering by user, so you will need to explicitly add a QuerySet to your form that only shows the desired categories. Change your "categories = ..." line to something like:

form.category.queryset = Category.objects.filter(user=user)

form.fields['category'].queryset = Category.objects.filter(user=user)</strike>
amacf
  • 257
  • 2
  • 8