Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: join two table on foreign key to third table?
I have three models class A(Model): ... class B(Model): id = IntegerField() a = ForeignKey(A) class C(Model): id = IntegerField() a = ForeignKey(A) I want get the pairs of (B.id, C.id), for which B.a==C.a. How do I make that join using the django orm? -
how can I generate dyanamic charts with highcharts.js or charts.js in django?
I have a Django app where users might want to monitor their entries where they see how many entries they added this month and throughout the whole year. basically I made a DateTime field in every model and would use that to make the queries but the problem is making the template how can I make it more dynamic so I don't have to change it every year and how should I make the queries of the dates? i would use something like this -
Django debugger hangs in settings.py - Runs fine
I can't debug custom_commands in django anymore. I try it with PyCharm (tried it with VSCode as well) using the template for Django Server and entering my custom command. If I hit run on this configuration it is running fine. If I try to debug it hangs after printing the graylog configuration. I could debug it from the settings.py until it is in venv/lib/python3.6/importlib/__init__.py in the function import_module where it tries to execute the command _bootstrap._gcd_import(name[level:], package, level) and from that on it hangs. Unfortunately I can't share the repository. The same thing happens with other custom commands as well. Any ideas for that problem? -
send a contact form to mail id and PostgreSQL database using Django
I would like to send a contactform to an emailid as well as save it to postgresql database.The following code helps me to send it to the mail id but can't save it in the database. can anyone please help me to solve this one which would be very much appreciated urls.py from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('email/', views.email, name='email'), path('success/', views.success, name='success') ] models.py from django.db import models from django.forms import ModelForm class Comment(models.Model): what_about = models.CharField(max_length=255) contact_email = models.EmailField(max_length=255) content = models.TextField() Name = models.CharField(max_length=255) Phone_Number = models.CharField(max_length=255) def __str__(self): # __unicode__ on Python 2 return self.what_about forms.py from django.forms import ModelForm from django import forms from .models import Comment class MyCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['what_about', 'content', 'contact_email', 'Name', 'Phone_Number'] views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.utils import timezone from.forms import MyCommentForm def email(request): if request.method == 'GET': form = MyCommentForm() else: form = MyCommentForm(request.POST) if form.is_valid(): form.save() cd = form.cleaned_data subject = form.cleaned_data['what_about'] from_email = form.cleaned_data['contact_email'] message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'], cd['Phone_Number'], cd['Name'], cd['content']) try: … -
How to search in django ManyToMany admin edit
I have a ManyToMany field in django that I want to update in the admin dashboard. It looks like this: However there are 200+ entries here and I would like to search through them in order to update them (instead of scrolling). When I hit a key on keyboard to filter through the list, it searches in the order of the string and doesn't look for substrings. So if I type in the word "holding" I won't get any results. How can I change this so that it searches substrings? -
urls.py works but when I use <int:id> to update a particular item then I get "Current path didn't match any of these" error
My urls.py works when trying to read or create new items. But when trying to update an existing item I do the following: in app/urls.py: ... path('update_goals/<int:id>', update_goals, name='update_goals'), in views.py: def update_goals(request, id): item = Items.objects.get(id=id) form = ItemFilterForm(request.POST or None, instance=item) if form.is_valid(): # validate the form form.save() return redirect(list_items) return render(request, 'items-form.html', {'form': form, 'item': item}) in models.py: class Items(models.Model): id = models.AutoField(db_column='ID', primary_key=True) company = models.CharField(null=True, db_column='Company', max_length=40, blank=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'Items' verbose_name_plural = 'Items' html: {% for i in item %} <a href="{url 'update_goals i.id'}"> <li>{{i.company}}</li> ... </a> {% endfor %} The other paths that I use to read current items and create new items work, but just the update doesn't work. The error: Page Not Found(404) Request URL: http://127.0.0.1:8000/%7Burl%20'update_goals%20i.id'%7D Using the URLconf defined in app1.urls, Django tried these URL patterns, in this order: ... update_goals/<int:id> [name='update_goals'] admin/ The current path, {url 'update_goals i.id'}, didn't match any of these. It might have something to do with the ID column, but I tried using update_goals/<str:company> abd i.company as well and it still gives the same error. -
Debug = False and static files not applied
I am trying to configure my django project I have the folder organization bellow my problem is that my styles.css files in not applied in my understanding, the path in STATICFILES_DIRS is correct but I have a 404 error [18/Nov/2019 13:58:01] "GET /static/css/styles.css HTTP/1.1" 404 2377 what I am doing wrong? - static - admin - django_extensions - project - settings.py - monitor - randomization - registration - static - css - styles.css - images STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = 'D:/Users/jl3/DevSpace/static/' -
Does django load translation files dynamically in runtime?
Is it possible to reload .po/.mo files in runtime dynamically in a Django web application without restarting the application server? -
Why use a pre-written audit package in Django
I am considering how to implement auditing my database with Django. There are lots of auditing packages and I am decided on using something that logs changes to models in the database, rather than externally, but can anybody give me reasons why I should not try to implement this myself? I have a finite amount of time to implement this (about a week) but should I be aware of any issues or complicating factors? I assume for each model I would need a pre-save signal and post-save signal and I would need to store the model, field, previous value and post-save value to the db -
Django-channels sending message when model changes
I'm using django-channels to organize my websockets on backend. Right now everything is working alright except of message sending to the front-end when info in db is changed. There is http endpoint to change model. Here is my websocket consumer import asyncio from asgiref.sync import async_to_sync, sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from rest_framework.response import Response from rest_framework import status from channels.db import database_sync_to_async # models and serializers from billing.models import Billing from billing.serializers import BillingSerializer from customers.models import Customer from customers.serializers import CustomersSerializer from shipping.models import Shipping from shipping.serializers import ShippingSerializer from .models import Order from .serializers import OrdersSerializer from .views import OrdersViewSet from .exceptions import ClientError from .utils import get_orders_or_error, get_orders_or_warning class OrdersConsumer(AsyncJsonWebsocketConsumer): async def connect(self): orders = await get_orders_or_warning() if 'user' in self.scope: await self.close() else: await self.accept() self.orders = set(orders) # await self.create_order(content) async def receive_json(self, content): command = content.get('command', None) orders = await get_orders_or_warning() # print(list(self.orders)) # print(set(orders)) try: if command == "join": await self.join_room(JWT_Token=content['token']) elif command == "leave": await self.leave_room() elif command == "send": await self.send_room(content['message']) except ClientError as e: await self.send_json({"error": e.code}) async def disconnect(self, code): for room_id in list(self.rooms): try: self.send_json({ 'type': 'CLOSE', 'message': "Socket closed" }) await self.leave_room(content['token']) except ClientError: pass async … -
Manipulate string data inside an api response
I have an API in my DRF which sends data in a HTML String Views.py class map(APIView): def get(self, request): .... data = pd.DataFrame({'lat': latitude, 'lon': longitude, 'name': markers_list}) m = folium.Map(location=[21, 78], tiles="OpenStreetMap", zoom_start=4.75) for i in range(0, len(data)): folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name']).add_to(m) print(" m is ", m) html_string = m._repr_html_() context = {'map2': html_string} return Response(context) And the context is: { "map2": "<div style=\"width:100%;\"><div style=\"position:relative;width:100%;height:0;padding-bottom:60%;\"><iframe src=\"data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh...cHQ+\" style=\"position:absolute;width:100%;height:100%;left:0;top:0;border:none !important;\" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe></div></div>" } In my Iframe I just need data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh...cHQ+ which is in front of <iframe src=\ in the response, How Can I retrieve this data? -
How to pass data from a Django Template to the Rest Framework (DRF) without a model?
I have a template that allows me to upload an image. This image is not stored in the model, however; it's saved within the media folder in my Django project. After doing so, I want to view this image filename within my DRF after calling the API url. I want the result to be like this in my API View: {"image" : <"image filename or absolute path of the filename">} This is what I tried so far: views.py: #Code for viewing the API class API(APIView): def get(self, request, format = None): name = request.data['image'] # This is not accurate but I intend to grab the image from my Template. if name: image = [{"image_name": name}] serializer = ImageSerializer(image, many = True).data return Response(serializer, status = status.HTTP_201_CREATED) else: return Response({"image_name" : "no image available"}, status = 400) serializers.py: from rest_framework import serializers class ImageSerializer(serializers.Serializer): image_name = serializers.CharField() urls.py: from django.urls import path from myapp.views import API from myapp import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path("upload/", views.upload, name = "upload"), #Template that allows uploading an image path("img_api/", API.as_view(), name = "img_api"), #DRF view ] urlpatterns = format_suffix_patterns(urlpatterns) Can someone please let me know how to do this? How can … -
Add a row in django admin
I wanted to add a row at the end of the list or may be in the footer showing total of count review. How do I customise the admin view ? -
How to retrieve all items created by a user using the django rest framework
I am trying to get only courses belonging to a particular user below I have the model, serializer and view I am using to try and achieve this. If I delete the entire get_queryset function from the view the api returns the appropriate user and every course created by every user. If get_queryset remains, the api always returns user not found and still gives every course that exists. Can anyone point me to how I can achieve my desired result. view: class UserDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsProfileOwnerOrReadOnly] # queryset = User.objects.all() serializer_class = UserSerializer def get_queryset(self): user = self.request.user queryset = User.objects.all() if user is not None: queryset = queryset.filter(courses__owner_id=user.id) return queryset serializer class UserSerializer(serializers.ModelSerializer): courses = serializers.PrimaryKeyRelatedField( many=True, queryset=Course.objects.all()) class Meta: model = User fields = ['id', 'username', 'courses'] Model class Course (models.Model): title = models.CharField(max_length=200) description = models.TextField() pub_date = models.DateField(default=date.today) owner = models.ForeignKey('auth.User', related_name='courses', on_delete=models.CASCADE) def __str__(self): return self.title -
stream torrent while downloading python/django
i'm trying to make a streaming application in python 3 and django. I should first download a film by torrent and stream it during the downloading. I can't find how to do it, someone can help me ? -
Return a fake year between a range using Faker?
I am trying to create some fake years (just years not dates) in a range from 1800 to 1900 using Faker. I have read the docs regarding fake dates and years and it seems like Faker.year() is the way forward. However there is no documentation regarding adding a range to .year(). Currently, it just outputs years post 1970. -
Django admin model description list
When I am in something like /admin/ I see a list of all my apps and models (with add and change buttons) I would like to add a description for each model below the model name, is that possible I can see how to add a description on the list change list view Model description in django-admin Is it possible to do something similar when I see my list of models Thanks Grant -
Django Python Where to add Auxiliary Functions to not repeat code?
I come from native POO programming languages and I'm new in Python, also Django. I see that in Django they put all code from an app in same views.py or models.py. Now I'm in a view called: def create_ticket(self): .... And inside I have this code is_staff=User.objects.get(pk=request.user.id).is_staff if is_staff==1: R_Client_Accountant = LinkUserContable.objects.filter(contable=mongoId) print(R_Client_Accountant) accountantList = [] for relation in R_Client_Accountant: try: rmongosql = RMongoSql.objects.get(mongoId=relation.user.id) user = User.objects.get(pk=rmongosql.helpdeskId) accountantList.append((user.id,user.username)) except: pass else: R_Client_Accountant = LinkUserContable.objects.filter(user=mongoId) accountantList = [] for relation in R_Client_Accountant: try: rmongosql = RMongoSql.objects.get(mongoId=relation.contable.id) user = User.objects.get(pk=rmongosql.helpdeskId) accountantList.append((user.id,user.username)) except: pass As you can see I repeat code inside the 'try' just exchanging {user XOR contable} If I want to write a function passing by parameter this {user XOR contable} where should I place it ? To me, in corresponding model from models.py is not correct because there are so much code lines referring to different models and views.py is just for view functions right ? Regards, Víctor. -
Modifying auth_user and auth_password for send_mail on django-registration
I'm using django-registration in my project, but I'm slightly stuck on something. I don't want django-registration to use the global username / password for email defined in my settings file. I want any emails sent from django-registration to contain auth_user and auth_password perameters in the send_mail function. I'm not sure how to override these send_mail functions, which will be in the account signup and password reset functions. Can you think of what the best way to do this would be? Thanks! -
Integrate angular application in Django project
I am developing a project with Django in backend and Angular in frontend. My Angular build application contains one index.html file, some folders and some files. I want to integrate my angular application with my Django project, which contains some applications. What should be my directory structure. Where do I need to map my URLs to call the index.html page of angular. The output I need to achieve is: When hitting the homepage URL, the single sign on application of Django should run to authenticate the user and after authentication redirection to index homepage(of angular) should happen. What should be the way to achieve this? -
Problem with static files configurations - don't understand project/app staticfiles organization
I have started to develop a Django project with currently 3 apps (registration, monitor and randomization) I wand to set parameters for statics files. I am using bootstrap 4.0 and I have currently only one css files for sticky footer as this css is for all template of the project, I have created a static folder at the project's root: -project - settings.py - monitor - randomization - registration - static - css - styles.css - images and in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = 'D:/Users/jl3/DevSpace/intenseTBM_eTool/static/' I have run the commande collectatic but I have an error: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. how can I set 'global' static files for my project? how should I set parameters? -
pdf tag doesnt open pdf files on chrome but works on other browsers, why?
i am trying to display pdf documents on the browser but its not displaying on chrome, instead its downloading, but on other browsers like IE it's working just fine {% block content_display %} <embed type="application/PDF" src="{{bk.upload_content.url}}" width="100%" height="650"/> {% end block %} -
Show distinct values in dropdown menu with django-select2
I am using django-select2 with forms for creating a drop-down list, using ModelSelect2Widget. My problem is that I filter on the field 'name' and several objects can have the same 'name' but different 'value' (see model description below). This leads to the same name appearing several times in the dropdown menu. I would like to remove these duplicates. I tried to use .distinct('name') for selecting the queryset, but it doesn't seem to work. example of result obtained with ModelSelect2Widget Below is the description of the code I use: I have two models linked by a foreign key models.py class Who(models.Model): name = models.CharField(max_length=256) value = models.CharField(max_length=256) def __str__(self); return str(self.name) class Data(models.Model): who = models.ForeignKey(Who) And I use the form described here: forms.py from django_select2.forms import ModelSelect2Widget ... class CreateDataForm(ModelForm): class Meta: model = Data fields = ('who',) widgets = {'who': ModelSelect2Widget( queryset=Who.objects.all().distinct('name'), search_fields=['name_icontains'] )} Does anyone know how I could remove these duplicates? -
Why i am getting below error during installation of Django==2.0?
I have already install packages using pip several times. I am using Python3 and django==2.0. But today when i tried to install django again it throw below error. Please help me someone. PermissionError: [Errno 13] Permission denied: '/home/manas/.local/lib/python3.6 I tried below things sudo apt install python3-pip sudo apt-get install python-django -
Django Azure AD Integration
I'm currently integrating SSO using Azure AD for a Django Project. I'm currently using the package: https://github.com/leibowitz/django-azure-ad-auth . I have followed the docs to setup the Azure AD Authentication . On entering the application url, it takes me to the microsoft login page and after entering the credentials it's redirected to the application. But on redirection to the application after the Azure Auth, the code checks in the session for 'nonce' & 'state' variables , which are strangely returned as None and hence the application redirects to the failure url.