Home > other >  Django How to retrieve data based on their pk
Django How to retrieve data based on their pk

Time:08-21

I want a staff Dashboard which can see all user data and also CRUD it. how can I dynamically filter for the pk of the user data. If I use objects.all I get everything but cant edit specific values

from django.contrib.auth.mixins import UserPassesTestMixin
class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):

    def test_func(self):
        return self.request.user.is_superuser or self.request.user.is_staff




class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView):
    model = SchulverzeichnisTabelle
    template_name = 'SCHUK/Dashboard.html'
    context_object_name = 'Dashboard'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all()


        return context

CodePudding user response:

You edit an item with an UpdateView [Django-doc], so:

from django.views.generic import UpdateView


class DashboardView(AdminStaffRequiredMixin, ListView):
    model = SchulverzeichnisTabelle
    template_name = 'SCHUK/Dashboard.html'
    context_object_name = 'Schulverzeichnis'


class SchulverzeichnisUpdateView(AdminStaffRequiredMixin, ListView):
    model = SchulverzeichnisTabelle
    template_name = 'SCHUK/edit_schulverzeichnis.html'

In the url.py you make then an entry to edit the item:

# app_name/urls.py

from django.urls import path

urlpatterns = [
    path('dashboard/', DashboardView.as_view()),
    path(
        'dashboard/schulverzeichnis/<int:pk>/edit/',
        SchulverzeichnisUpdateView.as_view(),
        name='edit-schulverzeichnis',
    ),
]

In your DashboardView template, you then link to the edit for that view:

<a href="{% url 'edit-schulverzeichnis' pk=obj.pk %}">edit</a>

with obj the object that you use in the ListView. In the edit_schulverzeichnis.html template, you then can use the {{ form }} and submit a POST request to the same view to update.


Note: Models normally have no Tabelle suffix. A model is not a table, it is stored in a relational database as a table, but even then it has extra logic like validators, managers, etc.


Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class to DashboardView, instead of Dashboard.

CodePudding user response:

i don't know your model, and how it related to user, but i can imagine:

class Dashboard (...):

    # any staff here

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.filter(author=self.request.user)
        return context

By the way, try to use only englisch language in code. If you start to work in team, this knowledge helps.

  • Related