Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement web socket for push notification from server to browser using react and django
I want to implement push notification using web socket in a project where front end part is implemented in reactjs and backend in django. -
How to configure datetimepicker to work correctly when only the date is selected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- XDSoft DateTimePicker --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script> <body> <input id="datetimepicker" type="text" > <script> jQuery('#datetimepicker').datetimepicker({ minDate: 0, // today minTime: 0, // now defaultSelect: false, inline: true, }); </script> </body> The problem is that when I only select the date, datetimepicker gets initialized with current time passing the validation, which I don't want because I'm using 60min default step and also because it's counterintuitive since I didn't select any time ( nor one it's selected by default - which is fine ). Any ideas on how I can make it work properly when submitting the form? I would like to stick with the inlined version. -
populating a category menu with sub-categories dynamically in djnago template
I have two django models, the first is main category table and the other is a sub-category model linked to the main model, it means each category have multiple sub categories. What is the best way to dynamically populate my template in a side menu using {% for *** %}{% endfor %} in and for exemple: here is the models.py: class cate(models.Model): ref = models.CharField(max_length=50) name = models.CharField(max_length = 100, db_index=True) slug = models.SlugField(max_length=50) def __str__(self): return self.name class subcate(models.Model): sect = models.ForeignKey(cate, on_delete=models.CASCADE) name = name = models.CharField(max_length = 100, db_index=True) def __str__(self): return self.name -
My update view isnt working when i submit the update form it dosent update the form
My update view isnt working when i submit the update form it dosent update the form. When i click the update button it just shows me the original post (unedited). if anyone could help that would be great. views.py from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.all() context = { 'post_list': posts } return render(request, "posts/post_list.html", context) def post_detail(request, post_id): post = Post.objects.get(id=post_id) context = { 'post': post } return render(request, "posts/post_detail.html", context) def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Create' } return render(request, "posts/post_create.html", context) def post_update(request, post_id): post = Post.objects.get(id=post_id) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Update' } return render(request, "posts/post_create.html", context) urls.py from django.urls import path from .views import post_list, post_detail, post_create, post_update urlpatterns = [ path('', post_list), path('create/', post_create), path('<post_id>/', post_detail), path('<post_id>/update', post_update), ] -
can we save django form data directly in django rest serializer?
class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAdminUser] def post(self, request): queryset = self.get_queryset() form = NameForm(request.POST) serializer = UserSerializer(data=form, many=True) if serializer.is_valid(): serializer.save(user=request.user) return Response({'res':'Success',status=200}) can we data directly into DB. I was trying to save form data into the model through serializer -
Page not found (404) The current path, register/POST, didn't match any of these
i am creating a blog via Django on the PyCharm editor and i have come across a 404 error. This is the full error message: Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order: admin/ register/ [name='register'] [name='blog-home'] about/ [name='blog-about'] The current path, register/POST, didn't match any of these. This is the urls.py folder in the main project folder: the 'users' and 'views' below underline in red from django.contrib import admin from django.urls import path, include from *users* import *views* as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('', include('blog.urls')), ] This is my views.py in my users folder: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages # to display a message if the form data is correct def register(request): if request.method == 'POST': # if the request is a 'post' then it will create a form form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserCreationForm() # anything not a post request it will create a blank form return render(request, 'users/register.html', {'form': form}) And the html file register in the users directory within the templates folder This is … -
django NumberInput widget does not set css class
Django version 3.0.8, basically: This works well and sets class to 'forms': description = forms.CharField(max_length=100, widget=TextInput(attrs={'class': 'forms'})) This does not set class(i also tried with 'style'): value = forms.FloatField(widget=NumberInput(attrs={'class': 'forms'})) In general I need to change the font size. Why this works only for TextInput ? Thank you in advance :) -
Django template to show information from several parameters
I have to compute a lot of information that is not stored in the db (client requirment to store only some info 🤷🏻♂️). So i have to compute it in the views.py method which is shown below. def servicesoverview(request): form = ServicesOverviewForm() data = Leistung.objects.all() #berechne Raummiete, Geraeteaufwand, Verbrauchsmaterial, Labor, Marketing, Arzt, # dict muster infos = {raummiete:'',gereateaufwand:'',...} #dict of dicts details = {id: infos, details = {} for l in data: infos = {'raummiete':0,'artik':0,'geraeteaufwand':0,'verbrauchsmaterial':0,'labor':0,'marketing':0, 'arzt':0} raummiete = 0 geraeteaufwand = 0 verbrauchsmaterial = 0 artik = 0 labor = 0 marketing = 0 arzt = 0 artikel_values = l.artikel.filter(artikel_typ=1).values('preis') for i in artikel_values: raummiete = raummiete +i['preis'] infos['raummiete']=raummiete print('Raum:'+str(raummiete)) artikel_values = l.artikel.filter(artikel_typ=2).values('preis') for i in artikel_values: artik = artik + i['preis'] infos['artik'] = artik print('Artikel:'+str(artik)) artikel_values = l.artikel.filter(artikel_typ=3).values('preis') for i in artikel_values: geraeteaufwand = geraeteaufwand + i['preis'] infos['geraeteaufwand'] = geraeteaufwand print('Geraete:'+str(geraeteaufwand)) artikel_values = l.artikel.filter(artikel_typ=4).values('preis','menge') for i in artikel_values: marketing = l.preis * (i['preis']/i['menge']) print('Marketing'+str(marketing)) artikel_values = l.artikel.filter(artikel_typ=5).values('preis') for i in artikel_values: labor = labor + i['preis'] infos['labor'] = labor print('Labor'+str(labor)) artikel_values = l.artikel.filter(artikel_typ=6).values('preis') for i in artikel_values: verbrauchsmaterial = verbrauchsmaterial + i['preis'] marketingNeu = marketing+verbrauchsmaterial*0.15 infos['marketing'] = marketingNeu print("Marketing neu:" + str(marketingNeu)) infos['verbrauchsmaterial'] = verbrauchsmaterial print("VErbrauchsmaterial: "+str(verbrauchsmaterial)) details[l.id]=infos context … -
Download zip file with Django
I'm quite new on Django and i'm looking for a way to dwonload a zip file from my django site but i have some issue when i'm running this piece of code: def download(self): dirName = settings.DEBUG_FOLDER name = 'test.zip' with ZipFile(name, 'w') as zipObj: # Iterate over all the files in directory for folderName, subfolders, filenames in os.walk(dirName): for filename in filenames: # create complete filepath of file in directory filePath = os.path.join(folderName, filename) # Add file to zip zipObj.write(filePath, basename(filePath)) path_to_file = 'http://' + sys.argv[-1] + '/' + name resp= {} # Grab ZIP file from in-memory, make response with correct MIME-type resp = HttpResponse(content_type='application/zip') # ..and correct content-disposition resp['Content-Disposition'] = 'attachment; filename=%s' % smart_str(name) resp['X-Sendfile'] = smart_str(path_to_file) return resp I get: Exception Value: <HttpResponse status_code=200, "application/zip"> is not JSON serializable I tried to change the content_type to octet-stream but it doesn't work I didn't find useful answer so far but maybe I didn't search well, so if it seems my problem had been already traited, feel free to notify me Thank you very much for any help -
Apache + mod_wsgi + django error on windows 10
I followed this guide exactly: https://www.codementor.io/@aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e I am trying to deploy my django application for the first time ever using mod_wsgi and apache on windows 10. As mentioned in the guide, I changed a few things: wsgi_windows.py activate_this = 'C:/pythonvenv/djangoproj/Scripts/activate' # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('C:/pythonvenv/djangoproj/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('C:/pythonstuff/djangoproj') sys.path.append('C:/pythonstuff/djangoproj/djangoproj') os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproj.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoprog.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd.conf i added the following two lines as given by: mod_wsgi-express module-config LoadModule wsgi_module "c:/pythonvenv/djangoproj/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win32.pyd" WSGIPythonHome "c:/pythonvenv/djangoproj" httpd-vhosts.conf # Virtual Hosts # # virtual SupervisionTool <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "logs/my_application.error.log" CustomLog "logs/my_application.access.log" combined WSGIScriptAlias / "C:\pythonstuff\djangoproj\djangoproj\wsgi_windows.py" <Directory "C:\pythonstuff\djangoproj\djangoproj"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/pythonstuff/djangoproj/djangoproj/static" <Directory "C:/pythonstuff/djangoproj/djangoproj/static"> Require all granted </Directory> </VirtualHost> # end virtual SupervisionTool Everytime i try to run httpd.exe to start my webserver, it gives the following error and then doesn't start. The error is found in the logs. [Mon Jul 06 19:31:33.542403 2020] [mpm_winnt:notice] [pid 19432:tid 748] AH00455: Apache/2.4.41 (Win32) PHP/7.3.12 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Mon Jul 06 19:31:33.542403 2020] [mpm_winnt:notice] [pid 19432:tid … -
How to solve image resize issue in Django?
I have multiple images upload in my Database, and when I am uploading image in Django then it's reducing the size of image (eg: 200km to 90 kb), but suppose if image size is 1000*800 then it's saving in the same size. I want to resize it with 600*400, Please let me know where I am mistaking in this code. please check my code, here are my models.py file import sys from django.db import models from PIL import Image from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile class ProductImage(models.Model): product=models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image=models.ImageField(upload_to='product_image',blank=False,null=True) def save(self, *args, **kwargs): if not self.id: self.image = self.compressImage(self.image) super(ProductImage, self).save(*args, **kwargs) def compressImage(self, image): imageTemproary = Image.open(image) outputIoStream = BytesIO() imageTemproaryResized = imageTemproary.resize((600, 400)) imageTemproary.save(outputIoStream, format='JPEG', quality=60) outputIoStream.seek(0) image = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return image -
Trying to make the program add a string after an id
I am trying to make a button take me to http://127.0.0.1:8000/admin/Inventory_Management/item/7/delete/ well with url i added it takes me to http://127.0.0.1:8000/admin/Inventory_Management/item/7. without the '/delete' am trying to add, but i don't quite know how, even after some research it's still not working. related view def Warehouse(request, pk): Warehouse = warehouse.objects.get(id=pk) items = item.objects.all() context = { 'items': items, 'warehouse': Warehouse, } return render(request, 'Inventory_Management/warehouse.html', context) related url path('admin/Inventory_Management/item/<str:pk>/', Warehouse, name="change_"), button <a href="{% url 'change_' item.id %}" class="btn btn-danger btn-sm" role="button"> x</a> I tried the following, but as i expected, it didn't work... <a href="{% url 'change_' item.id/delete %}" class="btn btn-danger btn-sm" role="button"> x</a> sorry, if this is a silly question. I am not a great programmer yet. any help appreciated! please help! -
Django-storages with Dropbox backend with error in the images of the Wagtail website
I have a Wagtail site where I'm using django-storages with the Dropbox backend. It works fine in my development environment but I'm having an error when using it on Heroku. Every time I try to access the admin/images page or add an image to a page the application crashes. The document storage works fine even on Heroku, so I think the problem might be related to how the image is defined in my page class (below) but I couldn't find what would be the proper way of declaring it for django-storages. background_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) Here is the StackTrace for when I try to access the admin/images page in Wagtail: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File … -
What is the right App Domain to input in developers.facebook.com now that i deployed my project in heroku?
I deployed my django project on heroku and my project have facebook login. And now that my project is deployed to a webhost it now has a domain name given by heroku. The website name looks like this since I'm using their free service. https://mywebsite.herokuapp.com I tried to use that as App Domain in facebook developer site but everytime I tried logging in this is what facebook tells me. Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. What is the right App Domain that I should input? -
API KEYS for Django
Could you please pinpoint me to the information, article, example, book, django documentation... of how to hide api keys while url queries in django to connect to external web site... I looked through many comments, which would use like github or extra programs, which needs to be installed into django environment..., which some professionals say it is still a bad practice. I tried couple of ways, like using .env and gitignore, but it didn't work for me... The api key returns from .env as None. POST wouldn't work for me either, because I return the query from view function, not from form... The closest explanations, which makes most sense, I saw, is to use javascript or external proxy servers(?)... The thing is these articles just explain how to do this on the surface, without going into details or explaining practices... Is there anywhere, good and detailed explanations on this certain topic? Thank you -
Please help in dJango, I have been trying to solve it for ten days?
*...Hi, I've been learning Gango a month ago There is a problem that stopped me ten days ago He found confusion too, please help him The problem when clicking on the password does not enter the page given error vewis from django.shortcuts import render from django.http import HttpResponse import random from django.shortcuts import render def home(request): return render(request,'home.html') def password(request): thepassword = 'testing' chr = list('asdfghjklpoiuytrewqzxcvbnm') lenth = int(request.GET.get('length',12)) thepassword = '' for x in range(lenth): thepassword += random.choice(chr) return render(request,'password.html',{'password':thepassword}) Create your views here. home.html password where <form action="{% url"password"%}> 6 7 8 9 10 11 <option value="12"select="selected">12 13 14 uppercase Numper ch-mo password your oassword is: {{Password}}**** -
Use Django Form data without being saved to a database
I'm working on a django application the uses a form. The form is a list of countries which when submitted shows the covid-19 statistics from an API. The problem I'm having is that I don't quite understand how I'll use country = form.cleaned_data['country'] for querystring = {"iso":"PHL"} if its inside if request.method == 'POST':. I hope you understand my point. Have a nice day! views.py from django.shortcuts import render from django.http import HttpResponse from .models import CountryChoice from .forms import PersonForm from django_countries.fields import CountryField import datetime import requests url = "https://covid-19-statistics.p.rapidapi.com/reports" querystring = {"iso":"PHL"} headers = { 'x-rapidapi-host': "covid-19-statistics.p.rapidapi.com", 'x-rapidapi-key': "aa8e138180msh511e11bd33068d9a1b68185sn0e1f6cdged96" } response = requests.request("GET", url, headers=headers, params=querystring) data_json = response.json() today = datetime.datetime.utcnow().date() data = [ { 'date' : data_json['data'][0]['date'], 'cases' : data_json['data'][0]['confirmed'], 'recovered' : data_json['data'][0]['recovered'], 'deaths' : data_json['data'][0]['deaths'], 'yesterday' : today-datetime.timedelta(days=1), }, ] def home(request): countrycode = [] context = { 'data' : data, 'country' : CountryChoice(), 'countries': PersonForm(), } if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): country = form.cleaned_data['country'] countrycode.append(country) return render(request, 'home\home.html', context) -
django crud server always return 404
i tring to create a very simple crud server using django but i always get 404 not found and i not sure why i'm shering all my code (hope it's not too long) glad to your help here my setting.py DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', 'rest_framework', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('leads.urls')), leads.serializers.py from rest_framework import serializers from leads.models import Lead class LeadSerializers(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' leads.urls.py from rest_framework import routers from .api import LeadViewSet router = routers.DefaultRouter() router.register('api/leads', LeadViewSet, 'leads') urlpatterns = router.urls my post http request is http://localhost:8000/leads/ with a simple body -
Django Oracle OCA-24450
So I recently had an error with the default oracle db.backend of django. I performed a raw query directly on my db and it throw me an "django.db.utils.DatabaseError: ORA-24450: Cannot pre-process OCI statement". I knew the query itself was valid, because it ran in the old flask application as well as in table plus. I googled and did not really find anything useful on that topic, other than the generic error description. I will put the answer for future readers here. Hopefully it is helpful. -
Django filtter- Conditional Query
Say I have 2 models, class Product(models.Model): name = models.CharField(blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE,blank=True, null=True) scale = models.CharField(blank=True, null=True) class Company(models.Model): name = models.CharField(blank=True, null=True) scale = models.CharField(blank=True, null=True) I have following filters products = Products.filter.objects(scale__isnull = False, scale__in = ['L1','L2']) products_2= Products.filter.objects(scale__isnull = True, company__scale__in = ['L1','L2']) is it possible to combine these filters into 1? -
Django : edit profile using AbstractBaseUser
in my django project, I use AbstractBaseUser to register a new user. I use set_password to define his password for it to be encrypted. Now I want to create a view for editing a profil. I want the password to be able to be change and to be encrypted. I've already create a view, but the password isn't encypted in the databse when I edit it... These are my files: models.py class memberArea(AbstractBaseUser): username = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) phone = models.TextField() date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) deliveryAddress = models.TextField() postalCode = models.CharField(max_length=255) forget = models.TextField(null=True, blank=True) city = models.CharField(max_length=255) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'phone', 'deliveryAddress', 'postalCode', 'city'] objects = MyAccountManager() serializers.py from django.contrib.auth.hashers import make_password ... class AccountSerializer(serializers.ModelSerializer): class Meta: model = memberArea fields = ['username', 'email', 'phone', 'password', 'deliveryAddress', 'postalCode', 'city'] extra_kwargs = { 'password': {'write_only': True}, } def validate_password(self, raw_password): return make_password(raw_password) views.py #Edit account @api_view(['PUT', ]) def edit_account(request, pk): try: account = memberArea.objects.get(pk=pk) except memberArea.DoesNotExist: return HttpResponse(status=404) if request.method == 'PUT': serializer = AccountSerializer(account, data=request.data) data = {} if serializer.is_valid(): serializer.save() data['response'] = 'Account updated with … -
Muting errors raised by middleware
Our app supports arbitrary domains, which means ALLOWED_HOSTS = ['*'] but we handle them manually with a custom middleware: class AllowedHostMiddleware(object): def process_request(self, request): if not domain_allowed(request.get_host()): raise DisallowedDomain('Invalid domain: {}.format(domain') Problems: a giant log file is being created because it's logging every random host on the web, basically crawlers custom error handling middleware doesn't work because it works only with exceptions thrown by views, not by other middleware. My understanding is that the way ALLOWED_HOSTS work natively is that is just eats disallowed requests and doesn't log them. How can I do the same with my own middleware? Or how can I handle DisallowedDomain exceptions and route them to a different log? The middleware should block the request but it shouldn't treat it as an error otherwise it's going to get logged, pollute the log files and contribute to their massive size. I'm on Django 1.8. -
what is the most preferable way to send notification from server to browser? [closed]
I am working on a project in which front-end is implemented in reactjs and back-end in django.Postgresql database has been used for storing data. But now push notification part is needed to implement to send notification to some particular users. I want to implement from scratch. I have found out web socket can be a way to send data or notification from server to browser And i want to implement it. Is there any proper documentation where i can get proper guideline to implement it. -
Django Crispy Forms extra class only for the input field
Closely related to this question, I want to use an input spinner for a field generated by crispy fields. The "price" label should stay the same, but "price" input should become of type form-control step='0.01' value='0.00' min='0' max='10000' data-decimals='2' to take care of the input spinner options. Formset: class PartPriceFormset(ModelForm): required_css_class = "required" class Meta: model = PartPrice fields = ("price", "customer",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout(Row(Column('price', css_class="form-group col-md-6 mb-0"), Column('customer', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Submit('submit', 'update price')) I already tried to switch "price" to something like Div(Field('price') but then again, this affected the label AND the input field. The template is rather simple: {% extends 'base.html' %} {% load crispy_forms_tags %} {% load humanize %} {% block title %} Update part price {% endblock title %} {% block content %} {% crispy form %} {% endblock content %} {% block custom_js %} <script type="text/javascript"> $("input[type='number']").inputSpinner() </script> {% endblock %} -
Get list of memberships for a user from the users model using generic listview
I want to create a view that shows a list of memberships fot a specific CustomUser. The view i have only shows a list of memberships for the logged in user. How can i achive this with generic.listview? i want the list to show all the memberships for a specific user by passing the PK from CusomUser can anybody help me with this? URL path('<int:pk>/membership/', views.MemberShipIndex.as_view(), name='MemberShipIndex'), View class MemberShipIndex(generic.ListView): model = Membership template_name = 'members/membership_list.html' context_object_name = 'membership_list' def get_queryset(self): return self.model.objects.filter(CustomUser=self.request.user)