Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not connected to the database?
I deployed an app to Heroku and it was successful,however, the data from the SQLite3 database was not loaded online. So I tried to dump data locally and then load it but when I checked my project locally. The database is not connected to the project and because of that, it's not showing any data even locally. It gives me no error but now how can I now reconnect my sqlite3 database to my project so I can dump it and then load to Heroku. Here are my settings for the database which seems correct DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
How can i call an different API from Post request in Django?
I am new to Django and django restframework. I am using Django Rest framework to create API. What i am trying to do is call a diffrent api when post request is made.Ex: I have name, attribute, version in my serializer class. So when post is called, it should call the api on swagger with parameter name,attribute and version. I can do that by doing something like that in my create function of viewset. But how do i edit that. response = requests.post( f"{AGENT_URL}/schemas", json=request_body, return HttpResponse() my view.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """Handles creating, reading schema""" serializer_class = serializers.SchemaSerializer queryset = models.Schema.objects.all() My model.py file: class Schema(models.Model): """Database model for Schema """ #id = models.IntegerField() idid = models.TextField() name= models.TextField() version = models.TextField() attributes = models.TextField() num = models.IntegerField( null=True, blank=True) def __str__(self): return self.idid my serializers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version','attributes',) -
Downloading new language texts from server in i18n system in React App
I want to create a React App with localization and supporting several languages that switches between languages via /?lng=en and things like this. I use i18n and this tutorial: https://react.i18next.com/legacy-v9/step-by-step-guide But this system works at client side and browser must download entire languages inside JS file. I don't want this. I need speedy and light App and need to download new languages texts from the server, Each time user selects new language. I need to render new UI each time user selects new language. What I have to do? My backend is Python(Django) -
How do I remove all labels in my crispy form layout?
so I've seen some similar questions regarding the labels of crispy forms, such as: self.helper.form_show_labels = False I put this in the class in my forms.py. However I keep on getting this error message: self.helper.form_show_labels = False NameError: name 'self' is not defined What have I done wrong? This is my forms.py BTW. from crispy_forms.helper import FormHelper class MyInputForm(forms.ModelForm): self.helper.form_show_labels = False -
Module is not imported after sys.path.append()
I am trying to deploy my django application. Like many others I faced the problem of "missing" django, no module named django, though it exists. I had to install Django of version 2, not the newest and it was installed into '/home/ivan/.local/lib/python3.5/site-packages/'. I have my apache configured and wsgi module looks like this: """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os import sys sys.path.append('/home/ivan/.local/lib/python3.5/site-packages/') print(sys.path) # import /home/ivan/.local/lib/python3.5/site-packages/django from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() When I type python3 in terminal and do this: >>> import django >>> django.__path__ ['/home/ivan/.local/lib/python3.5/site-packages/django'] So I got my path of django module and I append it, I also tried: sys.path.insert(0, '/home/ivan/.local/lib/python3.5/site-packages/django') and still I got 500 error with annoying: [Tue Apr 21 13:12:41.861348 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] Traceback (most recent call last): [Tue Apr 21 13:12:41.861379 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] File "/var/www/mysite/mysite/wsgi.py", line 15, in <module> [Tue Apr 21 13:12:41.861384 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] from django.core.wsgi import get_wsgi_application [Tue Apr 21 13:12:41.861397 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] ImportError: No module named 'django' Why wsgi cannot … -
How to check whether birthday is tomorrow in django?
I am checking whether students birthday is today or tomorrow in Python. In every loop it is getting birthday is not today even I changed DOB column to today date. How can I solve this? Below is the code. Views.py def Birthday_alert(): students= Students.objects.all() tmr= dt.date.today()+ dt.timedelta(days=1) tmr_bdays=[] to_bays=[] # verifying if date of today is working or not for m in students: if m.dob == dt.date.today(): print(m.name) # putting into dictionary for s in students: if s.dob == dt.date.today(): to_bays.append({ 'name': 's.name', 'course': 's.course.class_name', 'dob' : 's.dob', 'contact': 's.parent_contact', }) elif s.dob + dt.timedelta(days=1) == tmr: tmr_bdays.append({ 'name': 's.name', 'course': 's.course.class_name', 'dob' : 's.dob', 'contact': 's.parent_contact', }) else: for m in students: print("else:",m.name) return (tmr_bdays,to_bays) models.py class Students(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) dob = models.DateField(null=True, verbose_name='Date of Birth') age = models.IntegerField() grade_choice = ( ('G1', 'Grade-1'), ('G2', 'Grade-2'), ('G3', 'Grade-3'), ('G4', 'Grade-4'), ('G5', 'Grade-5'), ('G6', 'Grade-6'), ('G7', 'Grade-7'), ('G8', 'Grade-8'), ('G9', 'Grade-9'), ('G10', 'Grade-10'), ('G11', 'Grade-11'), ('G12', 'Grade-12'), ) gender_choice=( ('M', 'Male'), ('F', 'Female'), ('N', 'None'), ) blood_choice=( ('O', 'O'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('A+', 'A+'), ('AB', 'AB'), ) relation_choice=( ('Uncle', 'Uncle'), ('Aunty', 'Aunty'), ('Father', 'Father'), ('Mother', 'Mother'), ('Grandpa', 'Grandpa'), … -
Django ProgrammingError relation does not exist
I am having this problem ProgrammingError at /admin/telegram/phonenumber/ relation "telegram_phonenumber" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "telegram_phonenumber" I have already tried all solutions, nothing helped. So I pulled new models then did make migrations and migrate , and one of my models was giving column does not exist on table , I checked it in database , indeed it does not. So I did all the solutions from stackOverflow I could, and now I am in 'relations does not exist ' with just 0001initmigration.py it has my columns and tables but they are not being applied after python manage.py migrate -
Django custom UserCreationForm doesn't use CustomUserManager to create object
I wrote a SchoolMember model that inherits from AbstractUser and which adds the fields is_teacher and is_student. I also added SchoolMemberManager that implements a create function requiring few arguments. I then wrote a SchoolMemberCreationForm that is set to be the add_form variable in SchoolMemberAdmin. My problem is that when I create a SchoolMember from the admin interface, the create function of the SchoolMemberManager is never called because the SchoolMemberCreationForm inherits from UserCreationForm which calls save instead of create. That means that even if I can create the SchoolMember user, some settings are not correctly defined... I'm new to Django and I don't know where I should act... -
Why can't I run "manage.py runserver" when I install Django 2.2?
I can't install Django 2.2 with pip: (django-2.2-env) fadedbee@server:/www/myproject.example.com$ pip install django==2.2 DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support ERROR: Could not find a version that satisfies the requirement django==2.2 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, … -
Different views for different types of login in Django?
I am working on a project of online food ordering using Django. Problem is I want to create different views according to the user that is customer, restaurant management and delivery person. On the same platform they should view different pages as per the credentials. How to create different views according to the login credentials in Django? and How to check which category they belongs to like customer... what should I stores in models to check the category and assign view accordingly? -
models.objects.all(): Object of type SafeDeleteQueryset is not JSON serializable
I re-use code I already used in a previous project and don't know why it doesn't works now? I define my models Site with SafeDeleteModels and try to return list of sites with a middleware and get the error Object of type SafeDeleteQueryset is not JSON serializable -
Checkout form not getting saved
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. What is the problem? Can anyone please help me out? My views.py: @login_required() def checkout(request): address_form = UserAddressForm(request.POST or None) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action="{% url 'ajax_add_user_address' %}?redirect=checkout"> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> -
Convert JSON to SQLite having geoJSON content
Need help to prepare model for this dataset for SQLite using Python Django { "countryName": "India", "countryCode": "IND", "airportName": "Vishakhapatnam", "cityName": "Vishakhapatnam", "latitude": 17.722166666666666, "longitude": 83.22277777777778, "airportCode": "VOVZ", "geometry": { "type": "Point", "coordinates": [ 83.22277777777778, 17.722166666666666 ] } } -
No module named 'south'
The scenario is I am upgrading the Django projet. previous version:- Django 1.8 Python 2.7 Tastypie 0.13.0 Now the upgraded version is:- Django 2.2 Python 3.5.2 Tastypie 0.14.3 I have changed all syntax and converted it into python 3 using python convertor 2to3. Now while upgrading the structure of Django, it is raising an error. from south.db import db ImportError: No module named 'south' -
What is the best architecture to integrate AngularJS with Django?
I am trying to integrate Angular with Django. I have 2 approaches which one is the best way: Build a separate angular app and serve it's static files to django to render. In this way the routing and rendering everything will be handled by Angular. Or to build templates in django using Angular directly and use MVT architecture of Django only. Which is the correct way from architecture point of view? If not these two please suggest any good approach. -
How can I use argparse to parse a mutual exclusive argument group with defaults, so that only one of the arguments get a default value?
I have the below mutual exclusive argument group (group), where I want the default to be args.thread=10 and args.process=None, if neither --thread or --process is specified. Furhermore, if --thread or --process is specified, the other should be set to None. With my current code, the result is always args={ ..., 'thread': 10, 'process': 10, ... }. How can I fix my code to get the anticipated behavior? fmt = lambda prog: argparse.HelpFormatter(prog, width=140) p = argparse.ArgumentParser(description='Atlassian Watchdog: Search through all resources on Confluence, Bitbucket, or Jira looking for secrets.', formatter_class=fmt) group = p.add_argument_group('Concurrency') group = group.add_mutually_exclusive_group() group.add_argument('-t', '--thread', type=int, default=10, metavar='N', dest='thread', help='number of threads (default: %(default)s)') group.add_argument('-p', '--process', type=int, default=10, metavar='N', dest='process', help='number of subprocesses (default: %(default)s)') -
Django Subquery Average Employee Salary Per Company
I was looking for a better way using Subquery annotate and Avg but couldn't figure it out. This is what i have at the moment and it works giving me the average number of employees per company but it's ugly. companies = Company.objects.all() for company in companies: salary = [] for emp in company.comp_emp.all(): salary.append(emp.salary) print(sum(salary) / len(salary)) >>> 99054.4 >>> 96403.75 >>> 498351.375 I tried the following but no go, companies = Employee.objects.filter(company=OuterRef('pk')) employee_count = Company.objects.annotate(avg_emp_salary=Avg(Subquery(companies.values('salary')[:]))) >>> 46907.0 >>> 147288.0 >>> 43158.0 The values I get back are incorrect but I also can't make sense of where they're coming from either. This is just for my own learning purposes. Thanks in advance. -
How to disable use of website on mobile devices
Display an error page if website is accessed through mobile. I have already tried @media only screen (max-device-width : 768px) { html,body { display: none; } } and if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { getElementById('body').style.display = 'none'; } -
context_processors.py: files path?
I have a context_processors.py files in one of my app that I declared in my settings.py and it works. but, as context_processors.py files's data are common to all the project, I would like to declare it at the root of my project but files is not recognized... current project's architecture - myproject - my app - context_processors.py declared as follow in settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'registration/templates'), os.path.join(BASE_DIR,'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'parameters.context_processors.data_context_processor', <******************** 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] expected project's architecture - myproject - context_processors.py - my app How should I declare my context_processors.py files in settings.py? I try with os.path.join(BASE_DIR,'context_processors.data_context_processor') but it does not works... -
Django TemplateDoesNotExist (Root arrangement)
I had tried many times, and lastly I have solved this, but I can't understand why the root page need to be arrange like this? Learning_log = Project name ll_env = virtual env project01 = project name App01 = app name https://i.stack.imgur.com/zoSm1.png -
How to synchronously add files in a queue?
It's a bit hard to explain my problem but I try to, sorry in advance I have a Django server running which utilizes files in a directory /PROCESSING_DOCS/*.json An API call dynamically adds more files to this folder and now I need to maintain a queue which updates dynamically as the files added into that folder. How can I implement this? I don't have any idea? -
What happens in background when we pass the command python manage.py createsuperuser in Django?
I'm working on Django and I know to create a account to log in into admin page I have to create a superuser.And for that we have to pass the command python manage.py createsuperuser. But my question is when we pass this command what happens first and because of what in the background and after that what happens?? Which all methods and classes are called to create a superuser?? I know its a weird question but I wanted to know how this mechanism works.. Thanks in advance!! -
'AnonymousUser' object has no attribute '_meta' error when login in my user model form
I am getting 'AnonymousUser' object has no attribute '_meta' error when using get_user_model. Here are my form.py and view files be: this is forms.py file class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean_username(self): username = self.cleaned_data.get('username') try: user = User.objects.get(username=username) except User.DoesNotExist: raise forms.ValidationError('Are you sure you are registered? we can not find this user.') return username def clean_password(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') try: user = User.objects.get(username=username) except: user = None if user is not None and not user.check_password(password): raise forms.ValidationError('Invalid password') elif user is None: pass else: password this is views.py file def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) login(request, user) context = { 'form':form } return render(request, 'form.html', context) -
javascript is not loading in django template....or its not working in django
this is my html page where am loading js file <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/grid.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'main/post.css' %}"> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/post.js' %}"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> and this is my js file in static/js/post.js $(".sidebar-dropdown > a").click(function() { $(".sidebar-submenu").slideUp(200); if ( $(this) .parent() .hasClass("active") ) { $(".sidebar-dropdown").removeClass("active"); $(this) .parent() .removeClass("active"); } else { $(".sidebar-dropdown").removeClass("active"); $(this) .next(".sidebar-submenu") .slideDown(200); $(this) .parent() .addClass("active"); } }); $("#close-sidebar").click(function() { $(".page-wrapper").removeClass("toggled"); }); $("#show-sidebar").click(function() { $(".page-wrapper").addClass("toggled"); }); what should i do...am not facing any error but its not working ...is there any kind of inheriting problem ? -
how to solve MySQL server has gone with query
What is error in this code ? it is giving error "Failed inserting BLOB data into MySQL table 2006 (HY000): MySQL server has gone away" def insertBLOB(request): id =(1) name=("Eric") photo = ("/home/gauri/Pictures/w3schools.jpg") biodata = ("/home/gauri/Downloads/mnum.npy") try: connection = mysql.connector.connect(host="127.0.0.1", user="root", passwd="", port=3307, db="data2") cursor = connection.cursor() sql_insert_blob_query = "INSERT INTO python_employee(id, name, photo, biodata) VALUES (%s,%s,%s,%s)" with open(photo, 'rb') as file: binaryData = file.read() with open(biodata, 'rb') as file: binaryData1 = file.read() insert_blob_tuple = (id, name, binaryData, binaryData1,) result = cursor.execute(sql_insert_blob_query,insert_blob_tuple) connection.commit() print("Image and file inserted successfully as a BLOB into python_employee table",result) except mysql.connector.Error as error: print("Failed inserting BLOB data into MySQL table {}".format(error)) return HttpResponse("data")