Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refuse connect to my local server database MySQL
I working with a project in Python and Postgress And I should had a methode to connect to db from MySQL I write this function def connexion (): db = mysql.connect( host = "localhost", user = "root", passwd = "", database = "Test", port ="3306" ) return db when I call this function to verify linking database I had this error raise exception.with_traceback(None) from new_cause mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused) What I should I do to make this connection validated RQ: I'm sure about name and port number -
Django filter query when two datetime columns have same date
I want to filter a Django queryset when two datetime columns have the same date. I have tried the following two codes that do not work : drivers = drivers.filter(deleted_at__date=F("created_at__date")) and drivers = drivers.filter(deleted_at__date=F("created_at")) -
Reverse for 'app_list' with keyword arguments '{'app_label': 'common'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|otp_totp)/$']
config/urls.py from django_otp.admin import OTPAdminSite from django.contrib.auth.models import User from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice, TOTPDeviceAdmin) urlpatterns = [ re_path(r'^admin/', admin_site.urls) ] common/admin.py from common.models import ConfigVar, ConfigVarFile, Source from config.urls import admin_site admin_site.register(ConfigVar) admin_site.register(ConfigVarFile) admin_site.register(Source) error {"@timestamp": "2022-08-24T16:21:04.889396Z", "ecs.version": "1.0.0", "log.level": "ERROR", "message": "Internal Server Error: /admin/", "process.thread.name": "Thread-1", "log.logger": "django.request", "fileName": "log.py", "funcName": "log_response", "lineNo": 241, "spanId": "d5bb9ad916674801", "traceId": "d5bb9ad916674801", "error.type": "<class 'django.urls.exceptions.NoReverseMatch'>", "error.message": "Reverse for 'app_list' with keyword arguments '{'app_label': 'common'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|otp_totp)/$']", "error.stack_trace": "Traceback (most recent call last):\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 55, in inner\n response = get_response(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/core/handlers/base.py\", line 197, in _get_response\n response = wrapped_callback(request, *callback_args, **callback_kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 261, in wrapper\n return self.admin_view(view, cacheable)(*args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/utils/decorators.py\", line 133, in _wrapped_view\n response = view_func(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/views/decorators/cache.py\", line 62, in _wrapped_view_func\n response = view_func(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 242, in inner\n return view(request, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 553, in index\n app_list = self.get_app_list(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 537, in get_app_list\n app_dict = self._build_app_dict(request)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/contrib/admin/sites.py\", line 519, in _build_app_dict\n \"app_url\": reverse(\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/urls/base.py\", line 88, in reverse\n return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)\n File \"/Users/tiwari.aditya/.pyenv/versions/3.9.13/envs/amsnbfcvenv/lib/python3.9/site-packages/django/urls/resolvers.py\", line 802, in … -
A shutdown hook for Django with mod_wsgi
I have a simple Django server that runs and manages some services in the backgrounds. I want to stop those services when the server stops. After looking online, I have found this solution: signal.signal(signal.SIGINT, _stop_services) And it works great when I run the server with python manage.py runserver. But, when I run the server with Apache engine and mod_wsgi and restarting/stopping the apache server, the callback is not invoked. I also tried using SIGTERM and even the atexit module, but none of them worked. Is there any built-in solution in Django for this? I know that in packages like aiohttp you can add a listener that will be called when the server shuts down. -
How to make create and retrieve work in the same serializer?
i have a somewhat tangled problem, I have the following models class ModelA(models.Model): name = models.CharField(max_length=64) class ModelB(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) and the serializers class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = '__all__' class ModelBSerializer(serializers.ModelSerializer): terminal = ModelASerializer(read_only=True) class Meta: model = ModelB fields = '__all__' when I want to create a ModelB object including the model_a_id it has 2 responses depending on whether I put the read_only=True or False I would like that when I try to create via POST in an object of ModelB I only have to send the mode_a_id, but at the same time when I do a GET it returns the serialized data of ModelASerializer in the model_a field. If I put the read_only = True it only works to receive the serialized data in GET, but via POST I cannot assign an id to model_a in case of read_only=False, I can't assign the id to that object either since it asks me for a dictionary, I imagine to create a new ModelA Object, but I only want to assign one that already exists. A solution may be to place the serializer with another variable name, but I would really like it to … -
show dynamic data from form value change in template
I'm new to django, i'm used to angular. i'm trying to do something that make sense to me in angular and I can't achieve in django. I'm working with python 3.9 and django 4.1 I simplified my case to this.. I have a form that I created and and a view for it, i have a select element, whenever i select something, i want to show what i selected. so I created a LocationForm form class: class LocationForm(forms.Form): apartment_type = forms.ModelChoiceField(queryset=ApartmentType.objects.all()) apartment type is just a list of apartment types (building, apartment, garden and so on) i past the form to the view: def location(request): context = {'form': LocationForm} return render(request, 'prospects/location.html', context) and the code for the view: {% load static %} <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> CCC{{ form.apartment_type.value }}DDD<br/> the problem is that no matter what I select, form.apartment_type.value still shows None, it's not being updated. i guess i'm used to angular too much but this issue is really alarming for me if django only parses things statically, i guess i'm not used to it and i have no idea how to resolve it otherwise. in my full code i want to … -
Fcm-Django IOS no sound
So everything works fine in terms of notifications being sent. however, no sound gets played when a notification is delivered to an IOS device I am using fcm-django as the package. here is the code I use: myself is just the user sending the notification to. fcmdevicee = FCMDevice.objects.get(user=usertosendto) fcmdevicee.send_message(Message( notification=Notification( title=f"{myself.username}new notification") )) -
Django- Only pulling through the base template when trying to extend
I'm making my first Django app and I'm trying to set up my signup.html page while extending my base.html. The URL I have configured works, however it only pulls through the base.html template. I've checked the view, url and the signup.html template and I'm not sure what I'm getting wrong. signup.html: {% extends './layout/base.html' %} {% load static %} {% block content %} <h1>Signup</h1> {% endblock content %} base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&family=Oswald&display=swap" rel="stylesheet"> <link rel="icon" href="{% static 'favicon.ico' %}"> <a target="_blank" href="https://icons8.com/icon/DpuVIej1M9Br/health">Health</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a> <title>Your Health Now</title> </head> <body> <h1>Hello, world!</h1> </body> </html> urls.py: from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views app_name = 'HealthHub' urlpatterns = [ path('signup/', views.signup, name='signup'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))) ] views.py: from django.shortcuts import render def signup(request): return render(request, 'HealthHub/signup.html') -
Django query with TruncHour for multiple product with each group latest sum. How to do that?
The scenario is: The product database price update every hour. People can add product to wishlist. Wishlist page has some graph. That shows last 24 hours price changes. I want to show every hour price change of all his wishlist product for last 24 hours. I am trying but I can't complete the query. What I am trying is given below: now = datetime.datetime.now() last_day = now - datetime.timedelta(hours=23) x = ( FloorPrice.objects.filter( product__in=vault_products_ids, creation_time__gte=last_day ) .annotate(hour=TruncHour("creation_time")) .values("hour", "floor_price") ) Suppose I add in wishlist 4 product. Now I want each hour 4 products sum with that hour latest entry(each hour each product has multiple floor price, so we need to pick the last entry of each product on that hour). -
Can't insert an element to a MS SQL Server table without identity field in Django
I have a legacy table in MS SQL Server in which the ID is not an identity field, and I can't insert entities because it hasn't an identity property. In order to find the error I created a new table with the same characteristics and just two fields: ID and name. When I try to insert a record I get the same message: Table 'base_test' does not have the identity property. Cannot perform SET operation. (8106) (SQLExecDirectW) If my table has an identity record it inserts it correctly. I tried with ODBC Driver 17 for SQL Server, ODBC Driver 13 for SQL Server, pydobc, mssql, always the same message. Is it possible that the ODBC driver is not prepared for this situation? -
django form errors not showing on template
I'm using the basic django registration form and I'm not getting any errors displayed. I've seen a bunch of answers and nothing is working for me. I'm not sure if it's because I have custom css for the page or bootstrap or something else. Basically how do I display the errors in this particular case. Here's my form: <div class="form-content"> <h1>Sign Up</h1> {% if user.is_authenticated == False %} <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn form-btn">Sign Up</button> <h4><span>or</span></h4> <a class="btn google-btn" href="{% provider_login_url 'google' %}" role="button" style="text-transform: none; width: 100%" > <img width="20px" style="margin-bottom: 3px; margin-right: 5px" alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" /> Sign up with Google </a> </form> {% else %} <p>You're already registered...</p> {% endif %} </div> Here's my view: class UserRegistration(generic.CreateView): form_class = RegisterForm template_name = 'registration/registration.html' def form_valid(self, form): user = form.save() form.registration_notification() login(self.request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect(self.request.GET.get('next')) and form: class RegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def registration_notification(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if self.is_valid(): registration_notification_task.delay(email, username) I'm not sure where to return the errors or where to validate the form and no answers for other questions have … -
Django Error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
I'm having some problems when running django on my machine, even though it's inside the virtual machine it accuses an error, I'm using macOS. Below is an image of my manage.py Print screen Manage.py -
Django Admin changelist submit redirect
Is it possible to have django redirect to another page after submitting changes directly in the changelist view? (After specifying the list_editable fields) Already tried with different methods response_post_save_change, response_change or response_add but none of them worked. I suspect it may be within the changelist_view, not sure how to tackle it since it handles the form saving. -
Django filter using Conditional Expressions
I have a model (let's say class Foo) that holds 2 important attributes and each attribute can have one of the two values, here is some pseudocode: period_condition = cons.BEFORE or cons.AFTER period_days = const.START_DATE or cons.END_DATE Now, I need to construct a filter dynamically based on those 2 values. I can do it with if-else but it seems pretty ugly and hard to read/follow: def list_subscriptions_for_sending(foo: Foo) -> QuerySet[Subscription]: days = foo.days if foo.period_condition == BEFORE: if foo.period_date == START_DATE: filter = Q(start_date=get_today() + timedelta(days=days)) if foo.period_date == END_DATE: filter = Q(end_date=get_today() + timedelta(days=days)) if foo.period_condition == AFTER: if foo.period_date == START_DATE: filter = Q(start_date=get_today() - timedelta(days=days)) if foo.period_date == END_DATE: filter = Q(end_date=get_today() - timedelta(days=days)) I was trying using Case and When - then Django's conditional expressions, but was getting the following error: *** TypeError: Cannot filter against a non-conditional expression. I cannot understand how the expression is non-conditional. In my understanding, it goes through each When of the Case and if the expression is True it assigns the Q expression from then : filter = Case( When( Q( foo.period_condition == BEFORE ) & Q( foo.period_date == START_DATE ), then=Q(start_date=get_today() + timedelta(days=days)), ), When( Q( foo.period_condition == BEFORE … -
How to get an attribute of a dictionary in a Django template?
I am trying to parse RSS feeds with a Django app. So far it works, but I can't get the images in the feeds to be shown. My views.py looks like this: from django.shortcuts import render from web.models import airline, world import feedparser from django.http import HttpResponse def news(request, selection): news = ['https://www.aerotelegraph.com/feed', 'https://www.aviationweek.com/rss.xml', 'https://www.airway1.com/rss'] selection = news[selection] feeds = feedparser.parse(selection) context_dict = {} context_dict['url'] = feeds.feed.link context_dict['titel'] = feeds.feed.title context_dict['feeds'] = feeds return render(request, 'web/news.html', context=context_dict) My template news.html looks like this: {% load static %} {% block body_block %} <h4>News from <a href="{{ url }}" target="news">{{ titel }}</a></h4> <ul class="list-group"> {% for entry in feeds.entries %} <li class="list-group-item"> <a target="news" href="{{entry.link}}"><b>{{entry.title}}</b></a><br> <img src="{{entry.image}}{{entry.media_content}}" width="250"><br> <p>{{entry.description}}</p> </li> {% endfor %} </ul> {% endblock %} Now instead of the actual image, it inserts the following string. [{'url': 'https://aerotelegraph.imgix.net/production/uploads/2022/08/brussels-a330.png?auto=compress%2Cenhance%2Cformat&ch=Save-Data&crop=edges&dpr=1&fit=crop&h=316&w=653&s=7e73358df59ca8274c54497fbe55ed6c', 'medium': 'image'}] This looks like a dictionary object, but I have tried to do the following variants, but all come up with an error. <img src="{{entry.image}}{{entry.media_content[0]['url']}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content['url]}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content.['url']}}" width="250"><br> <img src="{{entry.image}}{{entry.media_content.url}}" width="250"><br> It kees saying TemplateSyntaxError at /web/news/2, Could not parse the remainder: '[0].['url'] from 'entry.media_content[0].['url'] (or similar with the other variants). Is it possible to get that … -
How to add Postgres extension when pushing local database to Heroku
I have a Django application which relies upon the postgis Postgres extension. I want to copy my local Database to Heroku using pg:push, but I get numerous django.db.utils.ProgrammingError: relation does not exist errors, following on from: pg_restore: error: could not execute query: ERROR: type "public.geography" does not exist LINE 6: coords public.geography(Point,4326), ^ Command was: CREATE TABLE public.outreach_localcompanylocation ( id bigint NOT NULL, long_name character varying(200) NOT NULL, city character varying(200) NOT NULL, country character varying(3) NOT NULL, coords public.geography(Point,4326), google_location_id bigint, state character varying(200) ); This seems to be because pg:push does not enable the postgis extension (typically enabled by running the SQL command CREATE EXTENSION postgis;). If I try to enable it manually on a new Heroku database, then run pg:push, I get this error: Remote database is not empty. Please create a new database or use heroku pg:reset So is there a way to run CREATE EXTENSION postgis; as part of the pg:push process? -
How to filter a django queryset using case insensitive __in?
I have a model: class Skill(models.Model): name = models.CharField(max_length=120) icon = models.CharField(max_length=20) color = models.CharField(max_length=7) I want to do the following filter, but case insensitive: skill_names = ['Code Quality', 'Analytical Thinking', 'Productivity', 'Communication'] Skill.objects.filter(name__in=skill_names) -
OAuth 2 for authentication in native apps
Is it good to use OAuth for self-authentication in native apps? For example, I have a site and want to create a native application for that Now is it a good idea to use OAuth (OpenID Connect) to log in and register users in the app to use API on my site? Another example, Facebook use OAuth in the Facebook application login page -
Heroku Deployed Django App displaying ProgrammingError
I used Django Default Database Sqlite but when deploying I used Postgresql but I get this error below... I need help please I have made migrations but still meanwhile it is working perfectly on localhost with sqlite database. The Error -
djangorestframework: use kwargs instead of requests
My code is littered with a lot of parsing keys from request.data objects inside functions, which makes it hard to follow data flow. How can I change from from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated @api_view(["POST"]) @permission_classes([IsAuthenticated]) def greet(request): # FYI for Character.AI we use the chat and not this stateless_chat view. payload = request.data user = payload.get("user", "test") friend = payload.get("friend", "bart") num_friends = int(payload.get("num_friends", 16)) return None to @api_view(["POST"]) @permission_classes([IsAuthenticated]) def greet(user:str='test', friend:str='bart', num_friends:int=16): return None -
removing more than a character using cut
So I'm trying to search for Elements using query selector, the problem is, due to the way theses IDs are generated (with the name of regions, stores, and sale type, from the context) some of then includes spaces or dots on them which don't let them be searched. I have identified the spaces were breaking my searches before and used cut to remove the spaces from IDs. Is there a way to use cut to remove diferent characters as if I'm using cascaded replaces (in python) or replaceAlls (in JS) to make these ids don't have any spaces or dots? I tried using pipes but it didn't work. how can I do it? Snippet of the formation of the elements: {% if data.nivel == "N0" %} <tr id="family_{{ data.familia_produto|cut:" " }}" class="bu_name_line {{ data.nivel }} title0" data-level="{{ data.nivel }}" data-family="{{ data.familia_produto }}" data-regional="{{ data.nome_regional }}" data-segment="{{ data.segmento }}" data-bu-name="{{ data.nome_filial }}" onclick="show_lines('N1','{{ data.familia_produto }}')"> <td id='bu_name' onmouseenter='hight_light(this)' onmouseleave='hight_light(this)'> {{ data.familia_produto }} </td> {% elif data.nivel == "N1" %} <tr id="regional_{{ data.familia_produto|cut:" " }}_{{ data.nome_regional|cut:" " }}" class="bu_name_line {{ data.nivel }} title1 hide" data-level="{{ data.nivel }}" data-family="{{ data.familia_produto }}" data-regional="{{ data.nome_regional }}" data-segment="{{ data.segmento }}" data-bu-name="{{ data.nome_filial }}" onclick="show_lines('N2A','{{ data.familia_produto }}','{{ … -
Django conventional filestore location for miscellaneous files read by an app's views?
Is there a convention for where to put miscellaneous files which are opened and read by Django views, but which aren't python code or html templates and aren't processed by the temmplate renderer? (In my case, I have a View which returns an application/excel .xlsx file to the user. It is generated by reading in a "template" xlsx file with lots of tricky formatting and formulae but no data values. Openpyxl is used to insert selected data from the db, and the resulting workbook is saved and sent to the user.) -
I'm trying to open the admin website for my project but it isn't coming up, rather it shows the Django install worked successfully page. What can I do
I've created superuser and I've also ran the server yet it keeps showing the django "install worked successfully" page. Please what can I do? -
Add ID field to ModelForm
I need to add ID field to my form, and I'm getting so mad Currently I have : class ProductVideoForm(forms.ModelForm): class Meta: model = ProductVideo translatable_fields = get_translatable_fields(ProductVideoTranslation) fields = [ "product", "id", #added!!!! "type", "placeholder", ] + translatable_fields widgets = { "placeholder": ImageInput(), } trans_fields_per_lang = get_trans_fields_per_lang(translatable_fields) I added ID to fields, and the template is: {{ video_formset.management_form }} Why Is ID not displayed ?? actually, I just need display it, not updated. -
How to set cookie on DRF viewset?
I'd like to know how to set a cookie on Django rest framework ViewSet/ModelViewSet. I read some SO posts that say you can use Response({serializer.data}), but in retrieve it may be okay, but for create() like the following one, doesn't Response() affect its following processing? Actually when I used HttpResponse() like HttpResponse(status=401, reason="you cannot post anymore.") replacing the raise PermissionDenied() line in the below one, I got a 500 error (error says AttributeError: 'collections.OrderedDict' object has no attribute 'pk' or such) but not the specified 401 code. So basically the following explains what I want to do, that is denies when the user's post count is >= 4, but otherwise continues perform_create() and the following DRF script, with attaching a cookie, that tells browser "you have n post slots left". class PostViewSet(viewsets.ModelViewSet): .. def perform_create(self, serializer): role = self.request.user.userproperty.role if role == "guest": post_count = self.request.user.posts.count() if post_count >= 4: raise PermissionDenied({"message": "you cannot post anymore."}) else: response = // anyhow gets response here // response.set_cookie("notify", "your post slot is " + str(3 - post_count) + "left now.") serializer.save(user=self.request.user) But I don't know how can I possibly get response from something, or calling Response() without harming consequences script. I tried, …