Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Proejct deployed into DigitialOcean getting slower after adding domain name and DO Space
After adding a domain name to my (droplet) django project, its loading too slowly. Even sometimes it takes for 1 min to load a page of my website with small CSS and js files ( without any images sample page). But is the beginning when check Nginx with droplet IP, without domain and DO space (static files were inside my Django project dir) my site was being loaded very fastly. what's problem, and how can I increase the loading speed -
how can i change base_dir from pathlib to os
I am taking a course of Django where the instructor did all the file_DIRS from os . but my django showing me this one from pathlib import Path Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(file).resolve(strict=True).parent.parent I want to change the dir . it will be easy for me to follow the instructions . thanks -
Django Admin send email upon new entry or update on models
Would like to ask for help on how to send an email. So I have basic tracking application for a logistics app. When I add a new entry(name,email,phone number,tracking number,cargo received date..) in my database in django admin or update the database (update cargo received date..),I want it to send an email to the client's email address for an update. My models.py is class Tracking2(models.Model): MODE_CHOICES = ( ('Air Freight', 'Air Freight'), ('Sea Freight', 'Sea Freight'), ) name = models.CharField(max_length=255) contact_number = models.CharField(max_length=255) email_address = models.CharField(max_length=150, default='Email Address') mode = models.CharField(max_length=255, choices=MODE_CHOICES) tracking_number = models.CharField(max_length=255) cargo_received_date = models.DateField(null=True, blank=True) cargo_received_details = models.CharField(null=True, max_length=255,blank=True) out_for_delivery_date = models.DateField(null=True, blank=True) out_for_delivery_details = models.CharField(null=True, max_length=255,blank=True) arrived_at_region_date = models.DateField(null=True, blank=True) arrived_at_region_details = models.CharField(null=True, max_length=255,blank=True) departed_shipping_facility_date = models.DateField(null=True, blank=True) departed_shipping_facility_details = models.CharField(null=True, max_length=255,blank=True) cargo_delivered_date = models.DateField(null=True, blank=True) cargo_delivered_details = models.CharField(null=True, max_length=255,blank=True) class Meta: verbose_name_plural = "Italy" def save(self, *args, **kwargs): return super(Tracking2, self).save(*args, **kwargs) My admin.py is from daterange_filter.filter import DateRangeFilter from django.contrib import admin from .models import Tracking2 from import_export import resources from import_export.admin import ImportExportModelAdmin from rangefilter.filter import DateRangeFilter, DateTimeRangeFilter class Tracking2Resources(resources.ModelResource): class Meta: model = Tracking2 class Tracking2Admin(ImportExportModelAdmin): resource_class= Tracking2Resources search_fields = ('name', 'contact_number', 'tracking_number','out_for_delivery_details' ) list_display = ("name","contact_number","mode","tracking_number", "cargo_received_date","cargo_received_details", "out_for_delivery_date","out_for_delivery_details","arrived_at_region_date", "arrived_at_region_details","departed_shipping_facility_date", "departed_shipping_facility_details","cargo_delivered_date", … -
Storing routes in a file and importing into App.js
I'm trying to store routes in a file to make them more modular. I am using BrowserRouter, Switch, and Route. Right now, the components are not showing up on the page where the links are. App.js: import React from 'react'; import MembershipRouter from "./members/MembersRouter"; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; function App() { return ( <div className="App"> <Router> <Switch> <Route path="/memberships/redesign" component={ MembershipRouter }/> </Switch> </Router> </div> ); } export default App; MembersRouter.js: import React from 'react'; import MemberForm from './MemberForm'; import MembersTable from './MembersTable'; import MembershipForm from './MembershipForm'; import MembershipTable from './MembershipTable'; import LockerRentalForm from './LockerRentalForm'; import LockerRentalTable from './LockerRentalTable'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; export default function MembersRouter() { return ( <Router> <Route path="/member_form" component={ MemberForm } /> <Route path="/members_table" component={ MembersTable} /> <Route path="/membership_form" component={ MembershipForm } /> <Route path="/membership_table" component={ MembershipTable } /> <Route path="/locker_rental_form" component={ LockerRentalForm } /> <Route path="/locker_rental_table" component={ LockerRentalTable } /> </Router> ); } -
how to update rendered variable in django templates?
I'm trying to render a variable that will update multiple time in the code, but it just renders the last one to the template, for example on my : views.py: def test(request): message = 'first massage' #do something message = 'second massage' return render(request,'test.html',{'message':message}) test.html : <h1> {{message}} </h1> It's only display second message but I want to first display first message then after it changed display second message. Any help ? -
Django - Populating html table with data from Select2MultipleWidget
I have a form where one can edit a service and add or remove several articles attributed to a service. it looks like this: The dropdown left to the label "Zugeordnete Artikel:" is a Select2MultipleWidget I used in order to offer an easy assignment method that has a search function. I want to populate the table underneath that widget with the information stored in the db. The table is populated after the service is saved and the page is refreshed. Can i update the table in realtime with the information of the assigned articles? If yes, what's the best way to do it? -
Get full request URL from inside APIView in Django REST Framework
Is there a method, or an attribute in request object that I can access to return me the URL exactly as the client requested? With the query params included? I've checked request.build_absolute_uri after looking at this question but it just returns the URL without the query params. I need the URL because my API response returns the URL for the "next page" of results. I could build it from the query_params attributes, but this view takes a lot of query params and some exclude others, so having access to the request url would save me a lot of pain. -
How to use Spotify API's Authorization flow with Django, React and Redux
I am currently working on an app that has a Django backend and React/Redux front end. I am trying to achieve the Authorization flow, but I am unsure how to do it. I've read a bunch of articles and I've tried everything they said, but I am not grasping the concepts. I have my front end making a call to the authorize url, but I get a CORS error, so then I read I am supposed to actually just redirect the user there, but how do I do that AND pass over all the credentials that I send in my axios request on the front end, just include them in the URL? Then I read that I should not even be doing this from the front end, but from Django, but how do I even do that? I am using Knox for authentication, but here's the thing I don't want to authenticate users with spotify, I just want to my app to have access to their playlists. I am really lost, and need help. Here is some code (most of it is from the tutorial) import qs from 'qs'; const scopesArr = [ 'user-read-currently-playing', 'user-modify-playback-state', 'user-read-playback-state', 'streaming', 'app-remote-control', 'playlist-read-collaborative', 'playlist-modify-public', … -
Django - extract image from pdf during saving process of an object
I am working on private portfolio, where I have model called 'Certification'. class Certification(models.Model): id = models.CharField(max_length=50, primary_key=True) title = models.CharField(max_length=200) organiser = models.CharField(max_length=200) description = models.TextField() date_completed = models.DateField() pdf_file = models.FileField(upload_to='static/media', blank=True) cover_image = models.ImageField(upload_to='static/images', blank=True) I want to extract 'cover_image' from first page of the 'pdf_file' during creation of an object Certificate, the image will be used as a cover image of a tile in my front-end. I tried to use pdf2image library, but without a success - the function I wrote cannot handle file which is not saved yet. What script should I use to achieve this goal and where should it be placed? -
Django: unable to locate static files folder
I am trying to setup an AS2 server using the python package django-pyas2 (https://github.com/abhishek-ram/django-pyas2) Everything has been working fine while I was using the runserver command, but when trying to host my web app using IIS(10), I've noticed that none of my static files get loaded when loading a page. I've been on countless forums/documentations and I know that I need to setup my IIS to serve these files, but I haven't been able to answer a rather stupid question: Where is the /static/ folder of django-pyas2 located ??? There is no such folder on the github page. When using the runserver command, django somehow manages to find all the static files (.css, .js, .png) from the static folder, but I am still totally clueless to where that folder is actually stored. I've been searching in these locations to no avail: (I'm using a virtual env on Windows Server 2016) my own project my venv's site-packages\django-pyas2 folder in C:\Python37\Lib\site-packages\django-pyas2 in C:\User\AppData\Roaming\Python\Python37\Lib\site-packages\django-pyas2 I've also tried to use the command collectstatic, but I first need to know where the actual /static/ folder is stored. I've double-checked, and the files are apparently stored locally and not on a CDN. This is driving me … -
Upgrading Django to 2.2 LTS - object is not subscriptable
I am trying to update a Django project from 1.11 LTS to 2.2 LTS. Other packages I use: django-cache-machine 1.1.0 django-bmemcached (updated from 0.2.3 to 0.3.0) python-binary-memcached (updated from 0.26.0 to 0.29.0) Consider the line below, which used to work before the updates I listed above. CustomUser.cache_objects.get(user=request.user) I now get an error: Request Method: GET Django Version: 2.2 Exception Type: TypeError Exception Value: 'dict_keys' object is not subscriptable Exception Location: /app/.heroku/python/lib/python3.8/site-packages/bmemcached/protocol.py in get_multi, line 497 Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.5 This only happens on my Heroku instance, if I run it locally it works as expected. -
Python Django - How to get emails from models file field
I am working in a private project and for me as a beginner in Django, I'm having a lot of misconceptions when it comes to models and forms. The idea of the project is to create Group(containing a name and csv file with emails), create Template(containing a name and the content plain text or html), and then create a Campaign containing Group and Template then to send email to those groups with selected template. Am I able to do this with models and forms,or this is not the right way of solving the problem. from django.db import models from ckeditor.fields import RichTextField class CreateGroup(models.Model): name = models.CharField(max_length=50, null=False, blank=False) email = models.FileField(upload_to='emails/%Y/%m/%d', blank=True, null=True) def __str__(self): return self.name class CreateTemplate(models.Model): name = models.CharField(max_length=30,null=False, blank=False) content = RichTextField(blank=True, null=True) def __str__(self): return self.name class CreateCampaign(models.Model): name = models.CharField(max_length=30, null=False, blank=False) template = models.ForeignKey(CreateTemplate, default="", on_delete=models.CASCADE) recipients_group = models.ForeignKey(CreateGroup, default="", on_delete=models.CASCADE) def __str__(self): return self.name class ComposeEmail(models.Model): subject = models.CharField(max_length=70, blank=True, null=False) to = models.CharField(max_length=200, error_messages=False, blank=True, null=False) body = RichTextField(blank=True, null=True) addtoemail = models.FileField(upload_to='Singlemail/%Y/%m/%d', blank=True, null=True) class MassMail(models.Model): subject = models.CharField(max_length=70, blank=False, null=False) to = models.OneToOneField(CreateCampaign, default="", on_delete=models.CASCADE) addtomass = models.FileField(upload_to='Massmail/%Y/%m/%d', blank=True, null=True) date = models.DateTimeField(auto_now=True) def __str__(self): return self.subject -
Query works fine in psql , but Django cursor.execute() gives "cannot extract elements from a scalar"
I've got a large query which I need to run manually on a postgres DB from within Django. When I run the query manually in psql I have no problems, but when I run it using cursor.execute() in Python I get an error. I reduced the query to the following: select id from mytable, jsonb_array_elements(details) as detail_elements; As you can see the second part takes some info from a jsonb field with which I do more in the larger query. This simple query runs great in psql (just showing a list of ids), so I then tried from within Django: from django.db import connection with connection.cursor() as cursor: cursor.execute("select id from mytable, jsonb_array_elements(details) as detail_elements;") rows = cursor.fetchall() but I get this error: psycopg2.errors.InvalidParameterValue: cannot extract elements from a scalar Does anybody know what magic Django tries to do which makes it different from running this directly in psql? All tips are welcome! -
Override related manager to add additional filter
class Category(Model): name = CharField(max_length=55, unique=True) parent = ForeignKey('self', on_delete=CASCADE, null=True, related_name='subcategories', blank=True) visible = BooleanField(default=True, blank=True) How can I override the behavior of c.subcategories, so that only visible categories are fetched. For example, c=Category.objects.get(id=1). c.my_related_manager.all() is equivalent to c.subcategories.filter(visible=True) -
Element that added with jquery does not work properly
I have a list of exercises At the end of jQuery i add new exercise to exercise-checkbox-list as you can see and user can see it in list, it works but <a elements does not work it, it works when i refresh page because list items loaded with django template language which is code that i write above. How can i solve that problem without reload page. when <a element with name=exercise clicked then that exercise deleted from list. when user adds exercise I handle with jquery and ajax with that code: jQuery.ajax({ url: '/ajax/add_exercise/', dataType: 'json', data: { 'exercise_type': 0, 'exercise_id': exercise_id, 'duration': duration, 'daily_person_id': daily_person_id, 'daily_exercise_program_id': daily_exercise_program_id, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, type: 'POST', success: function(data) { user_exercise_id = data.user_exercise_id; console.log(data.how_many_calorie_burn); how_many_calorie_burn = data.how_many_calorie_burn; console.log(how_many_calorie_burn); jQuery('#daily_burned_calories').text(data.daily_burned_calories); } }); $("#exercise-checkbox-list").append('<li> <label> <span><strong>' + exercise_name + "| " + duration + " min" + "| " + how_many_calorie_burn + " cal burned" + '<strong></span>\n <a href=\'#\'\n' + ' class="fa fa-pencil"></a>\n' + '<a href=\'#\' val="exercise_id,user_exercise_id" class="fa fa-times"></a> </label> </li>'); <li> <label> {% if user_exercise.exercise.exercise_type == 0 %} <span><strong>{{ user_exercise.exercise.name }} | {{ user_exercise.duration }} min | {{ user_exercise.how_many_calorie_burn }} cal burned</strong></span> <a href='{{ user_exercise.exercise.video_link }}' class="fa fa-pencil"></a> <a href='#' class="fa fa-times" … -
Django how many fields can i put unique in a model?
I can put two fields unique True? class Student(models.Model): name = models.CharField(max_length=25, unique=True) last_name = models.CharField(max_length=25, unique=True) age = models.BigIntegerField() -
django email list field
I want to create field that hods list of emails. My model is like this : class Alerts(models.Model): emails = MultiEmailField() events = models.OneToOneField(Event, on_delete=models.CASCADE) All good, but when this models is saved in DB it is like this { "id": 11, "emails": "['ht@ht.com, bb@bb.com']", "events": 13 } The list in 'emails' key is represented as a string "['ht@ht.com, bb@bb.com']" , not as a list ['ht@ht.com, bb@bb.com']. I tried different method, parsers and approaches, but without success. Is there a way to save list in DB or not? If it is the second is there a way to receive back a list as a response, not a string, that is fine too. ( DB is MYSQL) -
in a for loop get a list and sum values up together in one single list and append that to a dictionary
Excuse the super long viewset. I just wanted to give you guys the entire thing so it would be better to understand the flow. first i filter the queryset into different querysets for every machine then i annotate so i can get the jobs grouped per hour. for every qs i do another loop so i can calculate the total duration of every job for a given hour. I get a list of 24 values for every job in each queryset that has been grouped by machine name. I am stuck at the part where i need to get the sum of all those lists inside a loop before appending it to the dictionary. after that I also need to empty that list so i can reuse it for the next machine queryset. Right now I am not doing that, and i just get the last list because the list is being emptied everytime I loop: minutes_as_array = [0] * 24 for i in range(len(duration_per_hour_in_which_job_occured) - 1): # get time difference between 'next' hour spent and 'current' minutes_in_hour_spent = duration_per_hour_in_which_job_occured[i + 1] - duration_per_hour_in_which_job_occured[i] "minutes spent: {}, in hour: {}".format(minutes_in_hour_spent, duration_per_hour_in_which_job_occured[i]) minutes_as_array[duration_per_hour_in_which_job_occured[i].hour] = minutes_in_hour_spent.seconds / 60 print("===") print(minutes_as_array) total_dur.append(minutes_as_array) machine_list[name] … -
How to add extra column mysql database table in Django?
i am new in Django . I am using Mysql database for my django project.I have created model class in models.py. in my models.py from django.db import models class AuthModel(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) username = models.CharField(max_length=255) password = models.CharField(max_length=255) i have Migrated this Fields into my Mysql Database using following commands Python manage.py makemigrations Python manage.py migrate which is making table in my database as shown in below now, i want to add one more column in table which is "user_type". i can add "user_type" column manually from database but its not inserting "user_type" value into table. because i have not include "user_type" column in my 'AuthModel'. if i include user_type into 'AuthModel' and run migration commands ,however its not working . i want to add user_type column in to my table. how to do that? -
How to Serialize content from database saved as PickledObjectField?
As per below code, i have a Pickledobjectfield in my model. class History(models.Model): title = models.CharField(max_length=10, null=True) content = PickledObjectField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Why I use it? I needed to handle a dictionary, that is created in views.py The problem is when getting the value from database to api, History.content is like below, "content": "gAJ9cQAoWAMAAABkaWFxAVgGAAAAOTgwLjcwcQJYAwAAAHZlbHEDWAQAAAA3Ljk0cQRYBAAAAGZsb3dxBVgEAAAANjAwMHEGWAIAAABobHEHWAUAAAAwLjYwMHEIWAIAAABybnEJWAYAAAA1MjM5NjRxClgCAAAAZmFxC1gEAAAAMC43NnEMWAIAAABmZnENWAYAAAAwLjAxNTVxDlgCAAAAdnBxD1gFAAAAMzcuOTBxEFgFAAAAd2lkdGhxEVgAAAAAcRJYAgAAAGh0cRNoElgFAAAAZGlhX3VxFFgCAAAAbW1xFVgFAAAAdmVsX3VxFlgFAAAAbS9zZWNxF1gGAAAAZmxvd191cRhYAwAAAExQU3EZWAQAAABobF91cRpYBAAAAFBhL21xG1gEAAAAZmFfdXEcWA0AAABtPHN1cD4yPC9zdXA+cR1YBAAAAHZwX3VxHlgCAAAAUGFxH3Uu" } I am new in Django rest framework, please guide me. -
ReferenceError: $ is not defined while modalform popup angularjs
while pop bootstrap modal form from controller I get error.Though It worked for previous project var mymodule = angular.module('MyApp',[]).config(function($interpolateProvider) { mymodule.controller('categoryController',function($scope,$http,$log,$location) { $scope.overed = function() { $("#myModel").modal("show"); } }) -
How to replace the lambda function with def function?
students2 = [ {'name' : "harshit","score":90,'age':24}, {'name' : "mohit","score":70,'age':19}, {'name' : "rohit","score":60,'age':23} ] print(max(students2, key = lambda i: i.get("score"))) Output: {'name': 'harshit', 'score': 90, 'age': 24} How can I replace the lambda function with def function? -
How to restore postgreSQL from dump file to AWS?
I have PostgreSQL dump file in my local environment, and I want to restore it on AWS server where Django app was deployed. I think I should upload the dump file to AWS server but I don't know where it should be uploaded to and how to restore it. -
Show Fields of Foreign Key Records in Django Admin
I have two Django Models: Category & SubCategory. @python_2_unicode_compatible class Category(models.Model): category = models.CharField(verbose_name=_("Category"),max_length=250, blank=True,unique=True, null=True) class_id = models.ForeignKey(classes, null=True, blank=True, on_delete=models.CASCADE) boardCode= models.ForeignKey(boards,null=True, blank=True, on_delete=models.CASCADE) subjectDescr = models.ForeignKey(subjects,null=True, blank=True, on_delete=models.CASCADE) objects = CategoryManager() class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def __str__(self): return "%s - %s" % ( self.class_id.classVal, self.subjectDescr.subjectDescr ) @python_2_unicode_compatible class SubCategory(models.Model): sub_category = models.CharField( verbose_name=_("Sub-Category"), max_length=250, blank=True, null=True) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category"), on_delete=models.CASCADE) objects = CategoryManager() class Meta: verbose_name = _("Sub-Category") verbose_name_plural = _("Sub-Categories") def __str__(self): return self.sub_category + " (" + self.category.category + ")" I want to display , Sub_Category ( Category Class_ID) but I can only display Sub_Category (Category). Is it possible to display in the drop Down while Saving Another Model where Both Category & SubCategory are foreign keyed. -
Why is type of django IntegerField string
I have an IntegerField in my model and later on, I'm trying to perform an Increment on the field something like self.claims_database.claims_count += 1 but I'm getting the error *** TypeError: can only concatenate str (not "int") to str which means the IntegerField claims_count is being interpreted as a String. Why is this the case? UPDATE: class WebsitesClaimsDatabase(models.Model): url = models.URLField(help_text="URL to scrape claims from.") claims_count = models.IntegerField(default=0) Creating the self.claims_database self.claims_database, _ = WebsitesClaimsDatabase.objects.get_or_create(url=EUVSDISINFO_URL) Method def get_all_posts(self): claims_count = self.get_claims_count() self.claims_database.claims_count += 1 ....