Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse migration id column primary key
I have a table that had an id uuid primary key column. And i want to change this column into Char primary key column. So i did a migration that removes the field and then re-add. When i migrate everything migrates successful. But if i reverse the migration i get django.db.utils.IntegrityError: column "id" contains null values when tries to execute the following sql ALTER TABLE "Test" ADD COLUMN "id" uuid NOT NULL PRIMARY KEY. Below is my migration operations: operations = [ migrations.RemoveField( model_name='employee', name='id', ), migrations.AddField( model_name='employee', name='id', field=models.CharField(default='abcd', max_length=100, primary_key=True, serialize=False), preserve_default=False, ), ] -
coverage showing 100% for settings.py file
I'm confused with coverage report which is generated with help of pytest. Here is my coverage html report. settings.py file is showing 100% covered, not sure how it is.. ? Also, the following Loginform also shown as covered so I have added another dummy form even it is showing covered. I'm facing difficulty in understanding this, though I don't have any tests added for settings or for the above forms it's showing as 100% covered, with this I'm not confident whether my code is properly tested or not. -
Django Query how to display a count of records with a distinct dates and display date and count
I'm trying to create a Django query that as output will give me a list of dates and the count of records against those dates. This is my current query which gives me a count of distinct dates as {'dates':2} stats = models.SearchResultStat.objects.values().filter(organisation=organisation.id).annotate(date=TruncDate('created')) \ .values('date') \ .distinct() \ .aggregate(dates=Count('date')) But what I need is [{'2020-11-01' : 2},{'2020-11-02' : 1}] How do I achieve this? -
Forbidden (403) - CSRF verification failed. Request aborted in django when load in Iframe
Django CSRF error in Iframe. When I'm trying to log in its raises the error. Otherwise, it's work fine Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. I'm used LoginView for login also declared {% csrf_token %} in template form. -
Incomplete response format while displaying large number of users in get request?
This is my api view class UserListViewSet(ListModelMixin,GenericViewSet): serializer_class = UserListSerializer permission_classes = [IsAuthenticated] # pagination_class = BasicPagination authentication_classes = [TokenAuthentication, ] queryset = User.objects.filter(is_approved=True) I have the huge number of users more than 7000 users. This api used to give all the users in correct format when users were around in 3-4000 but when the users list get around 6000 then the response is displaying like this. [ { "first_name": "first name", "middle_name": null, "last_name":"last name" # user list ends in this format When I test locally if the users are few then there is no problem in response. I am testing the api in postman. Why is this happening ? How can solve this ? -
JavaScript doesn't change in the Browser
I am working on project with Django, when i edit a JavaScript script the Browser does not show changes. It keeps the old version -
how to save html dropdown value to database (django)
i have a form like this: <form action="/processing/save/" method="POST"> <table class="content-table"> <thead> <tr> <th class="tweet">Tweets</th> <th class="type">Tipe Data</th> <th class="manual">Sentimen Manual</th> <th class="auto">Sentimen Otomatis</th> </thead> <tbody> {% for tr in db_training %} <tr> <td class="tweet">{{tr.tweets}}</td> <td class="type">{{tr.dtype}}</td> <td class="manual"> {{tr.manual}} &nbsp; <select id="dstrain_{{ forloop.counter }}" onchange="gettrain(this)"> <option selected disabled="true">Pilih</option> <option value="negatif">Negatif</option> <option value="netral">Netral</option> <option value="positif">Positif</option> </select> </td> <td class="auto">{{tr.auto}}</td> </tr> {% endfor %} </tbody> </table> {% csrf_token %} <div class="processing"> <input class="btn_save" type="submit" value="SIMPAN"> </form> it looks like this: what i want to do is when i click save, the value from dropdown will be inserted to my database (in column "manual"). heres the database: is it complicated? i just started learning django. -
How can I serialize a nested model m2m field to self with django-rest-framework?
I have a User model that has a m2m relation to itself called friends and I'm trying to serialize it to see and update the pk's of users that are in the relation. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('Email', max_length=254, unique=True) name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False) friends = models.ManyToManyField("User", related_name='user_friends', blank=True) serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField( write_only=True, required=False, help_text='Leave empty if no change needed', style={'input_type': 'password', 'placeholder': 'Password'} ) # for setting the password class Meta: model = User fields = ('pk', 'email', 'name', 'friends', 'password') def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) When I go to my API I see the following: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ "http://localhost:8000/user_detailAPI/2/" ], } } but I would like for the serializer to display each friend in a list in a manner like this: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ 2 ], } } Plus if you could let me know how I would be able to add an object to friends field using POST or PUT request it would be nice because I am new to django-rest-framework and I feel like this is an … -
What is the correct format for adding data in Djongo Arrayfield?
I am using mongodb as my database and I have use djongo as my connector. The database connection is working fine. I have used models.ArrayField in Movie Model. When I try to add the tag in through the admin panel it shows the error as shown below.. [![enter image description here][1]][1] Here is my code from django import forms class Tag(models.Model): tag = models.CharField(max_length=200) class Meta: abstract = True def __str__(self): return self.tag class TagForm(forms.ModelForm): class Meta: model = Tag fields = ( 'tag', ) class Movie(models.Model): movie_name = models.CharField(max_length=255) tags = models.ArrayField( model_container=Tag, model_form_class=TagForm ) objects = models.DjongoManager() def __str__(self): return self.movie_name``` [1]: https://i.stack.imgur.com/li1B7.png -
use record from same model as foreignkey in django
my model is as follows : class Profile(model.Models): name = models.CharField(max_length = 20) full_name = models.CharField(max_length = 20) husband_spouse = models.ForeignKey(Profile, on_delete=models.CASCADE) on doing python manage.py makemigrations I get the following error : NameError: name 'Profile' is not defined Question : How should I use another record of the same model as a foreignkey in my current model TIA -
AttributeError: 'list' object has no attribute 'order_by'
I was trying to combine two queryset objects by itertools chain python predefine function and filter this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'. If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. views.py : try: qs = Conversation.objects.filter( Q(chat__from_user=user) & Q(chat__to_user=to_user)) qs_2 = Conversation.objects.filter( Q(chat__from_user=to_user) & Q(chat__to_user=user)) except: raise ValidationError({"message":"bad request"}) all_qs = list(chain(qs, qs_2)).order_by('-created_on') -
Django Redirecting to a created view (pk)
I am trying to redirect to a created post after filling up the form. I tried following Django redirect to created post after form but I encountered this error TypeError at /inquiry/ inquiry() missing 1 required positional argument: 'pk' def inquiry(request,pk): form = RescueeForm() if request.method == 'POST': form = RescueeForm(request.POST) if form.is_valid(): form.save() return redirect ('rescuee' form.pk) context = { 'form' : form } return render(request, "inquiry_page.html", context) urls.py urlpatterns = [ path('', views.index, name='index'), path('inquiry/', views.inquiry, name='inquiry'), path('rescuee/<int:pk>', views.rescueeview, name='rescuee'), ] -
Django filtering in bootstrap
I try to filter username from my all users in django and I need to have some forms in bootstrap. What I did is: <div class="form-group col-4 text-left"> <label for="exampleFormControlInput1">User Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="username" {{customer_filter.form.username}}> </div> It is working but in my page I have extra > printed on my page. I don't know how to use {{customer_filter.form.username}} in bootstrap in label tag. -
ValueError('Related model %r cannot be resolved' % self.remote_field.model)
while using AUTH_USER_MODEL django throwing error. while adding my own custom model to authenticate login.when i run command python manage.py migrate it give me an error, i actually want to create a custom user model to authenticate login to my own custom admin login my settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'g4!we933keyd4p*2z*1rz)=zl%s9qi#21^to$@*79e6rz8bj1e' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'farmingwave',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static') ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'seo.guru.tech00@gmail.com' EMAIL_HOST_PASSWORD = 'working12090' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',] AUTH_USER_MODEL = 'farmingwave.CustomUser' my models.py from django.db import models from django.forms import ModelForm from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser, BaseUserManager from django.conf import settings class CustomUser(AbstractUser): Username = models.CharField(max_length=255, unique=True,default='root') password = models.CharField(max_length=50,) my admin.py from django.contrib import admin from .models import contactForm from .models import writerForm from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import LoginForm from .models import CustomUser class CustomUserAdmin(admin.ModelAdmin): form = LoginForm model = CustomUser admin.site.register(CustomUser,CustomUserAdmin ) class Meta: db_table = 'user_auth' class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How can i override the save() method in admin page
it maybe look like a simple question, but i been struggling for weeks now, i want to override the save method in admin page, for a model name Transaction that i created, i want to pre save each transaction by groups.. lets say for example i have created 2 groups (Test1, Test2) and i assigned users to each group, and a user from group Test1 made a transaction and saved it. i want all users from Test1 group to see the transaction and modify it, but not Test2 groups members. I override save method and queryset method, but yet it still not working. any ideas ? here is my code class TransactionAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user.groups print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__in=request.user.groups.all()) -
Adding "group" field in Django User Admin
I am trying to add a "group" field to show group permissions on the user panel in Django 3.1.2. I tried combining this and this, but always end up in either end up with The model User is already registered with 'auth.UserAdmin' or The model User is not registered (when trying to unregister first): from django.contrib import admin from django.contrib.auth.models import User # fails in "model User not registered" admin.site.unregister(User) #fails in already registered with auth.UserAdmin @admin.register(User) class UserAdmin(admin.ModelAdmin): def group(self, user): return ' '.join([g.name for g in user.groups.all()]) list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', group] list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active'] How would I correctly register my custom UserAdmin? -
Django adding data into model from nested json returning TypeError: 'NoneType' object is not subscriptable
I am using a third-party API to get data and add it into my database via objects.update_or_create() method. This data has many records and some of the fields in the response only exists for certain records. Below the a snippet of the JSON that is returned from the API. However this data is only present for some of the records in the JSON response. When I try to add this data into my model, I am getting the following error: 'f_name': i.get('card_faces')[0].get('name'), TypeError: 'NoneType' object is not subscriptable I am trying to have it so that if the card_faces field exists, True is added to the card_face column in the database, and then the card_faces name to the database. If card_faces doesn't exist, then False is added to the card_face column in the database, and subsequent fields are null. JSON: { "data": [ "name": "Emeria's Call // Emeria, Shattered Skyclave", "card_faces": [ { "object": "card_face", "name": "Emeria's Call" }, { "object": "card_face", "name": "Emeria, Shattered Skyclave" } ], ] } views.py: for i in card_data: Card.objects.update_or_create( id=i.get('id'), defaults={ 'name': i.get('name'), 'card_faces': i.get('card_faces'), 'f_name': i.get('card_faces')[0].get('name'), 'b_name': i.get('card_faces')[1].get('name'), } ) -
How to give the json data in post api request in django rest framework
I am new to the Django rest framework, please guide me where I made a mistake, I want to make the API that takes two arguments cat name (which is char field) cat fields (which is JSON field) I want to put dynamic JSON fields, like it upon the client that they will add the 4 fields data with key pairs in JSON or any number of fields, I hope so you all guys would understand my query Please help me, it will really appreciate Here is my Views.py @api_view(['POST']) @parser_classes([JSONParser]) def add_cateogry_with_fields(request, format=None): if request.method == "POST": insert_Serializers = AddCategoryWithFieldsSerializer(data=request.data) if insert_Serializers.is_valid(): insert_Serializers.save() return Response(insert_Serializers.data, status=status.HTTP_201_CREATED) else: return Response(insert_Serializers.data, status=status.HTTP_400_BAD_REQUEST) and here is the serializer class serializer.py class AddCategoryWithFieldsSerializer(ModelSerializer): category_name = serializers.CharField(max_length=34) category_fields = serializers.JSONField() class Meta: model = CategoryModel fields = ('category_name', 'category_fields') the Model.py class is class CategoryModel(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=255) category_fields = models.JSONField() parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True) class Meta: db_table = 'category' enter image description here -
Pass id user to view function
I try pass id by template to view but I have MultiValueDictKeyError at /accounts/profile/1 <a class="nav-link" href="{% url 'accounts:profile' request.user.id %}">{{request.user}}</a> path('accounts/profile/<int:id>', views.profile, name="profile"), def profile(request, id): user = User.objects.get(id=int(request.POST[id])) return user -
Need 2 values to unpack in for loop; got 4
I'm new to Django, and trying to pass api results (dictionaries within a list) to a template using context. I have tried doing this {% if apiList != "Error..." %} {% for i in apiList %} {% for key, value in i %} {{ key }} {{ value }}<br> {% endfor %} {% endfor %} {% endif %} but I get the error Need 2 values to unpack in for loop; got 4. When I do the same code but take out the value, so it just searches for the keys, it works fine and prints out all the keys on a new line. I've also tried the following code: {% for key, value in apiList.items %} {{ key }} : {{ value }} {% endfor %} but this does not seem to work either, it does not give an error, but nothing shows on the screen. Any idea how to solve this problem? Here is my code in the views.py try: apiList = json.loads(api_request.content) except Exception as e: apiList = "Error..." return render(request, 'financials.html', {'apiList': apiList}) else: return render(request, 'financials.html', {}) Thanks! -
Django log to file by date
I am trying to create log files for Django application by using logging.handlers.TimedRotatingFileHandler class. but i am getting error. In setting.py i am adding this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s|%(asctime)s|%(module)s|%(process)d|%(thread)d|%(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(path, 'django.log'), 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 365, }, }, 'loggers': { 'django': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True, }, }, } but I am getting following errors --- Logging error --- Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 72, in emit self.doRollover() File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 397, in doRollover if self.backupCount > 0: TypeError: '>' not supported between instances of 'str' and 'int' Call stack: File "/home/mohsin/demo/bin/gunicorn", line 8, in sys.exit(run()) File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() -
i have proplem with pip resolver 2020
i am trying puplish my django project on Cpanel i had used pip install django==2.1 --use-feature=2020-resolver for install all my package but i got following error this error han't appear on my PC Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ ....... line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module
I followed the this video while installing the django debug toolbar as well as the docs. However, I just cannot get it to work. The mime type error keeps popping up in the console tab of the dev tools. settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'this is secret' DEBUG = True if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) INTERNAL_IPS = [ '127.0.0.1', ] ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'demo.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'mdeia') # … -
Understanding Model Permissions in Django 3.1
I have some troubles understanding how Django 3.1 checks permissions, especially how model permissions versus default permissions are handled. I have the following model: from django.db import models class MyModel(models.Model): class Meta: permissions = [("finalize", "Can finalize"),] is_final = models.BooleanField(default = False) which defines a new finalize permission for this model. With the model along we have a model admin: from django.contrib import admin from django.contrib.auth import get_permission_codename from .models import * class MyModelAdmin(admin.ModelAdmin): actions = ['set_final', 'remove_final'] def set_final(self, request, queryset): queryset.update(is_final=True) set_final.allowed_permissions = ('finalize',) def remove_final(self, request, queryset): queryset.update(is_final=False) remove_final.allowed_permissions = ('finalize',) # Permissions def has_change_permission(self, request, obj = None): if obj and obj.is_final: return False codename = get_permission_codename('change', self.opts) print("has_perm(change) : %s.%s : %s" % (self.opts.app_label, 'change', request.user.has_perm('%s.%s' % (self.opts.app_label, 'change')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, codename)) def has_finalize_permission(self, request, obj = None): codename = get_permission_codename('finalize', self.opts) print("has_perm(finalize): %s.%s : %s" % (self.opts.app_label, 'finalize', request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')) admin.site.register(MyModel, MyModelAdmin) which defines two actions: setting and removing the is_final flag from objects. Along with it, the has_change_permission is redefined because the … -
Django Choices Object Not passing id to URL
I'm using a model with a choices field that is being displayed by a form. I want to create a delete function in my views.py but can't get it to work. I suspect it's because my model object is not passing an id, or my url just isn't picking the object's id for whatever reason. Here's my model. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) Here's the delete function I'm trying to make in views.py def delete_player(request, id): player = Player.objects.get(id=id) player.delete() return redirect('show') and my url path('delete_player/<int:id>', views.delete_player, name="delete_player") I know that I obviously need an id to be passed to both the url and delete function in views.py, but I don't know how to get the id from my model. I'd appreciate any help/another set of eyes on the problem. Thanks in advance.