Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I stream the download of a Pandas Dataframe as a CSV using Django
In the django documents they implement streaming CSV download and it's very fast. Any idea how I can adapt that solution to a Pandas dataframe? Ideally without writing the file to disk? My code works, but it's very slow compared to the Django solution here: https://docs.djangoproject.com/en/2.1/howto/outputting-csv/ The code below implements both a streaming an non-streaming example -- switch stream to False if you'd like to see the non streaming solution. import io import pandas as pd import numpy as np from django.http import StreamingHttpResponse, HttpResponse df = pd.DataFrame(np.random.randn(100000, 4), columns=list('ABCD')) stream = True if stream: sio = io.StringIO() workbook = sio.getvalue() response = StreamHttpResponse(workbook, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="stream_download.csv"' return response else: response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="no_stream_download.csv"' df.to_csv(path_or_buf=response, index=False) return response -
Django Set & Retrieve Session Data
Im working on an eCommerce website using Django. Currently working on the cart app where im using session in django for the first time. Im having problems with setting and retrieving session data which is empty when i print it. PS: the data from the session will be used to retrieve the cart for the user or update the cart if the cart was created as a visitor. Not being able to retrieve session data result in a new session being created every time i refresh the browser. SETTINGS.PY INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # user apps 'carts', 'products', 'search', 'tags', # 3rd class app 'bootstrap4', ] 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', ] CART APP MODELS.PY from django.conf import settings from django.db import models from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) VIEWS.PY from django.shortcuts import render from .models import Cart def … -
how to fix django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library on GAE
I want to do the functionality of finding the places near me. It's about restaurants, so I have my location (latitude, longitude), and I need to get the closest restaurants within a given radius. I'm using django 2.1.7 and postgres 11.2. For the geolocation and geospacial queries postgis extension. On my computer it's working properly. This is the snippet of my code: from django.contrib.gis.geos import Point from django.contrib.gis.measure import D point = Point(float(latitude), float(longitude)) query = Restaurant.objects.filter(location__dwithin=(point, D(km=km))).order_by('location') The deployment is running on a GAE instance, and the postgres is on a Cloud SQL instance. When I do the deploy the page throws a 502 Bad Gateway and the command gcloud app logs tail -s default says: 2019-03-29 00:52:41 default[20190328t173044] Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 104, in init_process super(ThreadWorker, self).init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/srv/main.py", line 1, in <module> from marcobetetaapi.wsgi import application File "/srv/marcobetetaapi/wsgi.py", … -
unsupported operand type(s) for +: 'DeferredAttribute' and 'str'
I am trying to save a model via the admin but i keep getting this error "unsupported operand type(s) for +: 'DeferredAttribute' and 'str'". I want to return a string representation for the model. I'm new to django and stackoverflow this is what i have tried def str(self): return str(self.album_name + "" + self.artist) class Album(models.Model): album_name = models.CharField(max_length=250,) album_logo = models.FilePathField(path='music/static/music/song_logo', null=True, blank=True, recursive=True) artist = models.CharField(max_length=150) primaryid = models.AutoField(primary_key=True, null=False) @classmethod def __str__(self): return self.album_name + " " + self.artist i want to get something like 'hilltop' for example -
django.db.utils.IntegrityError 1062 Duplicate entry 'sns-N' for key 'PRIMARY'
Attempting to import data from django to object.get and update it, the error django.db.utils.IntegrityError: (1062, "Duplicate entry 'sns-N' for key 'PRIMARY') is generated. models.py class CommCdInfo(models.Model): USE_STATUS = (('Y', 'USE'), ('N', 'Not used')) comm_gpcd = models.CharField('code_group', primary_key=True, max_length=100) comm_cd = models.CharField('code', max_length=50) comm_cd_nm = models.CharField('category_name', max_length=100) comm_use_yn = models.CharField('use', max_length=100, choices=USE_STATUS) comm_sort = models.IntegerField('Sequence') register_date = models.DateTimeField() update_date = models.DateTimeField() class Meta: managed = False db_table = 'comm_cd_info' unique_together = (('comm_gpcd', 'comm_cd'),) verbose_name_plural = "contents category" admin_view.py @csrf_exempt def CommCdInfoAdmin_edit(request): if request.is_ajax() and request.method == "POST": comm_gpcd = request.POST.get("comm_gpcd") comm_cd = request.POST.get("comm_cd") comm_cd_nm = request.POST.get("comm_cd_nm") comm_use_yn = request.POST.get("comm_use_yn") if comm_gpcd is None: code = 10 msg = "wrong approach." else: print("comm_gpcd=====", comm_gpcd) print("comm_cd=====", comm_cd) print("comm_cd_nm=====", comm_cd_nm) print("comm_use_yn=====", comm_use_yn) try: commcd_Info = CommCdInfo.objects.get(comm_cd=comm_cd, comm_gpcd=comm_gpcd) commcd_Info.comm_cd_nm = comm_cd_nm commcd_Info.comm_use_yn = comm_use_yn commcd_Info.save() except CommCdInfo.DoesNotExist: print("ttttttttttttt") code = 0 msg = "modified." #retURL = "/adminbhsn/commcdinfo/" data = json.dumps({ 'code': code, 'msg': msg, #'retURL': retURL }) return HttpResponse(data, content_type='application/json') my print comm_gpcd===== sns comm_cd===== N comm_cd_nm===== naver comm_use_yn===== Y comm_sort===== 4 error message django.db.utils.IntegrityError: (1062, "Duplicate entry 'sns-N' for key 'PRIMARY'") -
Django - a href duplicate target
I run into a weird issue in my first django project in my view I have a function that generates a link dynamically based on certain form values. return '<p style="font-style:italic;"> <a href="' + baseURL + `str(xyz.pk) + '">Some text</a></p>'` When i print the output in the console it shows the correct link in example <a href="127.0.0.1:8000/xyz/20824305-d4e7-4dbd-992c-7b57bb5e477f"> I return the result of the function in my view: return render(request, 'xyz/xyz.html', {'form':form, 'url_text': generateAccessURLs(request,xyz), 'current_path': current_path }) But when I run the app and open it in the browser the target URL gets duplicated. In the HTML it looks like this: <a href="127.0.0.1:8000/xyz/ea0de6a5-5bcf-4c52-8032-dc865d660a0d">Some text</a> but when i click on the link it opens http://127.0.0.1:8000/xyz/20824305-d4e7-4dbd-992c-7b57bb5e477f/127.0.0.1:8000/xyz/ea0de6a5-5bcf-4c52-8032-dc865d660a0d In my template i have simply this: {{url_text|safe}} What am I overlooking here? Browser: Chrome, also tested deployed on a server rather than localhost. Many thanks -
django_tables2 & excelTableFilter overwrite header chevron
excelTableFilter: https://www.jqueryscript.net/table/Excel-like-Bootstrap-Table-Sorting-Filtering-Plugin.html django_tables2: https://github.com/jieter/django-tables2 excelTableFilter makes HTML tables more search/filter/sortable like excel, django_tables2 gives you more control over how a table is rendered. BUT the filter button in excelTableFilter is very large on mobile and hardly sizable. My goal was to replace the a-z, z-a sortng default of django_tables2 with the pop-up menu from excelTableFilter. After 2-3 hours of digging through here was my solution: (I'd love to get feedback / less hacky solutions) -
How to group objects by hour with django querysets?
Let's say I have a model that looks like this class Action(models.Model): timestamp = models.DateTimeField(default=timezone.now) # ... How do I, in a view, Get All actions objects Action.objects Group them into 24 brackets (using QuerySet properties, probably a group ?), like so: { 0: [Action1, Action2, Action3], # timestamp between 00:00 and 00:59, any day 1: [Action4], # timestamp between 01:00 and 01:59, any day # ... 23: [ActionN] # timestamp between 23:00 and 23:59, any day } Basically, I want to have a graph showing how many Actions were done , with a resolution of an hour. -
How to put algorithmically sorted values into an array to be used in a Django template?
I have an algorithm that sorts parents and children together into a printed list: Coding Ground. Since print returns none I can't display the list in a Django Template. This is fine nor is this the output I am looking for. What I want the algorith to do is to store all the sorted qmaQuoteAssemplyID's into an array so I can use it to call more related data and format the output in a table to use in my template. Essentially the array will be a list of sorted ID's. In my Coding Ground example you can add print(items) at the bottom and it will print the dictionary with just the qmaQuoteAssembliyID's and their relatives; {0: {0: {...}, 1: {21: {}}, 2: {22: {}, 23: {}, 24: {}, 25: {}}, 3: {27: {35: {36: {}}}, 28: {37: {}, 38: {}}}, 4: {29: {}}, 5: {34: {}}, 6: {}, 7: {}, 8: {}, 9: {}, 10: {}, 11: {}, 12: {}} What I want the algorithm output to be is just the order in which everything should be but stored in an array like so; someArray = [0, 1, 21, 2, 22, 23, 24, 25, 3, 27, 35, 36, 28, 37, … -
How to handle concurrent bids in auction app?
I am studying on starting a new Django project with reverse auctions (countdown timer). Every time a user makes a bid the price increases by a specific amount (eg 0.05$) and the clock resets. If no one bids in the given time the last bidder wins. I am thinking on using AJAX calls in order to update values and avoid page reload. But what is the best way to handle concurrent bids? Thanks in advance -
How to merge querysets of different models with foreign key relation?
I am having models in django with foreign key relation.I tried hard but unable .I am having the queryset of PropertyDetails for that queryset i want to get all the values of filestore where default image is True class PropertyDetails(models.Model): propertyname=CharField(max_length=10) dateposted=CharField(max_length=10) class Filestore(models.Model): propertyid = models.ForeignKey(PropertyDetails,on_delete=models.CASCADE) defaultimage=BooleanField() imagename=models.CharField(max_lenth=10) imgproperty=models.Charfield(max_lenth=11) for example Given: (QuerySet [PropertyDetails: P1, PropertyDetails: P2]) Task: for (PropertyDetails: P1) where defaultimage=True get values of propertyname,values of filestore table combined with it (and same for P2) The Response i want { "id":1, "propertyname":"P1", "propertyimage":["imgproperty":"property","imagename":"abc"], "id":2, "propertyname":"P2", "propertyimage":["imgproperty":"property","imagename":"xyz"] } Is there any efficient solution -
Creating Dynamic Tables Using Django
I have to create a database based on the information provided by the user in an html form. ie. using user provided attribute name, and attribute type, create an RDBMS table. I have already checked the Django documentation regarding "Dynamic Models", but it doesnt provide the necessary solution -
error is occured by url setting for action property
In the comment input form tag of Django project I set url in action as below action = {% url "blog: comment_new"%}> <form method = "post" id = "comment_form" <div class = "form-group"> {% csrf_token%} {{comment_form}} <input type = "submit" class = "btn btn-outline-primary"> </ div> </ form> An error occurred NoReverseMatch at / blog / 1 / I do not know why. Thank you if you can tell me how to fix it. -
Django JSON Serizeable Type Error with empty list
I want to create basket with elements stored in session using Django. Decimal('100') is not JSON serializable 100 is a value returned by get_shop_price() function in product model but it's not mentioned while declaring empty list. I already tried to solve this problem and I know that it doesn't occure with versy similar code in another module and also deoesn't show up when I delete line resposible for storing empty list in session. I also relized that probably sowhere along the way code tries to parse my Product class into session but I don't know why and where. Problematic Basket class from decimal import Decimal from django.conf import settings from shop.models import Product class Basket(object): def __init__(self, request): """ Inicjalizacja koszyka na zakupy. """ self.session = request.session cart = self.session.get(settings.BASKET_SESSION_ID) if not cart: # Zapis pustego koszyka na zakupy w sesji. cart = self.session[settings.BASKET_SESSION_ID] = {} self.cart = cart Piece of code that deleted removes error (and purpose of that code) self.session[settings.BASKET_SESSION_ID] = {} Very similar class that work perfectly fine from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Inicjalizacja koszyka na zakupy. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) … -
how to fix this error in pycharm when i run the server
I want to run a project in pycharm with framwork django but i get this error I used python 36 TypeError at / render() got an unexpected keyword argument 'context_instance' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.7 Exception Type: TypeError Exception Value: render() got an unexpected keyword argument 'context_instance' Exception Location: C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\xaon\app\views.py in home, line 16 Python Executable: C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\f\Scripts\python.exe Python Version: 3.6.5 Python Path: ['C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\xaon', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f\\Scripts\\python36.zip', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f\\DLLs', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f\\lib', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f\\Scripts', 'c:\\users\\hp\\appdata\\local\\programs\\python\\python36\\Lib', 'c:\\users\\hp\\appdata\\local\\programs\\python\\python36\\DLLs', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f', 'C:\\Users\\hp\\AppData\\Local\\Programs\\Python\\Python36\\dj\\f\\lib\\site-packages'] Server time: Thu, 28 Mar 2019 22:20:33 +0000 ``` -
Is it possible to link to sub-classes of an abstract model in the parent Django admin view?
I've created a base class in my Django models, and am creating multiple sub-classes to inherit these fields and store their own model fields. Is it possible for me to have the hyperlink of the base class identifier take me to the subclass object, rather than the abstract class object? Basically, I'm wanting to view all houses and stores in the single Buildings admin view, but view the full House or Store object when I click on the link in my admin. # models.py class Building(models.Model): address = models.CharField(max_length=300, verbose_name="ID", primary_key=True) date_built = models.DateField() square_feet = models.IntegerField() class House(Building): home_builder = models.CharField(max_length=100) neighborhood = models.CharField(max_length=300) car_ports = models.IntegerField() class Store(Building): store_name = models.CharField(max_length=100) annual_revenue = models.IntegerField() num_employees = models.IntegerField() # admin.py @admin.register(Building) class BuildingAdmin(admin.ModelAdmin): list_display = ('address', 'date_built') -
Displaying two datasets in one line chart
I have the following code. I am trying to display two different datasets in one line chart. I get no errors but the chart just displays one line. var data = { labels: jsonObject5, datasets: [{ label: "Data", fill: true, backgroundColor: gradientStroke, borderColor: '#d048b6', borderWidth: 2, borderDash: [], borderDashOffset: 0.0, pointBackgroundColor: '#d048b6', pointBorderColor: 'rgba(255,255,255,0)', pointHoverBackgroundColor: '#d048b6', pointBorderWidth: 20, pointHoverRadius: 4, pointHoverBorderWidth: 15, pointRadius: 4, data: jsonObject4, }, { label: "Data2", fill: true, backgroundColor: gradientStroke, borderColor: '#d048b6', borderWidth: 2, borderDash: [], borderDashOffset: 0.0, pointBackgroundColor: '#d048b6', pointBorderColor: 'rgba(155,255,255,0)', pointHoverBackgroundColor: '#d048b6', pointBorderWidth: 20, pointHoverRadius: 4, pointHoverBorderWidth: 15, pointRadius: 4, data: jsonObject6, }] }; var myChart = new Chart(ctx, { type: 'line', data: data, options: gradientChartOptionsConfigurationWithTooltipPurple }); -
Django inserts wrong domain to activation email, facebook auth and filebrowser
I've set up a Django project on a nginx server. But.. Django detects request.get_host() in signup and activation views as localhost and sends email (for activation and password reset) with links like http://localhost/.... I've set up Facebook authorization via social-auth-app-django. But Facebook tries to open redirect_uri in localhost (...redirect_uri=http:localhost/oauth/complete/facebook...) Inside django admin TinyMCE editor Filebrowser also refers to localhost.. How to fix these problems? Or it seems one solution can fix all of them. Thank you for your time and help. -
How better way to create a function to pass a JSON by serializer?
I'm studying django rest framework and would like the create a function. In this function, I need to pass a JSON list and update by serializer. For help I wrote a code example below. Serialzer example: class GarageViewSet(viewsets.ModelViewSet): queryset = Garage.objects.all() serializer_class = GarageSerializer model = Garage class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet): queryset = Car.objects.all() serializer_class = CarSerializer model = Car Well. I need to update a car list through the garage serializer. I'm thinking anything like this: (example view) class GarageViewSet(viewsets.ModelViewSet): queryset = Garage.objects.all() serializer_class = GarageSerializer model = Garage @action(detail=True, methods=['put']) def update_car(self, request): queryset = Car.objects.create() serializer = CarSerializer(queryset, many=True) return Response(serializer.data) In my tests this solution doesn't work. Would there be a better solution? Am I think wrong? -
A a means of viewing task-specific logs via Flower (or some other similar interface)
I have an application/website which I use to run tests. Whenever I run a test, a Celery task is created, and this task goes through the process of running the actual test. The test contacts a 3rd party server, so there are quite a few reasons why the task might fail or hang. This all works fine when everything's run locally; I have direct access to stdout and stderr—they pop up right on the terminal I used to start Celery's worker. If there's an error, a hangup, or any other such thing, I can see it directly, deal with it, and make sure it's handled gracefully in the future. Eventually, this will be hosted on servers that are independent of my computer, which is where the problem begins: I'd like a way to access task-specific logs to stdout and stderr (preferably, in real time). I implemented Flower thinking it might do this, but it seems that it doesn't. I've thought about saving the logs to a file, one for each task, and including a "View Log" button link on my site which would allow me to see the logs I'd otherwise see locally—but this is pretty cumbersome. Maybe I could … -
Custom theme variables not overriding bootstrap defaults
I'm using django libsass to compile scss into css. In my main.scss, my imports are as follows: /* import the necessary Bootstrap files */ @import "bootstrap/functions"; @import "bootstrap/variables"; /* override bootstrap variables with custom theme variables from darkly */ @import "darkly/darkly"; @import 'bootstrap/bootstrap'; I've followed this thread: Bootstrap 4 SCSS overrides not working However, the compiled main.css still ends up using the variables that were defined in the bootstrap/_variables.scss How do I have my variables defined in darkly/darkly.scss override the bootstrap default for use in the main.css (compiled by django-libsass https://github.com/torchbox/django-libsass) -
How to count the number of subscribers
I'm using this model to allow user to subscribe or unsubscribe to a specific game. But now I'm unsure of how to count the number of users subscribed to a specific game. class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return str(self.id) -
Why does the attribute get set but does not persist
I am trying to dynamically add an attribute to at runtime using the following snippets of code: View ... for appellation in queryset: if appellation.id in used_id_set: appellation.is_used_flag() print(appellation.is_used) # prints true as expected else: appellation.is_not_used_flag() first = queryset.first() print(first.is_used) # prints AttributeError: 'Appellation' object has no attribute 'is_used' In Model ... def is_used_flag(self): self.is_used = True def is_not_used_flag(self): self.is_used = False Why does it work correctly when in the loop but when I try to retrieve the attribute from an instance after it does not work? I have run into the same issue using setattr, appellation.is_used = True and modifying __dict__. Also is there a better way to do this? I have referenced these posts: Why can't you add attributes to object in python? I do have a dict but it does not seem to "persist" after the loop How to assign a new class attribute via __dict__? Same issue as mentioned above Dynamically defining instance fields in Python classes Same as above -
How django-rest-framwork shows me data while the relavant table is actually empty?
I'm working on a Django project which has these models: class PlaceQuerySet(models.QuerySet): def filter_by_province(self, province): ... class BasePlace: class Meta: abstract = True objects = PlaceQuerySet.as_manager() name = models.CharField(max_length=50)) ... class Hotel(BasePlace): popularity = models.PositiveSmallIntegerField(default=0) ... For some reasons i need to create a new Hotel model with different fields. So I add this to my models.py: class HotelModel(BasePlace): new_popularity = models.PositiveSmallIntegerField(default=1) ... Eventually I want to access my new HotelModel with DRF. Here is my code: class NewHotelViewSet(viewsets.ModelViewSet): serializer_class = HotelSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) queryset = HotelModel.objects.all() class HotelSerializer(serializers.ModelSerializer): class Meta: model = HotelModel fields = ( 'id', 'blahblah' ) The weird part is when I query the NewHotelViewSet it responses with data while this new model is empty. Executing HotelModel.objects.all() shows same result. I even checked Postgres and it has no data. Can someone explain this to me? Thanks. -
Url not calling view from template
I have a simple blog app handling posts and comments. When I press the a "publish" button in an html template, nothing happens. It's rather odd, because by changing the urls.py and using a different link, I can make it work. I just can't see what the difference is. Here is the link in the post_detail.html file: <a class="btn btn-outline-dark" href="{% url 'post_publish' pk=post.pk %}">Publish</a> Here is the line in the urls.py file: re_path(r'^post/(?P<pk>\d+)/publish/', views.post_publish, name='post_publish'), I can see from the hover over, that the link it wants to go to is localhost:8000/post/3/publish/, which is correct. But it's just that nothing happens. According to the server, the GET is issued: [28/Mar/2019 20:51:54] "GET /post/4/publish/ HTTP/1.1" 200 3699 I've put server messages in the models.py and views.py, but they don't get printed. Now ... here comes the weird part. If I change the post_detail.html line to: <a class="btn btn-outline-dark" href="{% url 'post_publish_2' pk=post.pk %}">Publish</a> (i.e. just change the url reference name from "post_publish" to "post_publish_2") And add this line to urlpatterns in the urls.py file for the app: re_path(r'^publish/(?P<pk>\d+)/', views.post_publish, name='post_publish_2'), Then the link becomes localhost:8000/publish/3/. This works just fine - the server calls the url, the view is called, which …