Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
tutorial shows to use "python3 manage.py runserver", but gives "Python was not found..." error
I tried "python3 manage.py runserver", but it gave me this error. Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. details: My version is 3.11.0, I have anaconda and pycharm downloaded, but I used pycharm to try and do the manage.py thing, my interpreter is correct, and using python command in command prompt shows the details, meaning I do have python I'm a new coder, and I was watching a tutorial from a 3.7.2 user, and he told me to use "python3 manage.py runserver" but it gave me an error. On his screen, he gets a link to the django website, but I don't. -
how to troubleshoot django 'internal server error'
a similar question was asked 7 years ago, but the answer/comments were not that helpful and maybe not current. I'm developing a new website and relatively new to django. At times django provides a very detailed error response (very helpful) but other times it simply says 'internal server error' (less helpful). why is this and what is a good method for troubleshooting 'internal server error' errors? -
Django - model fields properties won't update
auth_id = models.CharField('something', max_length=14, unique=True, null=True, blank=True) name = models.CharField('something', max_length=64) email = models.EmailField('something', unique=True) class Meta: verbose_name = 'something' def __str__(self): return self.name I'm currently updating the properties of auth_id and email. None of the solutions I search worked. Whenever I run the command py manage.py migrate only the max_length is updated in the database. null & blank for auth_id and unique for email are not reflected on the database. I'm using postgres. -
How to get the first record of a 1-N relationship from the main table with Django ORM?
I have a Users table which is FK to a table called Post. How can I get only the last Post that the user registered? The intention is to return a list of users with the last registered post, but when obtaining the users, if the user has 3 posts, the user is repeated 3 times. I'm interested in only having the user once. Is there an alternative that is not unique? class User(models.Model): name = models.CharField(max_length=50) class Post(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', related_query_name='posts') created = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'created' ordering = ['-created']` I already tried with selected_related and prefetch_related, I keep getting multiple user registrations when they have multiple Posts. user = User.objects.select_related('posts').all().values_list('id', 'name', 'posts__title', 'posts__created') This does give me the answer I want, but when I change the created field to sort by date, I don't get the newest record, I always get the oldest. user = User.objects.select_related('posts').all().values_list('id', 'name', 'posts__title', 'posts__created').distinct('id') -
Render a Django view with data classified in a one to many relationship
I have a one to many relationshiop: class SessionGPS(models.Model): start_timestamp = models.IntegerField() end_timestamp= models.IntegerField() class GPSData(models.Model): longitude = models.DecimalField(max_digits=15, decimal_places=13) lat = models.DecimalField(max_digits=15, decimal_places=13) session_new = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps") Each SessionGPS entry has multiple GPSData entries. A session is composed of a set of GPS coordinates. This set is in the model GPSData. I need to query SessionGPS based in start and end timestamps: def date_search(request): data = request.body.decode("utf-8") start=int(datetime.datetime.strptime(request.POST['start'], '%Y-%m-%d').timestamp()) end=int(datetime.datetime.strptime(request.POST['end'], '%Y-%m-%d').timestamp()) res = GPSData.objects.filter(session_new_id__inicio_sesion__gte=start,session_new_id__fin_sesion__lte=end) res = serializers.serialize("json", res) return HttpResponse(res, content_type='application/json') In this way I get all GPSData between the timestamps but are not classified by session, they are merged. I need to get the query like this: session 1 ->> all GPSData of that session 1 session 2 ->> all GPSData of that session 2 So in the template I can render like this: For GPSData in session 1 do something For GPSData in session 2 do something etc. I tried to return multiple queries to the view but it didn't worked. Thanks for any help. -
How can I add a Logout POST function to my HTML template that is written in vue?
I made my basic logout function here in my user's views. class SignOutView(View): def get(self, request): logout(request) return HttpResponseRedirect(reverse("home")) I called it in my user’s URLs. path( 'signout/', view=views.SignOutView.as_view(), name='signout', ), If I had a normal HTML template, I would call it normally with {% URL:users:logout %} But, what I have is an HTML from vue: const menu = `<MenuItems> <MenuItem> <a href="auth/logout"> Sign Out </a> </MenuItem> </MenuItems> ` My current logout is a href that makes a GET, but I want to change it, I want to add a POST here. I am looking for doing something like: <script type="text/javascript"> // get the anchor with dom and make the post </script> I am currently logging in and getting the csrf token. -
How to work with users on the Ory Hydra network in the Django system?
In my project, I use Django (as a backend development tool for multiple applications on the same network) and Ory Hydra (as a ready-made network for user authorization with the ability to use all applications from this network). Hydra is a tool thanks to which it is possible to work effectively with users, but it is important to transfer data about users locally from the applications that it uses. Below are the connection settings for the Django with Hydra add-on # Add import os to the beginning of the file import os import environ env = environ.Env() ... # We need to change a couple of settings here TEMPLATES ... # This tells django to use `mysite/templates` dir # for searching templates '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', # Add this line to enable context processor # and have variables like `login_url` available # in templates 'django_ory_auth.context.processor', ], }, But as far as I understand, the server simultaneously creates all users from Hydra in the Django database in all networks at the same time, which significantly loads the database, although it may never use this particular application. How can I configure the system … -
Django admin class model issue
class TheList(admin.ModelAdmin): list_display = ['name', 'age'] actions = None I want to see a list in admin panel as readonly. If I use the below method it will show a list of objects which then need to be clicked on in order to display the name and age. readonly_fields = ['name', 'age'] I have tried using the below admin functions which didn’t fix the problem: has_delete_permission has_add_permission The list is still editable I tried using this with list_display: has_change_permission that made the class not viewable in admin panel I want it to be like list_display but readonly, is that even possible? -
Make another dataframe from pandas or make another table
mates, tried for 3 days to deal it with my own but unsuccesfully... I have these models: A patient: class Patient(models.Model): <...> hist_num = models.IntegerField(validators=[MinValueValidator(0)], primary_key=True) <...> def __str__(self): return f"{self.first_name} {self.last_name}" Group of labaratory Analysis: class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) # analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" An analysis (haemoglobin and etc.): class AnalysisType(models.Model): a_name = models.CharField(max_length=16) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) analysis_group = models.ManyToManyField(AnalysysGroup) And a patient analysis: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) I try to get a table with all analysis of my patient per day and sort by analysis types. My query seems like this analysis_qs = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date').distinct() df1 = pd.DataFrame(analysis_qs.values('analysis_type','analysis_date','analysis_data')) <...> return df1.to_html() And gives me: Result of {{df1 | save} I want to see sth like ideally + measurments | Data | Haemoglob| Red blood| Leuc | | -------- | -------- | -------- | -------- | | Data | Result | Result | Result | | Data | Result | Result | Result | -
Secure Django REST Api with react and keycloak
I'm new to the world of keycloak. I have a little trouble understanding some things. I understood well how to authenticate with React and get a JWT token. However I would like to protect a Django API with this JWT Token retrieved with React. And I don't see how to do it. The resources are scarce or from several versions. I am with Keycloak 20. Thx in advance. -
ImportError: cannot import name 'views' from project (C:\django_projects\project\project\__init__.py)
This is my first Django project. I tried to execute the code available at: https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ Just made few changes such as removed staff module and modified the file names. The tree structure of my project is shown below: c: manage.py project asgi.py settings.py urls.py wsgi.py __init__.py media static templates sudent_information_system admin.py │ Admin_Views.py │ apps.py │ base.html │ contact.html │ forms.py │ login.html │ models.py │ registration.html │ Student_Views.py │ tests.py │ views.py │ __init__.py │ ├───migrations │ __init__.py │ ├───templates │ home.html │ └───__pycache__ admin.cpython-37.pyc apps.cpython-37.pyc models.cpython-37.pyc __init__.cpython-37.pyc The code in urls.py is as follows: The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from . import views from . import HodViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', include('sudent_information_system.urls')), path('', views.home, name="home"), path('contact', views.contact, … -
AxiosError: Request failed with status code 403 - login and token
auth.js export async function loginUser(data) { const response = await axios.post( 'http://10.0.2.2:8000/api/rest-auth/login/', { username: data.username, password1: data.password, }, { headers: { "Content-Type": "application/json", } } ); console.log(response.data) LoginScreen.js import { useState } from 'react'; import LoadingOverlay from '../../components/ui-components/LoadingOverlay'; import AuthContent from '../../components/auth-components/AuthContent'; import { loginUser } from '../../util/auth'; function LoginScreen() { const [isAuthenticating, setIsAuthenticating] = useState(false); async function loginHandler(username, password1) { setIsAuthenticating(true); await loginUser(username, password1); setIsAuthenticating(false); } if (isAuthenticating) { return <LoadingOverlay message="Logging you in..."/> } return <AuthContent isLogin onAuthenticate={loginHandler}/>; } export default LoginScreen; setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } I've tried logging into both the REST API and Postman, and everything works fine - it returns the token to me once the right credentials are issued. But when I try to send the request via the login form from react native to django via axios, it gives me the error 403 forbidden by axios. On the contrary, the registration makes me carry it out both via REST API and via the registration form (React Native) and returns the token. -
Is it possible to calculate direction in Postgis & Django (GeoDjango)?
Is it possible to calculate direction to detect if users are moving in "similar" direction having a few of their last coordinates(Points) using PostGIS + Django (https://docs.djangoproject.com/en/4.1/ref/contrib/gis/)? I could't find information about this feature. -
Trying to get ForeignKey's names instead of pk in a QuerySet Django
Im trying to make a complex queryset and I want to include my ForeignKeys names instead of pk. I'm using ajax to get a live feed from user inputs and print the results on a DataTable but I want to print the names instead of the pk. Im getting a queryset and when I console.log it, sensor_name is not in there. My models are like this: class TreeSensor(models.Model): class Meta: verbose_name_plural = "Tree Sensors" field = models.ForeignKey(Field, on_delete=models.CASCADE) sensor_name = models.CharField(max_length=200, blank=True) class TreeSensorMeasurement(models.Model): class Meta: verbose_name_plural = "Tree Sensor Measurements" sensor = models.ForeignKey(TreeSensor, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) soil_moisture_depth_1 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_2 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_1_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_moisture_depth_2_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_temperature = models.DecimalField(max_digits=15, decimal_places=2) And my view looks like this: field_list = Field.objects.filter(user=request.user) tree_sensors = TreeSensor.objects.filter(field_id__in=field_list.values_list('id', flat=True)) Tree_Metrics = request.GET.getlist("Tree_Metrics[]") if Tree_Metrics is not None: for array in Tree_Metrics: From_T.append(array.split(',')[0]) To_T.append(array.split(',')[1]) try: statSensors = (TreeSensorMeasurement.objects .filter(sensor_id__in=tree_sensors.values_list('id', flat=True)) .filter(datetime__date__lte=To_T[0]).filter(datetime__date__gte=From_T[0]) .filter(soil_moisture_depth_1__lte=To_T[1]).filter(soil_moisture_depth_1__gte=From_T[1]) .filter(soil_moisture_depth_2__lte=To_T[2]).filter(soil_moisture_depth_2__gte=From_T[2]) .filter(soil_temperature__lte=To_T[3]).filter(soil_temperature__gte=From_T[3]) .order_by('sensor', 'datetime')) TreeData = serializers.serialize('json', statSensors) except: TreeData = [] The code above works correctly but I cant figure out the twist I need to do to get the TreeSensors name instead of pk in the frontend. An example … -
Registration form is not submitting
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django. This is the registration form <h1>Register</h1> <div> <form method="POST" action="{% url 'register' %}"></form> {% csrf_token %} {{ form.as_p}} <input type="submit" value="register" /> </div> Below is the views.py ` def register_page(request): form = CustomUserCreateForm() if request.method == 'POST': form = CustomUserCreateForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() login(request, user) return redirect('login') page = 'register' context={'page':page, 'form':form} return render(request, 'login_register.html', context) ` The forms.py ` class CustomUserCreateForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'name', 'password1', 'password2'] ` Its not throwing any error, rather just not submitting. I tried changing the input to button feature but it is still not working. Any Ideas? -
How deploy django application on your own company server?
I have a django application ready to go for production but my company gave me a suggestion which is having there own server and deployed there and honestly I have no clue how to acheive this. Any help with specific details would be highly appreciated -
I am getting IntegrityError NOT NULL constraint failed: login_new_user.sturesidance
In my template I have defined it like this, ` <!-- residance --> <div class="input-group mb-2 "> <span class="input-group-text w-25" for="residance">Residence</span> <input class="form-control text-bg-primary bg-opacity-10 text-dark text-opacity-50" type="textarea" name="stureisidance" cols="4" rows="5" placeholder="type current address" required> </div> ` In my models i have this filed . ` sturesidance=models.TextField() ` This is how I created my object, ` new_user.objects.create( stuname= stuname, stubirthday= stubirthday, stuphoto= stuphoto , stugemail= stugemail ,stugrade= stugrade , stuclass= stuclass,stuentrance= stuentrance , sturesidance= sturesidance ,stuguardian= stuguardian , stugtele= stugtele , stumother= stumother ,stumothertele= stumothertele ,stuotherskills= stuotherskills ,stucertificate= stucertificate ,stuletter= stuletter ,stumedical= stumedical ,stusports= stusports ,stupassword= stupassword ) ` Now I am getting error IntegrityError Exception Value: NOT NULL constraint failed: login_new_user.sturesidance -
<int:pk> or {pk} does not work in DRF router
I have an Comment which have an Article foreign key (so Article have an "array" of comments). I need to build an url to fetch theese comments using article's pk, but when I am trying to do smth like "articles/int:article_pk/comments/" or "articles/{article_pk}/comments/" drf router crates static route with path "articles/{article_pk}/comments/". How can I implement getting a comments using article pk? -
Cannot install mysqlclient for my Django project using pip on ZorinOS
Im new in Django. I am using python3.11.0 and pip 22.3.1 in django framework. I want to use mariaDB in my Django project. For that I have to install mysqlclient. I tried a lot of things, but it doesn't work. This error is coming when I try: pip install mysqlclient Output: (venv) kiril@noknow-PC:~/Work/django_project/mysite$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [44 lines of output] mysql_config --version ['8.0.31'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-311 creating build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-311/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-311/MySQLdb creating build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-311/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py … -
Why Django throws an error creating test database?
When I try to run tests on my Django project, it throws the following error creating the test database: django.db.utils.ProgrammingError: relation "users_websiteuser" does not exist If I run the project, everything works fine. I've already tried running all the migrations (makemigrations and then migrate) and deleting the test database, but it still doesn't work. How can I fix this? -
Django admin can't create records for model with self-referential foreign key
This is my model: class Customer(models.Model): name = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) referee = models.ForeignKey('self', on_delete=models.RESTRICT, blank=True, null=True) def __str__(self): return self.name When I try to create a customer via admin site I got this error: TypeError at /admin/customer/customer/add/ Field 'id' expected a number but got <Customer: my_customer_name>. How can I fix this? Thank you. -
Django, PgBouncer and DigitalOcean, How to work DB Connection Pools
I'm using digitalocean managed database with django. How to create connection pool? -
Is there a way to add custom data into ListAPIView in django rest framework
So I've built an API for movies dataset which contain following structure: Models.py class Directors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'directors' ordering = ['-id'] class Movies(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.IntegerField(blank=True, null=True) rank = models.FloatField(blank=True, null=True) class Meta: db_table = 'movies' ordering = ['-id'] class Actors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) gender = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = 'actors' ordering = ['-id'] class DirectorsGenres(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres') genre = models.CharField(max_length=100, blank=True, null=True) prob = models.FloatField(blank=True, null=True) class Meta: db_table = 'directors_genres' ordering = ['-director'] class MoviesDirectors(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors') class Meta: db_table = 'movies_directors' ordering = ['-director'] class MoviesGenres(models.Model): movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres') genre = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'movies_genres' ordering = ['-movie'] class Roles(models.Model): actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles') role = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'roles' ordering = ['-actor'] urls.py from django.urls import path, include from . import views from api.views import getMovies, getGenres, getActors urlpatterns = [ path('', views.getRoutes), path('movies/', getMovies.as_view(), name='movies'), path('movies/genres/', getGenres.as_view(), name='genres'), path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'), ] serializer.py from … -
Editing in Django admin reversed depended by foreign key
How in class QuestionsAdmin(admin.ModelAdmin) implement that in Django admin in Question can see all, add, edit and delete all Answers? class Answer(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) value = models.TextField() correct = models.BooleanField() question = models.ForeignKey("Questions", models.DO_NOTHING) class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) content = models.TextField() -
First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model?
I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py class User(AbstractUser): is_type1 = models.BooleanField(default=False) ... class Type1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite') views.py def FavoriteView(request, pk): current_user = request.user Type1.user = current_user.id buser = Type1.user Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite fuser = Type1.favorite if Type1.favorite.filter(id=request.user.id).exists(): Type1.favorite.remove(request.user) else: Type1.favorite.add(request.user) return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite})) class UserView(DetailView): model = User ... template_name = 'users/profile-details.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite favorite = False if favorite_connected.favorite.filter(id=self.request.user.id).exists(): liked = True data['user_is_favorite'] = favorite return data profile-details.html ... {% if user.is_authenticated %} <form action="{% url 'favorite' object.id %}" method="POST"> {% csrf_token %} {% if user_is_favorite %} <button type="submit" …