django CreateView doesn't show on ListView until rerun the server

2782 views python
7

I am trying to create an object using CreateView

class PlayerCreate(CreateView):

    template_name = 'form.html'
    model = Player
    form_class = PlayerForm
    header = "Player"

    def get_context_data(self):
        context = super(PlayerCreate, self).get_context_data()
        context['header'] = self.header
        return context

    def form_valid(self, form):
        valid = super(PlayerCreate, self).form_valid(form)
        if not self.request.user.is_staff or not self.request.user.is_superuser:
            return HttpResponse("Only authorized user can edit or create")
        return valid

It works. However, when I jump into the ListView Part, I need to rerun

python manage.py runserver

to make the new item show on the list.

I want to make it work without rerun the server. Thanks!

Below is my ListView code

class PlayerList(ListView):

    template_name = "list.html"
    header = 'Player'
    queryset = Player.objects.all().order_by("-timestamp")

    def get_context_data(self):
        context = super(PlayerList, self).get_context_data()
        context['header'] = self.header
        return context

    def get_queryset(self):
        query = self.request.GET.get("q")
        if query:
            self.queryset = self.queryset.filter(
            Q(name__icontains=query)
            ).distinct()
            return self.queryset
        else:
            return self.queryset

answered question

1 Answer

6

In this case, you should only use get_query_set() not queryset in your ListView. queryset only runs the very first time your server starts while get_query_set() works every time a request is made, that's why you only see the new element in the ListView when you rerun python manage.py runserver.

posted this

Have an answer?

JD

Please login first before posting an answer.