Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i call a an API from POST request in Django?
I am using Djangorestframework. Ny views.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 Serialziers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version','attributes',) my models.py: 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 This is what my api page looks: When i click on POST, it should call a different Post api with parameter i have entered here. How do i do that? -
Multiple Authentication classes Django doesn't try all the classes, fails at first
'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'michan_api.utils.validators.ExampleAuthentication' ), So I have this configured in my REST_FRAMEWORK setting in DRF. But it doesn't try all the classes.If the first one throws an exception it fails. for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise This piece of code is responsible for this. (https://github.com/encode/django-rest-framework/blob/master/rest_framework/request.py#L373) How do I make it try all the classes? -
how to securely publish my django website (security of backend code from being read by visitors)
I have written the backend code of a website by Django. I must publish this project for my other classmates to see the website. I want to rent a windows based host and put my code there and then give the link of my domain to them. But I really need to be sure that nobody even my classmates or others can access to download or read my backend codes. I want they have just access to work with the web site (for example they just be able to see home page, login page, and be able to register to my website and...). This is really important for me. How can I protect my backend code (or even just the most important part of that) from reading? I have heard that there is a solution which needs I put my backend codes in a folder and set a password for it. Is it correct? If so, I don't know how to do that. This is the first time I am publishing a website. Any help would be greatly appreciated. -
Write serializer for a model having multiple foreign key in django rest framework
I am building an api for CRUD operations on a user table which has association with country and state tables as given model definitions: class Country(models.Model): """ Model for Country""" country_abbreviation = models.CharField(max_length=80) country_name = models.CharField(max_length=80) is_active = models.SmallIntegerField() def __str__(self): return self.country_name class State(models.Model): """ model for saving state""" state_name = models.CharField(max_length=32) state_abbreviation = models.CharField(max_length=8) country = models.ForeignKey(Country, related_name='states', on_delete=models.CASCADE) is_active = models.SmallIntegerField(default=1, blank=True) def __str__(self): return self.state_name class Meta: """ meta class""" ordering = ('state_name', ) class User(models.Model): """ model for saving user information """ first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) country = models.ForeignKey(Country, related_name='user_country', on_delete=models.CASCADE) state = models.ForeignKey(State, related_name='user_state', on_delete=models.CASCADE) address = models.CharField(max_length=150) def __str__(self): return '%d: %s %s' % (self.id, self.first_name, self.last_name) class Meta: """ meta class """ ordering = ('first_name', ) I am writing serializers in a way that while I am getting records from user table, for every row in the table there must be available all the country and state info associated with that particular row instead of just their ids respectively: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'country', 'state', 'address'] Expected response : { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "first_name": … -
Create alias for filtering ChoiceField in django-filters
I have following filterset for some model: class MyModel(models.Model): STATUS_ACTIVE = 0 STATUS_DONE = 1 STATUSES = ( (STATUS_ACTIVE, 'Active'), (STATUS_DONE, 'Done'), ) status = models.IntegerField(choices=STATUSES, default=STATUS_ACTIVE) class ModelFilter(FilterSet): status = ChoiceFilter(choices=MyModel.STATUSES) class Meta: model = MyModel fields = ( 'status', ) When I make request to some API, i should use status as number - /app/model?status=0. How to make alias for it, so that i can use /app/model?status=running instead of number, without changing model? -
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