5

I'm trying to modify posts app from a django tutorial- https://github.com/codingforentrepreneurs/Advancing-the-Blog/tree/master/src/posts

I'm creating a new field 'userc' in a forms.py:

   userc = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True))

I've tried various methods but I'm unable to display the selected user in the template.

What should I add in views.py?

Edit: I've tried {{ obj.userc }}, {{ instance.userc }} to display the selected user in templates.

views.py

from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone

from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post

from django.contrib.auth.models import User

def post_create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404

    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        # message success
        messages.success(request, "Successfully Created")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
    }
    return render(request, "post_form.html", context)





def abc(request):

    if request.method == "POST":
      #Get the posted form
      form = PostForm(request.POST)

      if form.is_valid():
         userc = form.cleaned_data['userc']
    return render(request, 'post_detail.html', {"selected_user" : userc})

















def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    if instance.publish > timezone.now().date() or instance.draft:
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    share_string = quote_plus(instance.content)




    initial_data = {
            "content_type": instance.get_content_type,
            "object_id": instance.id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid() and request.user.is_authenticated():
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()


        new_comment, created = Comment.objects.get_or_create(
                            user = request.user,
                            content_type= content_type,
                            object_id = obj_id,
                            content = content_data,
                            parent = parent_obj,
                        )
        return HttpResponseRedirect(new_comment.content_object.get_absolute_url())


    comments = instance.comments
    context = {
        "title": instance.title,
        "instance": instance,
        "share_string": share_string,
        "comments": comments,
        "comment_form":form,
    }
    return render(request, "post_detail.html", context)

def post_list(request):
    today = timezone.now().date()
    queryset_list = Post.objects.active() #.order_by("-timestamp")
    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()

    query = request.GET.get("q")
    if query:
        queryset_list = queryset_list.filter(
                Q(title__icontains=query)|
                Q(content__icontains=query)|
                Q(user__first_name__icontains=query) |
                Q(user__last_name__icontains=query)
                ).distinct()
    paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
    page_request_var = "page"
    page = request.GET.get(page_request_var)
    try:
        queryset = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        queryset = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        queryset = paginator.page(paginator.num_pages)


    context = {
        "object_list": queryset, 
        "title": "List",
        "page_request_var": page_request_var,
        "today": today,
    }
    return render(request, "post_list.html", context)





def post_update(request, slug=None):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    instance = get_object_or_404(Post, slug=slug)
    form = PostForm(request.POST or None, request.FILES or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "title": instance.title,
        "instance": instance,
        "form":form,
    }
    return render(request, "post_form.html", context)



def post_delete(request, slug=None):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
    instance = get_object_or_404(Post, slug=slug)
    instance.delete()
    messages.success(request, "Successfully deleted")
    return redirect("posts:list")
14
  • This is impossible to answer. What do you want to do with that field? What output are you expecting? What does the rest of your view look like? Commented Jul 9, 2017 at 22:28
  • @DanielRoseman This is the rest of the app- github.com/codingforentrepreneurs/Advancing-the-Blog/tree/… . I've added a new field 'userc' to forms.py which allows you to select a user. I want this selected user to be displayed in the template. Commented Jul 10, 2017 at 9:35
  • That's still not nearly enough detail. Which view? And more importantly, what did you try in your "various methods" and what happened? Commented Jul 10, 2017 at 9:38
  • I don't understand why it is proving so difficult for you to show the actual view. Without seeing that view so we can see what you are actually doing and what objects are being sent to the context, it is impossible to help. Commented Jul 10, 2017 at 10:24
  • @DanielRoseman Updated! Commented Jul 10, 2017 at 10:29

2 Answers 2

5
+50

The code you have so far in forms.py and views.py is good. However, to display userc in the post_detail.html and post_list.html templates, you'll need to save the field to the database when the form is submitted.

One way to do this is add a userc field to the Post model:

  1. Add userc = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userc', default=1) to the Post class in posts/models.py
  2. Run python manage.py makemigrations posts and then python manage.py migrate on the command line (making sure you're in the src directory first)

Now, in the post_detail.html template, you can add {{ instance.userc }} to display the selected user.

note: related_name='userc' is required as Post already has a foreign key to the user model.

Sign up to request clarification or add additional context in comments.

Comments

0

Pass the instance as a context variable.

context = { "form": form, "instance": instance }

Set instance = None before to make it work if request.method is not POST. Templates can access only the variables that are passed as context in the view. So passing instance in the context will let you use {{instance.userc}}.

CodingforEntrepenuers is an excellent tutorial, but I would recommend to follow along more closely and get your fundamentals right.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.