Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form on Base.html
I have a navbar on my project in base.html and I want to add a form to the navbar. When you click on 'add' a window prompts and you should able to see and fill the form and then submit it. But I think I cannot connect my view with my templates, I am also unsure how to make a url path because it should be everywhere. I created a view under the project/views, and my template is under the project/templates. Here is my code which is relative easy but as I said I need to connect my form and template. Thank you very much. view.py from django.views import generic from account.models import Distribution from account.forms import DistributionForm class Distribution(generic.CreateView): template_name="base.html" model=Distribution fields=['distribution','semester'] base.html <!DOCTYPE html> {% load static %} {% load crispy_forms_tags %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <meta charset="utf-8"> <title></title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top"> <a class="navbar-brand" href="{% url 'distribution:home'%}">Ana Sayfa</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'account:register' %}">Kayıt … -
Alter Django Form
How can i adjust my code so that a user cannot choose another user for a new post. I want to make it so that the logged in user is automatically added as the author. I have tried setting the fields part in the views.py to just the content field, however it doesn't work models.py class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=140) views.py class CreatePostView(CreateView): model = post fields = '__all__' template_name = 'users/create.html' Myform.html <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> -
Django Web App: problem with “OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly”
Application My application based on kubernetes cluster with backend (django), frontend and other related pods. Also it has some services and one of them is postgresql database. I have two instances of my application (dev and prod - they exist in different namespaces) and problem that will be discussed bellow exists in both. About problem Sometimes I have troubles on my cite when performing operations related to accessing database (trying to login for example). In kubernetes backend pod logs I see error messages ended with: ... django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. This usually happens within 10-30 minutes and then goes away by itself. I have no idea how to reproduce or temporary solve this problem so I just can watch for it and some of my observation I will try to describe in this post. Django database configurations DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_DBNAME'), 'USER': os.environ.get('POSTGRES_NAME'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PASSWORD': os.environ.get('POSTGRES_PASS'), 'PORT': os.environ.get('POSTGRES_PORT'), 'CONN_MAX_AGE': None, } Researching the problem In moments when problem exists I found out the following: I can access server with database via ssh. Also I can exec -it docker container … -
Pycharm cannot run debug Django Web App ,What is something wrong?
I cannot run debug for the Django project in Pycharm I got stuck on how to debug Django Python Project in Pycharm. I don't know how I configure something in Pycharm incorrectly despite no problem in the other python project. Is there anything for additional setting in Pycharm Or further code in Django project file such as settings.py In figure below, I do the following step. Set Breakpoint in here 2.Click Debug in view.py debug stop at init.py raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE)) Debugger never reaches my breakpoint at all. click to see picture debuger in pycharm Thank you -
getting the COUNT of unique values on django queryset with for loop
newbie here on django and django-rest-framework. May I ask if it is possible to get the COUNT of the unique values on a for loop? I have encountered this use case where I need to get the the COUNT of all unique values on a for loop querysets. The implementation was to loop within the querysets and put on the list all the unique objects and return the len() of it. The problem with this implementation was it causes multiple queries on the DB base on django-debug-toolbar. Please see code below for reference. Is there another way to implement this? Thank you in advance. activity_list = [] classes = Class.objects.all() for class in classes: student_activities = class.studentactivity_set.all() for activity in student_activities: if activity not in activity_list: activity_list.append(activity) return len(activity_list) -
Django with vue.js frontend - Static Files Path
I am attempting to serve a django app with a vue frontend and need some help configuring the static files. Django serves the built index.html from vue, however it can not find the static files (scripts/css) that are autoinjected from the build process due to the path being "absolute". I have modified the vue.config.js to not autoinject the scripts (since they will need {% static %} during the build, and the template index.html to add them in appropriately. My directory structure is as follows: - Root - app - migrations - templates - app (outputDir) - index.html (Built from vue) - base.html - templateFolder1 - templateFolder2 - various .py files - assets (assetsDir) - css - static files - js - static files - frontend - public - index.html (Template for build for vue) - src - assets - components - App.vue - main.js The build is run from the frontend directory, with --no-clean to not delete my django templates folder on build. Here is my workaround for adding {% static %} tags to the built index.html. I realize I am breaking the convention vue has that assetsDir is a subdirectory of outputDir, and I am not opposed to adding … -
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?