Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ResolutionImpossible - Conflicting dependencies while deploying on heroku
While deploying a Django + React project on Heroku, this error occoured: The conflict is caused by: djoser 2.1.0 depends on social-auth-app-django<5.0.0 and >=4.0.0 rest-social-auth 8.0.0 depends on social-auth-app-django<6.0 and >=5.0 If I downgrade to social-auth-app-django==4.0.0 pkg, then get this error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'backend.wsgi.application' could not be loaded; Error importing module. This error is caused by social_django which is added in settings.py MIDDLEWARE = [ .... # For social auth 'social_django.middleware.SocialAuthExceptionMiddleware', .... ] Fixed this error by removing/commenting it out, then found another one: cannot import name 'urlquote' from 'django.utils.http' (lib\site-packages\django\utils\http.py) Because urlquote() is no longer available in Django 4.0+ versions, after downgrading social-auth-app-django==4.0.0 pkg. This try to import from django.utils.http import urlquote in filelib\site-packages\social_django\context_processors.py. I'm in Dependency hell. I have even tried to downgrading the djoser pkg, then got other errors. After searching a lot, I found this blog post, according to this: First, pip install pip-tools then create a requirements.in file and add django djangorestframework then run pip-compile ./requirements.in this will generate requirements.txt file: # This file is autogenerated by pip-compile with Python 3.9 # by the following command: # # pip-compile ./requirements.in # asgiref==3.6.0 # via django django==4.1.5 # via # -r ./requirements.in # … -
In Django, how to filter a _set inside a for loop?
I have these two models: class Convocacao(models.Model): cursos = models.ForeignKey(Cursos) class RegistroConvocacao(models.Model): convocacao = models.ForeignKey(Convocacao) I get a specific object from Convocacao: obj = get_object_or_404( Convocacao.objects.prefetch_related("cursos", "registroconvocacao_set"), pk=pk, ) Now, while the for loop runs through obj.cursos, I need to filter obj.registroconvocacao_set inside the loop: for curso in obj.cursos.all(): obj.registroconvocacao_set.filter(...filters...)... However, in each iteration of the for loop, obj.registroconvocacao_set.filter() makes a new query to the database, generating thousands of accesses to the database and repeated queries. How do I prefetch obj.registroconvocacao_set to avoid this? -
DEBUG=True is in your settings file and you have not configured any URLs
This junk is trippin. I have the app registered in installed apps, I have my templates directory set up properly, and I even have all the urls configured in both urls.py files. What am I doing wrong? (https://i.stack.imgur.com/CsosC.png)(https://i.stack.imgur.com/g6RA5.png)(https://i.stack.imgur.com/JIVJa.png)(https://i.stack.imgur.com/ausuN.png) I was expecting it to work, what else? -
Any way to speed up case-insensitive Django UniqueConstraint?
The Django docs show this example UniqueConstraint: UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category') First off, the desc() produces errors in the admin interface. (Edited version below.) ProgrammingError at /admin1/app/tablename/add/ syntax error at or near "DESC" LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO... ^ Request Method: POST Request URL: http://host/admin/app/tablename/add/?_changelist_filters=a_val Django Version: 4.1.5 Exception Type: ProgrammingError Exception Value: syntax error at or near "DESC" LINE 1: ...lename" WHERE LOWER("tablename"."name") DESC = (LO... Okay, never mind that. Let's drop desc(). And, I don't have two fields, I only have one. So look at this UniqueConstraint: UniqueConstraint(Lower('name'), 'name', name='unique_lower_name') When I load data into that table in Postgres (13 or 14, say), it's quite slow. Is there an easy way to speed up having a constraint that says "Only one version of this name (ignoring case) should be in the table"? I could drop the constraint. I could also add a field that's all lowercase and put a unique constraint on that field. It would be extra DB info (a cache), but for performance sake. -
Can't create superuser in Django using custom user
I got this error when i try to run manage.py createsuperuser TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' My User model: class User(AbstractUser): name = models.CharField(max_length=32) email = models.CharField(max_length=140, unique=True) password = models.CharField(max_length=140) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] and in my settings.py file: AUTH_USER_MODEL = 'usuarios.User' How can i solve this? Im new in Django, documentation is confused to me... I already tried remove AUTH_USER_MODEL = 'usuarios.User' or remove username attribute from class User -
How to return JsonResponse without using Return in Django
Am building a USSD app that requires me to send a return JsonResponse but i want to do it without using Return. Beacuase i want to a couple of things after the return payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type_msg, "USERDATA": text, "SESSIONID": session_id, "MSG": response, } return JsonResponse(payload) -
Django Authentication, should frontend connect to remote database using API or SSH key?
I'm new to backend and now in my backend, I have a database and server connecting, I'm trying to build a login and registration function. And in my frontend, I'm not connecting to my database directly. My question is, should I connect to my database using my ssh key so that I can register a user directly on my frontend? Or should I just post my username and password to the backend using my API? But for this approach, how to encode the password and save it to the user authentication table? Thanks for your help! Kind regards, Xi -
How to list a series of Objects Models in another model?
I'm creating a chatbot, with two Models. A Message model which will store all messages sent by all users to the bot, as raw data without filters. A second model representing a chat, which has to be private and specific to the user. Therefore, I need to store messages within this chat, but entries related to the chat user only. So, on the one hand I have a model with one object is equal to one message, on the other hand I want a second model storing only user's content messages. class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) room = models.CharField(max_length=1000) media = models.BooleanField(default=False) mediasrc = models.CharField(max_length=1000, default=None) class Chat(models.Model): userchat = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True) group = models.BooleanField(default=False) messages = models.ManyToManyField(Message, blank=True, related_name='userchat') last_modified = models.DateTimeField(auto_now=True) My issue is that this second model (the Chat's ones) is listing all existing messages. I need to specify a filter for the ManyToManyField. -
django json_script variables not updating in javascript for loop
In my django project I have a for loop that iterates through a list of dicts containing a list of prices and and a list of dates. The lists of prices and dates for each item will then be used for a javascript graph for each individual item. The problem is that all of the graphs are the same. When outputting prices and dates in the console each list of prices and dates are the same as the first element in the list of items. Why is this happening? console output - (sw0_ _ _ is the ID of each item) html {% for item in watchlist_items %} <canvas id="chart_{{item.item_id}}"></canvas> {{ item.prices|json_script:"prices" }} {{ item.dates|json_script:"dates" }} <script> var prices = JSON.parse(document.getElementById('dates').textContent); var dates = JSON.parse(document.getElementById('prices').textContent); var data = []; for (let i = 0; i < prices.length; i++) { data.push({x:prices[i], y:dates[i]}); } console.log(`chart_{{item.item_id}} - `, "prices:",prices, "dates:", dates) new Chart(`chart_{{item.item_id}}`, { ... data: { data:data } ... } </script> {% endfor %} -
Elastic Beanstalk 504 Gateway Timeout Error - Django
I recently completed the W3schools.com Django Tutorial. I followed it step by step. Everything works as expected locally. I also created and connected a PostgreSQL database on Amazon RDS to my app. Eventually I deployed the Django application to Elastic Beanstalk. Finally I visited the website and the homepage works, including 5 items added to the database during the tutorial which was migrated from the tutorial to the Amazon RDS. Unfortunately, neither the Django admin panel nor a simple subdirectory of the website are accessible. I get a 504 Gateway Time-out error. I don't know why. It is not clear from the logs what the issues might be. I am thinking it could possibly be a configuration file error or an incorrect value of settings.py on Django's side. Any help would be greatly appreciated. -
Not getting the expected result from Django reverse
hope anyone here will be able to help me out. I am trying to get the reverse url for a viewset but somehow it's not working. I will quickly go through what I have done from the moment everything was working fine to the moment the reverse stopped working. I had a viewset on an app called "card" the reverse was reverse('card:card-list') everything was perfect, then I decided to move the card viewset to a different app called 'company' I did check the new urls structure by using the django_extensions and running the following command on the terminal python manage.py show_urls which gave me the new routing company:card-list I have then changed my reverse to reverse('company:card-list'), but now the code is broken and the reverse is not working as expected. I have done those changes cause an end point as /api/company/card instead of /api/card/ . Any ideas on how to solve it? tks a lot -
Memory quota exceeded when running Django Celery On Heroku
I have a Django project for running periodic tasks using Celery that is deployed to Heroku from GitHub. The project is a web scraping project that scrapes through other websites and stores the result in backend. The website is deployed on heroku well and the other parts are working fine. The issue is that whenever I start the periodic tasks, I get the error Process running mem=760M(148.5%) Error R14 (Memory quota exceeded) in the logs. Also no results is saved in the database. The website is working fine in my localhost without any errors. Here is my Procfile configuration; web: gunicorn jobWebsite.wsgi --log-file - --log-level debug worker: celery -A jobWebsite worker -l info -B In the second line, I combined the worker and beat processes to use one dyno. Also, here is a part of the logs that I am getting; 2023-01-24T21:58:41.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-flat-79602 sample#active-connections=6 sample#load-avg-1m=0.42 sample#load-avg-5m=0.405 sample#load-avg-15m=0.395 sample#read-iops=0 sample#write-iops=0 sample#memory-total=16084924kB sample#memory-free=12314188kB sample#memory-cached=2049948kB sample#memory-redis=443248bytes sample#hit-rate=0.29167 sample#evicted-keys=0 2023-01-24T21:59:11.683479+00:00 heroku[worker.1]: Process running mem=760M(148.5%) 2023-01-24T21:59:11.685197+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) 2023-01-24T21:59:32.045205+00:00 heroku[worker.1]: Process running mem=760M(148.5%) 2023-01-24T21:59:32.046763+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) I have used the Heroku postgres database and also the Heroku Redis database in this project. Any assistance will … -
How to test that anything in a django-accessed database has changed?
I'm refactoring some code and adding an atomic.transaction block. We have some code that performs auto-updates en-masse, after the atomic block. (It can't be in the atomic block, because it traverses some many-related tables, which requires queries since the ORM doesn't store the distinct relations.) According to my reading of the code, it seems impossible that any changes could occur, but having a test to prove it would be nice in case someone makes a bad code edit in the future. So how would I go about writing a test that proves nothing in the database has changed between the start of the test and the end of the test? The database is postgres. We currently have it configured for 2 databases (the database proper and a "validation" database which I'd created after we discovered the loading code had side-effects in dry-run mode. I'm in the middle of a refactor that has fixed the side-effects issue and I just added the atomic transaction block. So I would like to write a test like this: def test_no_side_effects_in_dry_run_mode(self): orig_db_state = self.get_db_state() # How do I write this? call_command( "load_animals_and_samples", animal_and_sample_table_filename=("data.xlsx"), dry_run=True, ) post_db_state = self.get_db_state() # How do I write this? self.assertNoDatabaseChange(orig_db_state, … -
Django ImproperlyConfigured
I'm fairly new to programming and I was learning Python by following the textbook No Starch Python. There is a chapter on Django and I followed the steps of the textbook. However, when I run the program: from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text I will get this error message: Traceback (most recent call last): File "/Users/admin/learning_log2/learning_logs/models.py", line 4, in class Topic(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/models/base.py", line 127, in new app_config = apps.get_containing_app_config(module) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 92, in getattr self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can anyone tell me why it is the case and what can I do? Thank you very much. P.S. I know there is already a post on this but I tried what was written without any results. Also, I'm on macOS High Sierra version 10.13.6 if this information is relevant. I tried whatever I … -
How can I get the meta data in Json format from a GitLab URL without using a personal token key and without project ID in Python (Django framework)?
I tried many codes: url = "https://gitlab.com/meta_tool/repository" parsed_url = urlparse(url) path_parts = parsed_url.path.split("/") owner = path_parts[1] repo_name = path_parts[2] gitlab = Gitlab('https://gitlab.com') project = gitlab.projects.get(owner+"/"+repo_name) print(project.name) Or other codes but some did not work. -
Serializing Dict Field inside List : ValueError: Cannot assign "OrderedDict
I am expanding JSON data from my last question and trying to save it to the database. Period model contains startDate and endDate because the JSON object could have all 3, or maybe one of them so I want to make them options. I am following steps given in the documentation for Writable nested representation but I am unable to get the same results Commented out code are the attempts I made to get the data to save. When I am trying to save the data, I get ValueError: Cannot assign "OrderedDict([('instant', '2020-09-26')])": "Cashcashequivalentsrestrictedcashandrestrictedcashequivalents.period" must be a "Period" instance. Models: class Basetable(models.Model): basetable = models.AutoField(primary_key=True) CompanyId = models.IntegerField() class Cashcashequivalentsrestrictedcashandrestrictedcashequivalents(models.Model): cashtable = models.AutoField( primary_key=True) unitRef = models.CharField(max_length=100) value = models.CharField(max_length=100) decimals = models.CharField(max_length=100) basetable_id = models.ForeignKey(Basetable, on_delete=models.CASCADE) class Period(models.Model): period = models.AutoField(primary_key=True) instant = models.CharField(blank=False, max_length=100, null=True) startDate = models.CharField(blank=False, max_length=255, null=True) endDate = models.CharField(blank=False, max_length=255, null=True) cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = models.OneToOneField( Cashcashequivalentsrestrictedcashandrestrictedcashequivalents, on_delete=models.CASCADE) Serializer: class PeriodSerializer(serializers.ModelSerializer): # instant = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) # startDate = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) # endDate = serializers.DictField( # child=serializers.CharField(required=False, max_length=255)) instant = serializers.CharField(required=False, max_length=255) startDate = serializers.CharField(required=False, max_length=255) endDate = serializers.CharField(required=False, max_length=255) cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = serializers.IntegerField( required=False) # serializer = DictField(child = charField) somethhing like … -
using EmailMultiAlternatives in Django but after sending email, then rendering problem
After sending html email by using EmailMultiAlternatives in Django, renderig problem occurred. I wanted to show the user email an email is being sent to your email {{ email }} But instead of displaying proper email address, it was displayed as follows "<django.core.mail.message.EmailMultiAlternatives object at 0x7f7b11bdffa0>" How can I fix this problem? views.py #html email configuration html_content = render_to_string("basecamp/html_email-inquiry.html", {'name': name, 'contact': contact, 'email': email, 'message': message,}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( "Inquiry", text_content, '', [email] ) email.attach_alternative(html_content, "text/html") email.send() return render(request, 'basecamp/inquiry_details.html', {'name' : name, 'email': email, }) else: return render(request, 'basecamp/inquiry1.html', {}) inquiry_details.html <div class="py-md-6"> <h1 class="text-light pb-1">Thank you! {{ name }}</h1> <br> <p class="fs-lg text-light">An email is being sent to your email now</span></p> {{ name }} is displayed correct name but only email is not displayed proper email address. it is displayed like this; <django.core.mail.message.EmailMultiAlternatives object at 0x7f7b11bdffa0> -
NGINX Response Header missing Access-Control-Allow-Origin header when uWSGI - Djago application timesout
Our project is using the typical setup with a NGINX application gateway, uWSGI application container and a Django application. Django is configured using cors middleware and successfully handles requests from cross domains. However, one of our endpoints tars large files for download, which can take a significant amount of time. If it takes too long uWSGI times out and NGINX returns a response that lacks Access-Control-Allow-Origin header. We have increased uwsgi_connect_timeout and uwsgi_read_timeout values in the NGINX config to address most cases. Since, Django is handling cors and thus the Access-Control-Allow-Origin header, NGINX doesn't have those values to return to the client. Does anyone know what uWSGI or NGINX settings I need to get the correct headers? A simplified version of our nginx config: upstream results_uwsgi { server unix:///opt/app_manager/app_manager.sock; } server { listen 80; server_name \$hostname; return 301 https://\$host\$request_uri/; } server { listen 443 http2 ssl; listen [::]:443 http2 ssl; server_name \$hostname; charset utf-8; stub_status on; # adjust to taste client_max_body_size 75M; large_client_header_buffers 4 128k; location / { uwsgi_pass results_uwsgi; include uwsgi_params; } location /api { uwsgi_connect_timeout 10000s; uwsgi_read_timeout 10000s; sendfile on; uwsgi_pass results_uwsgi; include uwsgi_params; } } Our uWSGI configuration: [uwsgi] app_root = /opt/app_manager # emperor = /etc/uwsgi/vassals chdir … -
Is there an alternative to map() that doesn't return anything?
With the way that map() is designed it seems like it is intended to be used specifically when you are trying to return a list of modified things. I am wondering, is there an alternative to map() that is designed specifically for when you do not want to return whatever is being modified? I am currently working in a django project where I would like to set the initial value of a few fields if the instance already has data for these fields. Here is an example (note: I excluded some code not relevant to the discussion to keep it cleaner): class EquipmentStatusForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_field(["fk_user"]) def init_field(self, attr): if hasattr(self.instance, attr): if getattr(self.instance, attr) != "" and getattr(self.instance, attr) is not None: self.initial[attr] = getattr(self.instance, attr) Say I wanted to extend this to use a list of attrs rather than a single one, and then set the initial value of all of these. I don't need the results to be returned because I am not actively doing anything with these attrs after I modify them. Is there a built in alternative to map() designed for this? Or am I really just stuck using a for … -
How to print object's values with "annotate()" and "for loop" in ascending order?
I have Category and Product models below. *I use Django 3.2.16: # "models.py" from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) Then, when running test view to print id, name and product__count with annotate() and index as shown below: # "views.py" from .models import Category from django.http import HttpResponse from django.db.models import Count def test(request): qs = Category.objects.annotate(Count('product')) print(qs[0].id, qs[0].name, qs[0].product__count) print(qs[1].id, qs[1].name, qs[1].product__count) print(qs[2].id, qs[2].name, qs[2].product__count) print(qs[3].id, qs[3].name, qs[3].product__count) return HttpResponse("Test") These are printed in ascending order properly as shown below: 1 Fruits 14 2 Vegetables 10 3 Meat 4 4 Fish 3 But, when running test view to print id, name and product__count with annotate() and for loop as shown below: # "views.py" # ... def test(request): qs = Category.objects.annotate(Count('product')) for obj in qs: print(obj.id, obj.name, obj.product__count) return HttpResponse("Test") These are printed in descending order improperly as shown below: 4 Fish 3 2 Vegetables 10 3 Meat 4 1 Fruits 14 [25/Jan/202 In addition, when running test view to print id and name with all() and index as shown below: # "views.py" # ... def test(request): qs = Category.objects.all() print(qs[0].id, qs[0].name) print(qs[1].id, qs[1].name) print(qs[2].id, qs[2].name) print(qs[3].id, qs[3].name) return … -
How to use variables in django models.py, (DEFAULT properties of fields)
I would like that, when clicking on one of the companies below, a variable is stored (until the browser is closed) with the company's code. And, I need this variable to populate the 'CompanyCode' fields as default value. FOR EXAMPLE: class Employee(models.Model): class Meta: db_table = 'employee' CompanyCode= models.IntegerField( null=False, blank=None, default = 'VARIABLE', db_column='CompanyCode' ) After being stored in the database, I need to make a query to show all tuples where CompanyCode is equal to a certain value. Could someone tell me a python, django component that I could use to separate the data for each company? I thought of using JavaScript Local Storage at first. -
How to assign HTML Form fields to DJANGO Model Forms without using ModelForm
I am trying to make pretty looking HTML form where each fields are formatted with some validation and icons. Once these fields are submitted I want to save to Model instance using either using Model form or some other approach which allows to make this operation smooth. Here is my code snippet: model.py: class Client(Model): client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) date_of_birth = models.DateField(blank=True, null=True) email = models.EmailField(null=True) form.py: class ClientNewForm(forms.ModelForm): class Meta: model = Client fields = "__all__" view.py (I know this is wrong but need help to figure out what's the best way to do this): class ClientCreateView(CreateView): model=Client form_class = ClientNewForm template_name = 'Client/client_new.html' context_object_name = 'client' # refer the object as patient in template success_url = reverse_lazy('WebApp:clients') def form_valid(self, form): model = form.save(commit=False) #model.submitted_by = self.request.user model.save() messages.success(self.request, "The Client is created successfully.") return super(ClientCreateView, self).form_valid(form) Template: <div class='row'> <div class="col-md-8 col-sm-8 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>NEW REGISTRATION</h2> </div> <div class="x_content"> <form class="form-horizontal form-label-left input_mask" action="" method="post"> {% csrf_token %} <div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback"> <input type="text" class="form-control has-feedback-left" id="in-fn" placeholder="First Name" name="first_name"> <span class="fa fa-user form-control-feedback left" aria-hidden="true"></span> </div> <div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback"> <input type="text" class="form-control … -
Where is it better to start creating a simple social network(Django)?
I want to create my own simple social network (where you can post posts, videos, photos, etc.), but I don't know where to start. I'm already learning Python (Django), but I don't know this language (framework) professionally. Can you advise which videos, articles, forums, tutorials (and more) will help to create this simple project? -
django.urls.exceptions.NoReverseMatch: Reverse for 'index' with arguments '(5,)' not found. 1 pattern(s) tried: ['index/\\Z']
Django problem views.py def likes_up(request,post_id): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.like.filter(id=request.user.id).exists(): post.like.remove(request.user) else: post.like.add(request.user) return HttpResponseRedirect(reverse('index', args=[post_id]))` models.py class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.CharField(max_length=500,null=True,blank=True) timestamp = models.DateField(auto_now_add=True) like = models.ManyToManyField(User,blank=True,related_name="liked_user") def number_of_likes(self): return self.like.count()` index.html {% if user.is_authenticated %} <form action="{% url 'like-post' pst.id%}" method="POST"> {% csrf_token %} {% if post_is_liked %} <button type="submit" name="post_id" value="{{pst.id}}" class="btn btn-info">Unlike</button> {% else %} <button type="submit" name="post_id" value="{{pst.id}}" class="btn btn-info">Like</button> {% endif %} </form> {% endif %} <strong class="text-secondary">{{ number_of_likes }} Like{{ number_of_likes|pluralize }}</strong>` I try to make post like and unlike button and ı want to show page that how many users liked post? But I got this error: How can I solve this problem? Internal Server Error: /like/5 Traceback (most recent call last): File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\OSMAN MERT\Desktop\env\blogs\mysite\blog\views.py", line 102, in likes_up return HttpResponseRedirect(reverse('index', args=[post_id])) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'index' with arguments '(5,)' not found. 1 pattern(s) tried: ['index/\Z'] -
override get_queryset DetailView
I'm new in Django and i try to use Class Based Views for my project, but i have problem in this. I wanna login a user into a page with its primary key but i don't know how to override query_set. here is my code, any help will grateful. in the views.py : def UserPage(LoginRequiredMixin, DetailView): template_name = 'user_page.html' model = User login_url = '/login/' def get_queryset(self): pass in urls.py: path('user/<int:pk>/' , UserPage.as_view()), I write this : return User.objects.get(pk=pk) but i got this error : Type Error missing 1 required positional argument: 'pk'