Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
How to manually connect postgres database (inside container) from django container? [closed]
I am not able to connect a database from another container in Django(inside a container). The database container is from another compose file. Currently, I am defining DATABASE_URL as postgres://db_user:password@localhost:5432/db_name in Django settings configuration. But, it's not working. Any idea how to resolve it? -
Django models not returning property value
I'm making an API with DRF and now still making database but i got a problem with a field from models.py my script of models.py class Inflasi(models.Model): sandang = models.FloatField(null=True) sembako = models.FloatField(null=True) perumahan = models.FloatField(null=True) kesehatan = models.FloatField(null=True) transportasi = models.FloatField(null=True) informasi = models.FloatField(null=True) rekreasi = models.FloatField(null=True) pendidikan = models.FloatField(null=True) penyedia_pangan = models.FloatField(null=True) perawatan_pribadi = models.FloatField(null=True) total_inflasi = models.FloatField(null=True) tanggal = models.DateField(null=True) @property def total_inflasi(self): return self.sandang + self.sembako + self.perumahan + self.kesehatan + \ self.transportasi + self.informasi + self.rekreasi + \ self.pendidikan + self.penyedia_pangan + self.perawatan_pribadi def __str__(self): return str(self.tanggal) class Meta: verbose_name = "Inflasi" verbose_name_plural = "Inflasi" and that not return the property value in Django admin dashboard and this my admin.py script @admin.register(Inflasi) class InflasiModelAdmin(ImportExportModelAdmin): class Meta: model = Inflasi fields = '__all__' what must i do for fix that? -
auto download the pdf file right after payment is done
what could be the function to automatically download pdf file automatically right after payment is done and page loads. Actually algorithm guides are there in the media folder but i dont know how to make it download right after payment is made. i am totally clue less help me out please.. views.py def payForAlgorithmGuide(request): print('---------payForAlgorithmGuide--------------') if request.method == 'POST': algoName = request.POST.get('algoName') print('algoName:', algoName) return render(request, 'pay-for-algo-guide.html') models.py class AlgorithmGuide(models.Model): id = models.AutoField(primary_key=True) # buyer_id = models.IntegerField(blank=True, null=True) algorithm_name = models.CharField(max_length=200, blank=True, null=True) guide_data = models.FileField(upload_to=user_directory_path2, null=True, verbose_name="", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx','pdf'])]) class Meta: db_table = 'AlgorithmGuide' -
how to use two tables inside a query? django
I am trying to use two tables inside one django query. But my query is resulting as "invalid JSON" format. I want to filter data in Request table by (status="Aprv"). The Request table contains attributes 'from_id' and 'to_id'. The uid is the id of the user who is currently logged in. If the current user(uid) is having the 'from_id' of Requests table, the query should return data of 'to_id' from the 'RegUsers' table. If the current user(uid) is having the 'to_id' of Requests table, the query should return data of 'from_id' from the 'RegUsers' table. class frnds(APIView): def post(self, request): uid = request.data['uid'] ob = Requests.objects.filter(status="Aprv") fid = ob.value('from_id') tid = ob.value('to_id') if fid == uid: obj = RegUsers.objects.filter(u_id=tid) else: obj = RegUsers.objects.filter(u_id=fid) ser = android_serialiser(obj, many=True) return Response(ser.data) I dont want to use foreign keys. Please Do Help me Currect the syntax. -
How to get instance of Parent Object and Create Related Child at the same time
Let's say we have: class Parent(Model): pass class Child(Model): parent = ForeignKey(Parent, related_name='children') Now on Child Creation: parent = Parent.objects.get(id=id) Child.objects.create(parent=parent) Here I can see 2 things happening, getting an instance of a parent object and then creating the child object. How I can process it at a time? on child creating. Is it fine to follow the above approach? or we can make it better. -
djagno management command as a package?
I'm trying to have a directory structure for my Django custom commands. According to the Django tutorial commands are created as modules under management/commands directory. e.g. management/commands/closepoll.py I have many commands so I'm trying to split them into packages. I want to have a package structure, like: management/commands/closepoll/closepoll.py <-- contains the Command class. management/commands/closepoll/closepoll_utils.py management/commands/closepoll/__init__.py Tried that, but Django does not recognize the command.