Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RecursionError:maximum recursion depth exceeded while calling a Python object in my Django web applications
I've been struggling with this issue for a while now. Each time I run python management.py runserver and navigate to the page with my web applications actual data, it suddenly breaks and gives the above error prompt models.py from django.db import models from django.urls import reverse from equipments .models import Equipment class TruckIssue(models.Model): description = models.CharField(max_length=100) part_number = models.CharField(max_length=100, blank=True) uni = (('MTR', 'Meter'), ('NO', 'Number')) unit = models.CharField(choices=uni, max_length=6, null=True, default="no") quantity = models.IntegerField(null=True) equipments = models.ForeignKey(Equipment, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) mechanic = models.CharField(max_length=10, default="no") job_card = models.CharField(max_length=10, default="no") remark = models.TextField(blank=True, default="no") def __str__(self): return f'{self.equipments} Issues' views.py from django.views.generic import ListView from .models import TruckIssue class TruckIssueListView(ListView): model = TruckIssue template_name = "truck/issue_list.html" context_object_name = 'truckissues' ordering = ['-date_posted'] paginate_by = 20 urls.py from django.urls import path from . import views from .views import TruckIssueListView urlpatterns = [ path('', TruckIssueListView.as_view(), name='issues'), ] I've tried recreating the web app on different occasions but all keep running into the same error. I'm using django 3.2.5 -
ORDER BY table structure instead of numerical
My current MsSQL query looks like this : all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)'\ ' AND genLedger.TxDate > ?'\ ' ORDER BY iAccountType' I would need the ORDER BY iAccountType to show the order that the data is placed in the table , not numerical. Currently the output looks like this (see Account column): But I need it to look like this: -
How can i iterate two django models
I have multiple models in my django project. i want to iterate them all so i can access it in django model field. how can i do this? I have tried zipping them like in my views.py like: inventory = Inventory.objects.all() header = Header.objects.all() setup = Setup.objects.all() revision = Revisions.objects.all() spec = SpecificationDetails.objects.all() review = Reviewers.objects.all() zippedItems = zip(inventory, header, setup, revision, spec, review) context = { 'zippedItems': zippedItems } return render(request, 'crud/dashboard.html', context) and in my template file i tried {%for items in zippedItems %} <td>{{items}}</td> but it's not working and i think it did not zipped the objects. any tips on how can i achieve this? -
Sorting by date in MsSQL Queries || Django || Python
I am trying to sort the data fetched by the below MsSQL statements by date (1 year from today) My current statement looks like this: one_yrs_ago = datetime.now() - relativedelta(years=1) all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)'\ ' AND WHERE genLedger.TxDate > ' + one_yrs_ago However, this returns multiple errors no matter how I change the statement. Does anyone know how to sort by date in mssql queries like the above ? -
Add Other Fields of AUTH_USER model with SimpleJWT in Django Rest Framework
I'm using Django Rest Framework with Simple JWT. All i want to do is fetch or add extra field (eg. first_name, last_name) with Refresh & Access Token. I want to use AUTH_USER model and not the Custom User model. I tried custom TokenObtainPairViewbut still not working and i'm only getting is Refresh & Access Token. When checked on jwt.io it shows only id. Can anyone please help. Is there anything left on my side to do. Please help { "token_type": "access", "exp": 1631511174,"jti":"13b76d1d5e2a4d978cc19fabbdc0fc9e", "user_id": 3 } Views.py from rest_framework_simplejwt.views import TokenObtainPairView class TokenObtainPairView(TokenObtainPairView): # Replace the serializer with your custom serializer_class = MyTokenObtainPairSerializer # token_obtain_pair = TokenObtainPairView.as_view() serializers.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data.pop('refresh', None) # remove refresh from the payload data['access'] = str(refresh.access_token) # Add extra responses here data['username'] = self.user.username data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name return data -
how to run django selenium automated scripts in cpanel
I have developed and deployed the Django app for selenium automation, which automatically opens the selenium chrome browser and extracts the data from a website. It works perfectly in the localhost server but when I deployed it into the Cpanel server it's giving "500 Internal Server Error" def startfunc(request): if request.method == "GET" : chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN") chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), options=chrome_options) driver.get("https://www.indiatoday.in/india?page&view_type=list") or, I am trying this way as well def startfunc(request): if request.method == "GET" : driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("https://www.indiatoday.in/india?page&view_type=list") -
Not Able to change css using JS
I am working on DJango which also Involves JavaScript I need to change background color of an element after a certain action but am unable to do so. Below code is the only Javascript file used in the project. function create_email(email){ const element = document.createElement('div'); element.id = "email"; element.innerHTML= `<b>${email.sender}</b>: ${email.subject}<p id='right' ><button id ="view" onclick="view_mail(${email.id})"class="btn btn-primary">View</button>${email.timestamp}<button id="archive" onclick="archive(${email.id})" class="btn btn-secondary">Archive</button><p>`; element.addEventListener('click', function() { console.log(`This message is sent by ${email.sender}`) }); document.querySelector('#emails-view').append(element); } Above I created an Element div using Javascript and assign id email , Later I will be changing this elements css property:- function read(id){ fetch(`/emails/${id}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) document.getElementById("email").style.backgroundColor="red"; } In this function I tried changing the background color of the element but is not changing anything. Note that this function is running as I have tried changing other elements property in this function only and they worked. The element email div is within the div with id emails-view . And I am able to change the background of emails-view div but not email div that is within this div block. -
DJANGO - Upload image and then display on template
I'm trying to display the 'plant_image' within the for loop on dashboard.html. I can get all other fields to display but the image will not. I understand there is some difference between development and production, but I just want to have it work in development for the moment. If someone could explain how to make this work, I would be very grateful. model.py class Plant(models.Model): plant_name = models.CharField(max_length=30) plant_image = models.ImageField(upload_to ='upload/', height_field=None, width_field=None, max_length=None) dashboard.html - template {% for plant in plants %} <p>/{{plant.plant_name}}</p> <img src="{{plant.plant_image}}" alt="Plant Image" width="250" height="250"> {% endfor %} views.py def dashboard(request): plants = Plant.objects.all() return render(request, 'dashboard.html', {'plants': plants}) urls.py urlpatterns = [ path('', views.dashboard, name='dashboard'), ] -
403 (Forbidden) when trying to access DRF API from React js
I started to use django recently and I also tried to use React js and I wanted to do something simple like a nav var in React. For that I would need to fetch the user information which I have on a DRF API as follows in the views file: ALLOWED_HOSTS = settings.ALLOWED_HOSTS @api_view(['GET']) @authentication_classes((SessionAuthentication, TokenAuthentication)) @permission_classes((IsAuthenticated,)) def user_details_view(request, *args, **kwargs): current_user = request.user id = current_user.id status = 200 data = dict() try: obj = CustomUser.objects.get(id=id) data = UserSerializer(obj) # data = obj.serialize() except: data['message'] = "Not Found" status = 404 return Response(data.data, status=status) The urls are set up and if I access it in the django server it works fine but when I try on react: function loadUserInfo(callback){ const xhr = new XMLHttpRequest(); const method = 'GET'; const url = "http://127.0.0.1:8000/userdetails/"; const responseType = "json"; xhr.responseType = responseType; // Let the xhr request know that its getting a json xhr.open(method, url); //This opens the request with the method and url entered xhr.onload = function(){ console.log("This is the response: ",xhr.response) callback(xhr.response, xhr.status) } xhr.onerror = function(){ callback({"message":"The request was an error"}, 400) } xhr.send();//Trigger that request } I call the function in App() but I get: GET http://127.0.0.1:8000/userdetails/ 403 … -
Url not being resolved in, 404 error django
I am not able to create an detail and update view using the <pk> and <pk>/update/, this is my url paths. urlpatterns = [ path('',views.IndexView.as_view(), name='index'), path('form/',views.CompanyView.as_view(),name='company'), path('<pk>/',views.CompanyDetailView.as_view()), path('<pk>/update/',views.CompanyUpdateView.as_view()) ] my views looks like this, class CompanyUpdateView(generic.UpdateView): model = Company fields = '__all__' success_url = '/company' class CompanyDetailView(generic.DetailView): model = Company fields = '__all__' Also I use a FormView to add the data to database, class CompanyView(generic.FormView): form_class = CompanyForm template_name = 'company/company.html' success_url = '/company' def form_valid(self, form): form.save() return super().form_valid(form) When I got to a url company/1/ or company/1/update I get a 404 error. What would be the reason for it and how to solve this -
'-' in a model field on the django admin page instead of the form data
The Port Name column is currently empty with just a '-' at the moment. I was able to get the form input in this column earlier but now I just get the '-'. Here is a screenshot of what I get in the admin page. -
How do I get bearer token from DRF using React?
I have a backend built using DRF, and frontend using React and axios. Once someone logs in, the server issues a csrf token and session id. Is there anyway I can extract the server-generated Bearer token? -
django form.is_valid returns false when while using XMLHttpRequest
since bootstrap 5 no longer ships with jquery and recommends using the vanilla javascript XMLHttpRequest() to make dynamic requests that is what I am trying to do in django. All the other examples of doing this use the traditional .$ajax. I have a basic javascript function: function sendPhoneVerification(_phone) { var http = new XMLHttpRequest(); const params = { phone: _phone } http.open('POST', '/approvephone/', true) http.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); http.setRequestHeader('Content-type', 'application/json') http.setRequestHeader('phone', _phone) http.send(JSON.stringify(params)) http.onload = function() { alert(http.responseText) } } The CSRF middlware token is working fine, but the in the view, the form.is_valid() returns false and the error is that required field "phone" is missing. I can't tell how I am supposed to provide that value. The form being tested against is a simple form with one field class AddPhoneForm(forms.Form): phone = PhoneNumberField() relevant part of the view @csrf_protect @login_required def approvephone(request): if request.method == 'POST': form = AddPhoneForm(request.POST) if form.is_valid() #returns false and error is missing field "phone" Any idea how I can correctly provide the phone fields in the POST response to make django happy? -
How to serialize my model to get desired output
I want to serialize my model which having multiple object. I want to nest them. this is my model class model8(): country = foreign key a_image = "ImageField" b_image = "ImageFiled" a_url = char filed b_url = char filed and my desired output is { “ a_images”:[ { “image”: “”, “url”: “” }, { “image”: “”, “url”: “” } ], “b_images”:[ { “image”: “”, “url”: “” }, { “image”: “”, “url”: “” } ] } can any one help solve this huddle -
saving value of one model field count to another field of the same model during save
I am working on a pool app and want to add the total_likes attribute to the model which will allow me to count the number of users who liked the question just like Youtube community question allows. I just tried to override the save(*args, **kwargs) but got many error. what should I do now from django.db import models from django.contrib.auth.models import User class Question(models.Model): enter code here text = models.TextField() voters = models.ManyToManyField(to=User, blank=True, related_name='voters') impression = models.CharField(max_length=30, choices=impression_choices, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(to=User, related_name='likes', blank=True) total_likes = models.IntegerField(default=0) def __str__(self): return self.text def save(self, *args, **kwargs): self.total_likes = self.likes_set.count() super().save(*args, **kwargs) The Model below works totally fine. In the model above I tried to override the save() method but don't know how to? class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=20) votes = models.IntegerField(blank=True, default=0) def __str__(self): return self.text -
Django - Settings.py, urls.py and views.py resulting in 404 error
Recently I came across a 404 error when running my Django Project. I can't figure it out for some reason and I need help. I'm new to django and coding in general. Here is the error Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin index.html [name='index'] experience.html [name='experience'] projects.html [name='projects'] research.html [name='research'] education.html [name='education'] 404.html [name='comeback'] design.html [name='design'] The empty path didn’t match any of these. Here is the program code. Here is views.py from django.shortcuts import render def index(request): return render(request, 'index.html', {}), def experience(request): return render(request, 'experience.html', {}), def projects(request): return render(request, 'projects.html', {}), def research(request): return render(request, 'research.html', {}), def education(request): return render(request, 'education.html', {}), def comeback(request): return render(request, '404.html', {}), def design(request): return render(request, 'design.html', {}), Here is urls.py (app) from django.urls import path from . import views urlpatterns = [ path('index.html', views.index, name="index"), path('experience.html', views.experience, name="experience"), path('projects.html', views.projects, name="projects"), path('research.html', views.research, name="research"), path('education.html', views.education, name="education"), path('404.html', views.comeback, name="comeback"), path('design.html', views.design, name="design"), ] Here is urls.py (where settings is) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] Here are the settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent … -
Trobles to load a partial for a dependent drop-down list in a Django template
I'm trying to implement a dependent drop down list between countries and cities, but the document responsible to load the cities doesn't load. I'm trying to solve this problem since 3 days and I don't get a clue. The database has no problem because I tested it with non-ajax requests. And it is not a database problem, because the entire partial doesn't load. The most probable cause of the problem is that I based some code on online tutorial which probably use old versions either of JQuery or Django. But, here's the code Models.py from django.db import models class Country(models.Model): class Meta: db_table = 'countries' name = models.CharField(max_length=300) def __str__(self): return self.name class City(models.Model): class Meta: db_table = 'cities' name = models.CharField(max_length=300) state_id = models.BigIntegerField(null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): class Meta: db_table = 'people' name = models.CharField(max_length=300) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name Forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city') """ right now we are overriding the default init method, and setting the queryset of the … -
Mono crash after python file was edited and saved
I'm coding to call C#.Net dll file from Django Python Project. I think there is no error or warning was occurred in source. But I edited python file and saved while Django was running. And following error was occurred. ================================================================= Native Crash Reporting ================================================================= Got a SIGSEGV while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application. ================================================================= ================================================================= Native stacktrace: ================================================================= 0xffff9bca02fc - /lib/libmonosgen-2.0.so.1 : 0xffff9bca0624 - /lib/libmonosgen-2.0.so.1 : 0xffff9bc5b1e0 - /lib/libmonosgen-2.0.so.1 : 0xffff9bbd914c - /lib/libmonosgen-2.0.so.1 : 0xffffa5eb75b8 - linux-vdso.so.1 : __kernel_rt_sigreturn 0xffff9bbe1d44 - /lib/libmonosgen-2.0.so.1 : 0xffff9bd9edd0 - /lib/libmonosgen-2.0.so.1 : 0xffff9bda2280 - /lib/libmonosgen-2.0.so.1 : mono_runtime_invoke 0xffffa065fff8 - /home/phyo/lib/python3.8/site-packages/cffi.libs/libffi-3d8725bd.so.6.0.1 : ffi_call_SYSV 0xffffa066096c - /home/phyo/lib/python3.8/site-packages/cffi.libs/libffi-3d8725bd.so.6.0.1 : ffi_call 0xffffa41d2904 - /home/phyo/lib/python3.8/site-packages/_cffi_backend.cpython-38-aarch64-linux-gnu.so : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x501e20 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x593dd0 - /home/phyo/bin/python : _PyObject_FastCallDict 0x594094 - /home/phyo/bin/python : _PyObject_Call_Prepend 0x67a830 - /home/phyo/bin/python : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x501e20 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x593dd0 - /home/phyo/bin/python : _PyObject_FastCallDict 0x594094 - /home/phyo/bin/python : _PyObject_Call_Prepend 0x67a830 - /home/phyo/bin/python : 0x5939dc - /home/phyo/bin/python : _PyObject_MakeTpCall 0x5019c8 - /home/phyo/bin/python : _PyEval_EvalFrameDefault 0x5932c0 - /home/phyo/bin/python : _PyFunction_Vectorcall 0x59268c - /home/phyo/bin/python … -
Django Form not updating data in the model
this is my first Django project and I am stuck. If not a solution, but just a hint on what I am doing wrong will be truly appreciated. I have a model with one attribute set as Null by default and I want to use a Form to update that attribute with the ID taken from another model. These are the 2 models: models.py class Squad(models.Model): squad_name = models.CharField(max_length=20) def __str__(self): return self.squad_name class AvailablePlayer(models.Model): player_name = models.CharField(max_length=25) squad = models.ForeignKey(Squad, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.player_name This is the form: forms.py class AddSquadToPlayerForm(forms.Form): # squad the player will be added to squad_to_player = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): super(AddSquadToPlayerForm, self).__init__() self.fields['squad_to_player'].queryset = AvailablePlayer.objects.all() This is the view file, where I think something is missing/wrong: views.py def add_player_to_squad(request, squad_id): # player = AvailablePlayer.objects.get(id=squad_id) squad = Squad.objects.get(id=squad_id) if request.method == "POST": form = AddPlayerToSquadForm(request.POST) if form.is_valid(): form.squad = form.cleaned_data['id'] form.save() return redirect('fanta_soccer_app:squad', squad_id=squad_id) else: form = AddPlayerToSquadForm(queryset=AvailablePlayer.objects.all()) context = {"squad": squad, "form": form} return render(request, 'fanta_soccer_app/add_player.html', context) And finally, this is html file add_player.html <body> <p>Add a new player to the Squad:</p> <p><a href="{% url 'fanta_soccer_app:squad' squad.id %}">{{ squad }}</a></p> <form action="{% url 'fanta_soccer_app:add_player' squad.id %}" method="POST"> {% csrf_token %} … -
How do I access instance of a many-to-many field in django __str__ method
I am having two models; class Cart(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="book") quantity = models.PositiveIntegerField(default=1, null=True, blank=True) def __str__(self): return f"{self.quantity} of {self.book.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart) def __str__(self): return f"{self.cart.quantity}" I get 'ManyRelatedManager' object has no attribute 'quantity'. This usually works for a foreignkey field; but it seems not to for a many-to-many field. Note: I am trying to access quantity that belongs to the cart model from the Order model using manytomany field. Is there any way of doing something like this? -
2.0.7 Django Operational Error No Such Table
I am just learning Django and I am attempting to make my own app called products. I have run python manage.py startapp products in PowerShell to create the app. The purpose was just a very simple app to store data on products. I will also post my settings.py, models.py, and admin.py for reference models.py # Create your models here. class Product(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() summary = models.TextField(default = 'This is the default response') settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # own 'products', ] admin.py from django.contrib import admin # Register your models here. from .models import Product admin.site.register(Product) I did then run both python manage.py makemigrations and python manage.py migrate both of these worked and detected the new migration Product. This also showed up on my admin page as shown here Django Admin It worked as expected all the TextFields were present, but when I clicked save I got this operational error back Error I am a bit lost as to what to do from here any help would be much appreciated. -
Django can't import module due to a circular import
Following a tutorial and am have the module views.py file #attempt2/src/products/views.py from django.shortcuts import render from .forms import ProductForm, RawProductForm from .models import Product def product_create_view(request): #this creates an instance of that form my_form = RawProductForm() context = { "form": my_form } return render(request, "product/product_create.html", context) But I get the following error File "C:\Users\dancc\dev2\attempt2\src\products\views.py", line 2, in <module> from .forms import ProductForm, RawProductForm File "C:\Users\dancc\dev2\attempt2\src\products\forms.py", line 4, in <module> from products.views import product_create_view ImportError: cannot import name 'product_create_view' from partially initialized module 'products.views' (most likely due to a circular import) (C:\Users\dancc\dev2\attempt2\src\products\views.py) I've tried searching to see where it might be importing a different product_create_view but there is not another one, none of the files or folders' names repeat this is forms.py #attempt2/src/products/forms.py from django import forms from products.views import product_create_view from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price' ] #This is what product_create_view is using class RawProductForm(forms.Form): title = forms.CharField() description = forms.CharField() price = forms.DecimalField() This is models.py file #attempt2/src/products/models.py from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) #max_length required description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) summary = models.TextField() This is views.py … -
Test with customized auth_user model
I have a customized auth_user model in my application name "test-app". Here is how I create migration file: python3 manage.py makemigration test-app It will generate auth_user fine in 0001_initial Now when I try to run python3 manage.py migrate I will get: django.db.utils.ProgrammingError: relation "auth_user" does not exist I assume it has something to do with me customizing auth_user model. So I run migration with python3 manage.py migrate test-app Everything works. Now the issue is when I run the tests with python3 manage.py test It throws the exact same error: relation "auth_user" does not exist, hence the test db's table cannot be populated correctly. I can't seem to find an option to tell the test db to create with specific app tag and it looks like it' just running python3 manage.py migrate. Any help is appreciated :) -
How to properly redirect to new template using uuid as url slug in view
I have the following source template which renders the uuid of model Pollers as a hidden <a> tag to redirect the user to this item rendered in a fresh new template upon user click. <div class="poller-wrapper"> <a class="hidden_poller_id" href="/poller/{{ poller.poller_id }}"> <div class="poller-text">{{ poller.poller_text }}</div> [...] The url mapping looks like follows: urlpatterns = [ # Main overview of recent pollers path('pollboard/', pollboard, name='pollboard'), # Redirect url to single Poller path('poller/<uuid:poller_id>', single_poller, name='single_poller'), ] View def single_poller(request): return render(request, 'pollboard/single_poller.html') Right now I get the following error and I'm not sure why it doesn't redirect properly: TypeError at /poller/d251ce80-1d0d-41c4-a096-c12bdd2399f8 single_poller() got an unexpected keyword argument 'poller_id' -
Django-Why doesn't the likes system work?
Why is the likes system not working? Аfter clicking on the "like" button I get an error. class ImageDetail(DetailView): model=Image template_name='images/image/detail.html' context_object_name='image' def get_queryset(self): return Image.objects.filter(id=self.kwargs.get('id'),slug=self.kwargs['slug']) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) likes_connected=get_object_or_404(Image, id=self.kwargs['id'],slug=self.kwargs['slug']) liked=False if likes_connected.users_like.filter(id=self.request.user.id).exists(): liked=True data['number_of_likes']=likes_connected.number_of_likes() data['post_is_liked']=liked return data def ImagePostLike(request,id,slug): image=get_object_or_404(Image, id=request.POST.get('image_id'), slug=request.POST.get('image_slug')) if image.users_like.filter(id=request.user.id).exists(): image.users_like.remove(request.user) else: image.users_like.add(request.user) return HttpResponseRedirect(reverse('image_detail', args=[self.id, self.slug])) Why is the likes system not working? Аfter clicking on the "like" button I get an error. urls.py from django.urls import path,include from . import views app_name = 'images' urlpatterns = [ path('create/', views.image_create, name='create'), path('detail/<int:id>/<slug:slug>/', views.ImageDetail.as_view(), name='image_detail'), path('image_like/<int:id>/<slug:slug>/', views.ImagePostLike, name='image_like'), ] Why is the likes system not working? Аfter clicking on the "like" button I get an error. detail.html {% extends 'base.html' %} {% load thumbnail %} {% block title %}{{image.title}}{% endblock title %} {% block content %} <h1>{{ image.title }}</h1> <img src="{{ image.url }}" class="image-detail"> {% if user.is_authenticated %} <form action="{% url 'images:image_like' image.id image.slug%}"> {% csrf_token %} {% if post_is_liked %} <button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Unlike</button> {% else %} <button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Like</button> {% endif %} </form> {% else %} <a class="btn btn-outline-info" href="{% url 'login' %}?next={{request.path}}">>Log in to like this article!</a><br> {% endif %} <strong class="text-secondary">{{ number_of_likes …