Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to send dynamic ID info from django class-based view to formset
I have a class-based view that renders a formset based on the project selected. Each project has a unique project_id. I get a 404 error caused by Line 14(below) in views.py if don't hard-code the project_id (ie '4') to replace 'None'.Also,the formset doesn't load if i don't hard-code the project_id in Line 4 under forms.py. Since the project_id needs to be passed automatically,how can i get it updated and passed into the formset? Thanks. I tried this: views.py class ReqView(CreateView): template_name = "req_view.html" model = ProjectBudgetReq form_class = ReqForm def get_form_kwargs(self,*args, **kwargs): form_kwargs = super(ReqView, self).get_form_kwargs(*args, **kwargs) form_kwargs['project_id'] = self.kwargs.get('project_id') print("get_form_kwargs:",form_kwargs) return form_kwargs def get_context_data(self,**kwargs): project_id = kwargs.pop('project_id',None)#Line 14 404 Error project = get_object_or_404(ProjectDetails,id=project_id) formset = ReqFormSet(instance=project) context = super(ReqView, self).get_context_data(**kwargs) context['project'] = project context['formset'] = formset return context def get_context_kwargs(self,**kwargs): context_kwargs = super(ReqView,self).get_context_kwargs(*args,**kwargs) context_kwargs['project_id'] = self.kwargs.get('project_id') return context_kwargs forms.py class CreateReqForm(forms.ModelForm): def __init__(self,*args,**kwargs): project_id = kwargs.pop('project_id',None) #Line 4 Formset not rendered super(CreateReqForm,self).__init__(*args,**kwargs) self.fields['proj_name'].queryset = ProjDesc.objects.filter(id=project_id) self.fields['budget_desc'].queryset = ProjBudget.objects.filter(proj_name_id=project_id) class Meta: model = ProjBudgetReq fields = '__all__' BudgetReqFormSet = inlineformset_factory(ProjDesc, ProjBudgetReq, form=CreateReqForm, fields='__all__',extra=2) Issues: views.py #Line 14: 404 Error since it returns 'None' forms.py #Line 4: Formset does not render, since it's 'None' -
Using Python, I want to check the data that is Type_Of_Wallet is already exists in my MySQL database table or not?
I am new to Django where I designed an application where I created a form in templates and used a database that is in localhost/PHPMyAdmin. Now when the user enters the data in given fields and presses the submit button, it should check in the database whether the given data is present in the database or not. But my code is not working. `views.py import mysql.connector from django.http import HttpResponse from django.template import loader from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): if request.method == 'POST': Type_Of_Wallet = request.POST.get('Type_Of_Wallet') BLE_MAC_ID = request.POST.get('BLE_MAC_ID') BAR_CODE = request.POST.get('BAR_CODE') Version = request.POST.get('Version') context = { 'Type_Of_Wallet': Type_Of_Wallet, 'BLE_MAC_ID': BLE_MAC_ID, 'BAR_CODE': BAR_CODE, 'Version': Version, } template = loader.get_template('valid_form/showdata.html') return HttpResponse(template.render(context, request)) else: template = loader.get_template('valid_form/index.html') return HttpResponse(template.render()) mydb=mysql.connector.connect( host = 'localhost', user = 'rajat', passwd = 'rajat', database = 'MyForum' ) mycursor=mydb.cursor() print('Enter Type_Of_Wallet:') Type_Of_Wallet=Input(context) CheckType_Of_Wallet=mycursor.execute( 'SELECT Type_Of_Wallet FROM form_simpleform WHERE Type_Of_Wallet=%(Type_Of_Wallet)s', {'Type_Of_Wallet':Type_Of_Wallet}) if CheckType_Of_Wallet !=0: print('Type_Of_Wallet does not exit') else: print('Its Available') ` index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Validation</title> </head> <body> <h2>Validation</h2> <form method="post" action="/getdata/"> <table> <tr> <td>Enter Wallet Type:</td> <td><input type="text" name="Type_Of_Wallet"/></td> </tr> <tr> <td>Enter your BLE_MAC_ID:</td> <td><input type="varchar" name="BLE_MAC_ID"/></td> </tr> <tr> <td>Enter your Bar Code:</td> <td><input type="varchar" name="BAR_CODE"/></td> </tr> <tr> … -
Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document
I am using preview-generator to make a pdf from docx file in Django. The code is working properly in my local machine but the same deployment is not working on the server which is ubuntu 18.04. I am having Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document error. I have researched about it and found libre office needs to be installed in the server and its already present on my server. can you please suggest what I need to do or how I can define path of libre office. I am using Django and once I use the shell the file generated properly but in the the web its not working. This is the error on terminal. gunicorn[29453]: Builder is missing a dependency: this builder requires inkscape to be available gunicorn[29453]: Builder is missing a dependency: this builder requires convert to be available Builder is missing a dependency: this builder requires qpdf to be available Builder is missing a dependency: this builder Builder is missing a dependency: this builder requires libreoffice to be available -
How to convert this raw query to Django ORM query set
task_data_calldetail.objects.raw('SELECT id from `task_router_calldetail` where direction = "inbound" AND YEARWEEK(`time_stamp`, 1) = YEARWEEK( "' + today_date + '" - INTERVAL 1 WEEK, 1)')