Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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)') -
Slug generator don't generate slug for tablecontent
I don't know why the slug generator does not generate a slug for the items in my table. It works perfectly if i save the data with the .save() command. But it does not work with a pipeline wich does not use django related commands. I use a Postgresql database Model: class WhiskyContent(models.Model): products = models.CharField(max_length=250) price = models.FloatField(default=20) date = models.CharField(max_length=250) picture = models.CharField(max_length=250) site = models.CharField(max_length=250) product_link = models.CharField(max_length=250) shipping = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, blank=True, null=True) def get_absolute_url(self): return "/products/{slug}/".format(slug=self.slug) def __str__(self): return self.products objects = models.Manager def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=WhiskyContent) Pipeline into database: import psycopg2 import sys import logging class Frankbrauer360Pipeline(object): def __init__(self): self.create_connection() def create_connection(self,): hostname = 'localhost' username = 'postgres' password = 'Whisky#123!' database = 'Items' x = 1 try: if (x == 1): self.connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database) except psycopg2.DatabaseError as e: logging.error(e) sys.exit() finally: logging.info('Connection opened successfully.') def process_item(self, item, spider): cursor = self.connection.cursor() cursor.execute(''' insert into homepage_whiskycontent(products, price, picture, site, product_link, shipping, date) values (%s, %s, %s, %s, %s, %s, %s); ''', [ item['products'], item['price'], item['picture'], item['site'], item['product_link'], item['shipping'], item['date'], # item["slug"], ]) self.connection.commit() return item def close_spider(self, spider): self.connection.close() … -
Average duplicates from specific columns in QuerySet in Django
I have a Django Model I am using that looks like this: class FinancialAid(models.Model): RECEIVED_EVERY = (("J", "Jours"), ("S", "Semaines"), ("M", "Mois")) ID = models.AutoField(primary_key=True) Name = models.CharField(max_length=100, null=True, blank=True) Value = models.IntegerField(null=True, blank=True, default=-1) ReceivedEvery = models.CharField(max_length=15, null=True, blank=True, choices=RECEIVED_EVERY) Exchange = models.ForeignKey('Exchange', on_delete=models.CASCADE) I am able to access the information I want but I have an issue in that I often have duplicates within my QuerySet over the Name and ReceivedEvery columns but not always on the Value and never on the Exchange. Say I have the following QuerySet expanded out: financial_aid_qs = [ (ID=1, Name="Aid1", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=1)), (ID=2, Name="Aid2", Value=200, ReceivedEvery="S", Exchange=Exchange.objects.get(pk=2)), (ID=3, Name="Aid1", Value=150, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=3)), (ID=4, Name="Aid3", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=4)) ] As you can see, I have the same Name and ReceivedEvery for indexes 1 and 3. What I would like to do is get a QuerySet (or ValuesQuerySet although I seem to recall this was removed) that will contain all the different FinancialAid objects in terms of Name and average out the Value of FinancialAid objects that have the same Name. Ideally it would take into account the fact that ReceivedEvery can differ even though the Name is the same (This is all … -
Making generated emails 'outlook friendly'
I'm using Summernote as a WYSIWYG editor for users to create emails and send them within a django application. As it stands it works perfectly well in most clients which handle HTML in any normal way, however when the mail is sent to outlook it goes awry. Essentially Summernote is using style="float: x width: x" which outlook is simply ignoring, then rendering the image that should be floated right or left wherever it has been placed and at full size. Does anyone know of a package that can parse the generated summernote HTML and make it Outlook friendly before I go ahead and start writing up a whole lot of string replacements in the generated HTML? -
How to import the data from a data dump (SqLite3) into django?
I have a data dump file(.sql) containing certain data, I would like to import it to my database(currently Sqlite3 but thinking about changing to MySQL) in order to use it in my test website. Also, I need to know if it's possible to add the models too automatically, I presume it needs to be added manually, but any how, if there is any way to solve it, please suggest it. -
Search Marker Leaflet Map
I am working on an application with Django. There in this application, I am first using Django to create a database with points and extract a JSON file (It is called "markers.json"). Then, using this JSON file, I am creating markers on a map with Leaflet. When I finished entering all the points to the database they will be around 5000 thousand. So, I decided that it is a good idea to be able to search this markers with an input tag and a search button. I enter the "site_name" as input and when I click the "search" button the related marker should popup. However, always the same marker pops up and I don't know where I am doing wrong. Could you please help me on that? HTML PART <input type="text" id="mast_find" name="mastName" placeholder="Search or masts..."> <button type="submit" id="mast_button">Search</button> JAVASCRIPT PART var streets = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: ['a', 'b', 'c'] }), esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' }), topo = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: 'Map data: &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: … -
Annotating average and count of latest instances created by one author
So, I've got that piece of code: def generate_annotated_applications(queryset): return queryset.annotate( avg_rating=Avg( 'application_ratings__rate', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ), ).annotate( num_ratings=Count( 'application_ratings', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ) In general it works well, but the problem is that avg_rating is counted from every existing application_ratings. What I need to achieve is to count average taking only latest ratings with unique author. There are many instances of application_rating with different rate and author. Same thing is with num_ratings - I need to count number of latest ratings with unique author field.