Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Do I Loop Through Two Different ManyToMany Quersets in Python Django?
I am trying to do something seemingly simple and it won't cooperate. I am trying to use the django template language to loop through a model. Easy enough. The challenge here is that the model contains two manytomany fields that I am trying to compare. In my model... owner_confirm = models.ManyToManyField(User,related_name='meeting_minutes_action_item_owner_confirm') owner = models.ManyToManyField(User) Simple enough... I have a model that populates these two fields...and that's all working. The problem is when I loop through the template...it's not recognizing them when I try to compare them doing something like... {% if action_item.owner.all == action_item.owner_confirm.all %} What am I doing incorrectly? I have been at this for 2 days and am beginning to lose my mind. The condition above passes as false even if it's true...when I loop through all other types of fields it works fine...manytomany is not. -
Issues with deleting cookie in Django
I am having an issue deleting a HubSpot cookie in Django. I have a landing page with a form, and we were at a Trade Show capturing leads and since all leads used my computer and the hubspotutk cookie tracking user id was added, all new leads coming in were 'reconversions' instead of new contacts. I am attempting to simply delete the COOKIE on page load if it is there so the hubspotutk cookie gets reset on every refresh of the page, but it appears the cookie is never actually removed although it is there. Unfortunately with the code below I get an infinite redirect, only assuming that the hubspotutk cookie is not deleted as expected. Can anyone show me what I am doing wrong? def request_demo_landing(request): if request.COOKIES.get('hubspotutk'): response = HttpResponseRedirect('site.com/request-demo-landing/') response.delete_cookie('hubspotutk') return response ... -
Django score ranking
I am completely new in development. I write a small tool in Django where I can add users and games and then see them in a table. Now I want to add the rank, but I have no idea how to do it. I hope I get some tips here how I can solve it. Here is a screenshot how my table currently looks like Ranking -
How to send a link to an image in a response
I want to send a link to a photo in the response, which is on the hosting, I'm running a django application on the hosting via python manage.py runserver 0.0.0.0:8000 . How do I make it so that in the response to the request there is a link to the image that is on the hosting. Example: I get this response when accessing the API { "title": "add", "description": "some text", "image": "http://127.0.0.1:8000/media/photo_2022-09-12_20-57-08.jpg", "created_at": "2022-09-12T22:24:42.449098+03:00" } I want to get this answer: { "title": "add", "description": "some text", "image": "domain.api/media/photo_2022-09-12_20-57-08.jpg", "created_at": "2022-09-12T22:24:42.449098+03:00" } -
Django Page not found (404) - The current path, Didn't match any of these
I am trying to add a clinic from a users profile, However, i am getting a 404 page not found and i noticed that a single quote is getting appended to the URL: http://127.0.0.1:8000/profile/'/clinic/add_clinic/ Any help would be appreciated. Below are my Project URLS: urlpatterns = [ # django admin path('admin/', admin.site.urls), # User management path('accounts/', include('allauth.urls')), # local apps path('', include('pages.urls')), # new path('clients/', include('clients.urls')), # new path('behaviors/', include('behaviors.urls')), path('clientsessions/', include('clientsessions.urls')), path('profile/', include('users.urls')), path('clinic/', include('clinic.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here are URLs from the users app urlpatterns = [ path('', views.profile, name='profile'), ] Here is the profile view @login_required def profile(request): if request.method == 'POST': user_form = UpdateUserForm(request.POST, instance=request.user) profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Your profile is updated successfully') return redirect(to='users-profile') else: user_form = UpdateUserForm(instance=request.user) profile_form = UpdateProfileForm(instance=request.user.profile) return render(request, 'users/profile.html', {'user_form': user_form, 'profile_form': profile_form}) Here are the URLs rom the clinic app urlpatterns = [ path('clinic/', views.clinic, name='clinic'), path('add_clinic/', views.add_clinic, name='add_clinic'), ] And here is the add_clinic view @login_required @allower_users(allowed_roles=['admin']) def add_clinic(request): if request.method == 'POST': name = request.POST.get('name') if name: name = Clinic.objects.create(name=name, created_by=request.user) clinic.members.add(request.user) clinic.save() userprofile = request.user.profile userprofile.active_clinic_id = clinic.id userprofile.save() return redirect(to='users-profile') return render(request, 'clinic/add_clinic.html') -
How to integrate Webssh with Django?
I am running a Django Nginx Gunicorn server and also running a web SSH service with a systemd process. Basically, Nginx runs the main domain example.com and then a systemd process listens on port 4433 at example.com:4433. The reason for this is so users can remote login in to different computers using the website instead of having to use a local shell. The rest of the website is behind a login because Django controls the views. However, the part of the website behind the port is being served by systemd and webssh. Is there a way I can integrate Django with Webssh in order to lock the domain example.com:4433 behind a login? -
Django: How can I override login error message?
I have a custom user model class from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager CustomUser(AbstractBaseUser, PermissionsMixin) ... And related view class CustomUserViewSet(viewsets.ModelViewSet): pagination_class = BasePagination queryset = CustomUser.objects.all() ... def create(self, request, *args, **kwargs): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data send_invitation_email( user=user, email=json["email"], password=request.data["password"], phone=json["phone_number"] ) create_chats(user) return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In case of email, username duplicate I have the following error message: {"user_name":["custom user с таким user name уже существует."]} How can I override error this message with my custom message: {"user_name":["Пользоватль с таким именем уже существует."]} -
I can't just delete the db django.db.migrations.exceptions.InconsistentMigrationHistory
I know that there are similar questions on the stackoverflow, however, I can’t just take and erase the database and create it again important data is stored there, I think it’s about the migrations themselves, if you have a solution to this problem, I will be very glad to hear it: python manage.py migrate raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration members.0001_initial is applied before its dependency company_directory.0002_initial on database 'default'. -
Select choice from models.py in html form DJANGO
I have model in models.py with field living_countries: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra')] country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='AFGANISTAN', blank=True) I want user who has html form in front of him to be able to choose one of those choices. I've tried: in view: living_countries = models.Employee.objects.all() in html: <select name="category" id="id_category"> {% for category in living_countries %} <option value="{{ category }}">{{ category }}</option> {% endfor %} </select> It just makes weird shape like: . I can click it but it doesn't do anything. I want user to see dropdown menu or something like this. Thanks:) -
Django ModuleNotFoundError after creating models
I've started learning Django and struggling with creating/migrating a model. Everytime I try to type python manage.py migrate(or anything), I get the error ModuleNotFoundError: No module named 'People'. Here's my directory structure; |- VLCase |- VLCase |- models.py |- urls.py |- settings.py |- asgi.py |- __pycache__ |- wsgi.py |- manage.py |- db.sqlite3 Here's my models.py; from django.db import models class People(models.Model): name = models.CharField(max_length=200) I added People into INSTALLED_APPS; INSTALLED_APPS = [ 'People', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I couldn't find the answer. I would be greatly appreciated. Thanks in advance. -
Django FilterSet with annotations always returns blank response
I do have a rather simple FilterSet that I want to use on a queryset with annotations, but the issue is that it always return an empty result for some reason. This is the filter I'm having issues with class BaseGroupFilter(django_filters.FilterSet): joined = django_filters.BooleanFilter(lookup_expr='exact') class Meta: model = Group fields = dict(id=['exact'], name=['exact', 'icontains'], direct_join=['exact']) And this is the service: def group_list(*, fetched_by: User, filters=None): filters = filters or {} joined_groups = Group.objects.filter(id=OuterRef('pk'), groupuser__user__in=[fetched_by]) qs = _group_get_visible_for(user=fetched_by).annotate(joined=Exists(joined_groups)).all() return BaseGroupFilter(filters, qs).qs -
Django rest framework not returning all fields
I am trying to make a model that stores favorite shows for users, and I have been using viewsets. I have a users and shows viewset that work just like I expect them to, and I have another model that simply stores relationships between users and shows. When I add that as a viewset though, I get the id, and user, and I don't get a show. Here are the results for the favorites: [ { "id":2, "user":{ "username":"poduck", "first_name":"", "last_name":"", "email":"poduck@gmail.com", "image":null, "url":"http://0.0.0.0:8000/api/users/poduck/?format=json" } } ] There isn't even a show field. It's not like the data isn't there either. I have been able to use queries on the data with no trouble. I have access to both the show and the user from the favorite. I thought that maybe that the fact that the show points to a user, and the favorite points to a user that there may be some circular conflict there, but beyond excluding the user field from the Show serializer, I don't know what to do to fix that, and yes, I did try excluding it from the Show serializer. shows.models: from django.db import models from django.utils.translation import gettext_lazy as _ from localflavor.us.models import … -
Problem when import ModelResource from tastypie.resources
I am new to Django and I want to create some API with tastypie, but when I import ModelResource from tastypie.resource I face with error :/ I just do this: from tastypie.resources import ModelResource I get this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/macbook/Documents/PriceList/api/models.py", line 4, in <module> from tastypie.resources import ModelResource File "/Users/macbook/.local/share/virtualenvs/PriceList-ofEay4QN/lib/python3.9/site-packages/tastypie/resources.py", line 22, in <module> from django.contrib.gis.db.models.fields import … -
rtk query session id
I'm hosting a django site locally. If baseQuery has relative path like that baseQuery: fetchBaseQuery({ baseUrl: '/api' }), then session id is sent inside headers automatically headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken') } if front-end and back-end parts are hosted on different ports and the path in baseQuery is absolute fetchBaseQuery({ baseUrl: 'http://localhost:8000/api' }) (while React is running on :3000) then session id is not attached to requests and Django sends a new one with every response. Is it normal behaviour and how can it be changed? -
How to display the label from models.TextChoices in the template?
The Django docs says that one can use .label, but it does not work in the template. class Model(models.Model): class ModelChoices(models.TextChoices): ENUM = 'VALUE', 'Label' model_choice = models.CharField(choices=ModelChoices.choices) In the template object.model_choice displays the value ('VALUE'). object.model_choice.label displays nothing. How is it possible to get the label ('Label') in the template? Thanks for your time and help, it is appreciated. -
Failed template inheritance in django templating
I am in a middle of a project. The project uses basic html at the frontend. I having trouble in template inheritance. This is the basic code : - {% extends 'main.html' %} {% block content %} <h2>Home</h4> <hr> {% if request.user.is_authenticated %} {% block home %}{% endblock home %} {% else %} {% for doc in doctor %} <div> <small>Doctors around</small> <br> <a href="{% url 'profile' doc.user.id %}"><li>{{doc.user.name}}</li></a> <br> </div> {% endfor %} {% endif %} {% endblock content %} Also the code is extended to another template. The child page is :- {% extends 'rec/home.html' %} {% block home %} <div> {% if request.user.usertype == 'p' %} <h1>Hi {{request.user.name}} </h1> {% else %} <h1>Hi {{request.user.name}} </h1> {% endif %} </div> {% endblock home %} Both the files are in the same directory. But i have defined the templates dir in settings file in a different directory. -
How Do I Improve A Huge Many-To-Many Django Query To Improve Django Speed?
I have a query set like this that I need to optimize because I think this query set slows down the website performance. The user_wishlist field is a many-to-many DB relational relationship to an Account model/table. How do I? product_wishlist_store_list = [] non_paged_products = Product.objects.prefetch_related('user_wishlist').select_related('category').filter(is_available=True).order_by('created_date') for product in non_paged_products.iterator(): # Get User Wishlist try: product_wishlist = product.user_wishlist.filter(id=request.user.id).exists() if product_wishlist: product_wishlist_store_list.append(product.id) except ObjectDoesNotExist: pass So when I turn on the log for a DEBUG purpose in Django, I see that there are nearly a thousand (0.000) SELECT queries of INNER JOIN. Does the 0.000 mean there is no hit to the database or is it? Still, seeing a thousand queries like that kind of scary to me -- I feel this code is so inefficient. Is it? -
Django rest-api - attributeerror: 'str' object has no attribute '_meta'
I'm getting the following error while running manage.py in my Django rest-api. attributeerror: 'str' object has no attribute '_meta' The traceback shows the following : '' Traceback (most recent call last): File "/home/myproject/myproject-api/manage.py", line 25, in execute_from_command_line(sys.argv) File "/home/myEnv/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line utility.execute() File "/home/myEnv/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute django.setup() File "/home/myEnv/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/myEnv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/myEnv/lib/python3.9/site-packages/cacheops/init.py", line 18, in ready install_cacheops() File "/home/myEnv/lib/python3.9/site-packages/funcy/flow.py", line 231, in wrapper return func(*args, **kwargs) File "/home/myEnv/lib/python3.9/site-packages/cacheops/query.py", line 578, in install_cacheops opts = rel.through._meta AttributeError: 'str' object has no attribute '_meta' '' -
I am trying to create authentication system in Django. My code is failing to authenticate the user
<form method="post" action="/" class="mb-2"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Enter Your Username" Required> </div> <div class="form-group"> <label for="pass1">Password</label> <input type="password" class="form-control" id="pass1" name="pass1" placeholder="Enter Your Password" Required> </div> <button type="submit" class="btn btn-primary">Log In</button> </form> This is the form from home.html def home(request): if request.method == 'POST': username = request.POST.get('username') pass1 = request.POST.get('pass1') user = authenticate(username=username, pass1=pass1) if user is not None: login(request, user) return render(request,"main_tem/room.html") else: return redirect('signup') return render(request,"main_tem/home.html") this is home view from views.py in 'main' app. so as u can see from the home view if user is present or signuped it should redirect user to room.html page but when i try to do it it redirects to signup page which shouldnt happen if user is already present in data base. i am kind of lost here as i dont know what kind of solution i should search for. from what i have observed i think home view is not able to get data from the form in home.html from django.contrib import admin from django.urls import path from . import views urlpatterns=[ path("",views.home,name="home"), path("signup",views.signup,name="signup"), path("rooms",views.rooms,name="rooms"), ] for reference here is the urls.py from 'main' app -
form submission in class based view: values not adding to the database
after registering values are not adding to database and cant login views.py from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView,FormView from django.contrib.auth.forms import UserCreationForm class registration(FormView): form_class = UserCreationForm template_name='registration.html' success_url = '/login/?next=/' urls.py from.views import display_all,display_detail,insert_detail,update_detail,delete_task,login,registration urlpatterns = [ path('',display_all.as_view(),name='all'), path('view_detail/<int:pk>',display_detail.as_view(),name='detail'), path('insert_detail/',insert_detail.as_view(),name='insert'), path('update_detail/<int:pk>',update_detail.as_view(),name='update'), path('delete_detail/<int:pk>',delete_task.as_view(),name='delete'), path('login/',login.as_view(),name='login'), path('logout/',LogoutView.as_view(next_page='all'),name='logout'), path('registration/',registration.as_view(),name='register')] registration.html <body> <form action="" method="post">{% csrf_token %} {{form.as_p}} <input type="submit" value="register"> </form> -
Django Redirect for All Pages
I have multiple pages in my Django project. Here's my urls.py urlpatterns = [ path('page1', views.page1), path('page2', views.page2), path('page3', views.page3), ] I want to add a redirect that applies to all the pages so that users that aren't authenticated will be redirected to MSOAuth2. Here's my views.py def page1(request): return render(request, "page1.html") def page2(request): return render(request, "page2.html") def page3(request): return render(request, "page3.html") def MS_OAuth2(request): if not request.user.is_authenticated: return redirect('https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?') What regex or url pattern do I need to use so all my pages can redirect to views.MS_OAuth2? This is what I have so far but it's not working. I want the redirect to apply to all pages in my website. urlpatterns = [ path('page1', views.page1), path('page2', views.page2), path('page3', views.page3), path(r'^$', views.MS_OAuth2) ] Thank you! -
Can I control the order of Cascade Deletes in Django?
I have models like this: class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) class Log(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) detail = models.TextField() I also have a signal like this: @receiver(post_delete, sender=Child) def handle_delete_child(sender, instance, **kwargs): log = Log(parent = instance.parent, detail="child deleted") log.save() Now, if I try to delete the parent, I can see with debug on that the steps are going like this: Delete parent's logs. Delete parent's children (causing new log to be written as per the signal). Try to delete parent, but fails with "Cannot delete or update a parent row: a foreign key constraint fails", I think on the log created in step 2. If I was able to specify that #2 should happen before #1, I think that would solve the problem, but I cannot find any reference to such things in the docs. Even a creative solution like a new signal or a model method override would be welcome. -
Heroku deploy "command '/usr/bin/gcc' failed with exit code 1" Error
I'm trying to deploy a Django app with Heroku, but I keep receiving these errors: Does anyone know how I could solve these issues? -
Use a SQL function in the FROM clause with the Django ORM
I need to convert the following SQL into a Django ORM query but cannot find a way to pull it off. It involves using a SQL function in the FROM clause. In this case, it's a JSONB function that will put the key/value pairs of the json field into separate columns. survey.answers is a JSONB field. The underlying database is postgres. SELECT s.id, jsonb_each_text.key, jsonb_each_text.value FROM survey as s, jsonb_each_text(s.answers); -
When I do "makemigrations" I get do "makemigrations"
I removed all migration files from my django project and now when i want to re-create i get this ./manage.py makemigrations INFO: AXES: BEGIN LOG :: [axes.apps] 2022-09-15 16:51:59,923 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:33 INFO: AXES: Using django-axes version 5.31.0 :: [axes.apps] 2022-09-15 16:51:59,926 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:34 INFO: AXES: blocking by IP only. :: [axes.apps] 2022-09-15 16:51:59,927 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:46 No changes detected ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, axes, base_information, contenttypes, django_celery_beat, sessions Running migrations: No migrations to apply. Your models in app(s): 'admin', 'auth', 'axes', 'contenttypes', 'sessions' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Recommend something