Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Error for Python Django Rest Framework Code
I'm new to Django in Python. I have a python Django project called "corr_end" with an app within it called "send_values" I wrote a serializer, trying to make get/put/post/delete methods available and working through Postman testing. When I try the get method, it doesn't work in Postman and gives me an error. I appreciate any help on this. Thank you. URL: http://127.0.0.1:8000/values/dinos Error from terminal: Error from terminal: Internal Server Error: /values/dinos TypeError: __init__() takes 1 positional argument but 2 were given [19/Mar/2020 07:02:00] "GET /values/dinos HTTP/1.1" 500 63860 Traceback (most recent call last): File "[redacted]/anaconda3/envs/chipseq/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "[redacted]/anaconda3/envs/chipseq/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "[redacted]/anaconda3/envs/chipseq/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) I created a Python package 'api' under send_values directory with send_values_api.py containing the serializer. from rest_framework.exceptions import ValidationError from rest_framework.serializers import ModelSerializer from rest_framework.viewsets import ModelViewSet from ..models import Dinosaur class DinoSerializer(ModelSerializer): class Meta: model = Dinosaur fields = ['name', 'age', 'species'] def validate(self, userData): if not userData['name']: print('name is required') return ValidationError return userData def create(self, userData): newDinosaur = Dinosaur.objects.create(**userData) newDinosaur.save() return newDinosaur def update(self, existingDinosaur, userData): fields = ['name', 'age', 'species'] for i in … -
Django(WAS) and Nginx running in same fargate task container - what proportion of cpu and mem allocation is recommended?
I have django and nginx containers running in same fargate task containers with 4GB mem and cpu_limit of 2048(=2vCPU). I currently have django use 75% of cpu and 3GB mem, and ngxin with 25% of cpu and 0.7GB mem (0.3mem left for task itself). But I have made this proportional decision on hitch, as I could not find any materials/guidelines on this topic. Any ideas or recommendations? Thanks. -
No module named 'djangosite' when trying to use manage.py
I am using Django 3.0 and python 8 to run my Django server, it has only just stopped working and was working before. The full error is Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\base.py", line 320, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\base.py", line 294, in create_parser self.add_arguments(parser) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\core\management\commands\test.py", line 44, in add_arguments test_runner_class = get_runner(settings, self.test_runner) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\test\utils.py", line 301, in get_runner test_runner_class = test_runner_class or settings.TEST_RUNNER File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\me\Desktop\Projects\Work in progress\python\Django-server-thing\env\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Must nested within should
I want to use nested must block within should block in elastic search. { "query": { "bool": { "should": [], "must_not": [], "must": [ { "bool": { "should": [ { "wildcard": { "custom_search": { "boost": 1.0, "value": "e456799p*", "rewrite": "constant_score" } } } ] } }, { "match": { "is_deleted": { "query": false } } } ] } } } The above query working fine for me but when I use the below query it's not working for me. But when I add one more condition with it than it's not working for me. { "query": { "bool": { "should": [], "must_not": [], "must": [{ "bool": { "should": [{ "bool": { "must": [{ "nested": { "path": "messages", "query": { "bool": { "must": [], "must_not": [], "should": [{ "query_string": { "fields": ["messages.message", "messages.subject", "messages.email_search","custom_search"], "query": "e456799p*" } }] } } } }] } }, { "wildcard": { "custom_search": { "boost": 1.0, "value": "e456799p*", "rewrite": "constant_score" } } }] } }, { "match": { "is_deleted": { "query": false } } }] } } } So please give me the best solutions to how to use this below query. Thanks in advance. -
How to create an object of Foreign class key in python with filter?
I came across the problem of creating an object which doesn't exist. The models are as follows: class Contact(models.Model): name = models.CharField(max_length=255, blank=True) class Phone(models.Model): contact = models.ForeignKey(Contact,related_name='contact_number') number = models.CharField(max_length=255) Now, when I fire a query Contact.objects.filter(id=1031).values('contact_number') The Output is: <QuerySet [{'contact_number': None}]> Can there be any Query for creating the contact_number for the same when it is None? Because if I update Contact.objects.filter(id = 1031).update(contact_number = '9999999999') it gives me an error? Error: AttributeError: 'ManyToOneRel' object has no attribute 'get_db_prep_save' What can be the possible correct query for creating it? -
Insert data in table using csv in django
I am newbie in Django and wanted to know a basic thing: I have 2 model : class QuizCat(models.Model): cid = models.IntegerField() c_name = models.CharField(max_length=200) class Quiz(models.Model): Qid = models.IntegerField() cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE) name = models.CharField(max_length=200) I want to insert data in database using 1 csv file such that data gets inserted in both QuizCat model and Quiz model. also what should be the structure of csv file ? -
Android app and Postgresql Database communication
l have created my android application using flutter. This application is used for customer survey. The challenge l'm facing now is l want the application to communicate to my webserver at 127.0.0.1:8000/admin and postgresql database. All l want is after user presses submit button the information is posted to postgresql database and updated to webserver. -
wrong in django UserCreationsForm to register users information
when i change django UserCreationForm default fields it doesn't save user.but in default fields it working correctly after change fields, i have run makemigrations and migrate command but it didn't deffrent. email = forms.EmailField() class Meta(): model = User fields = ('username', 'email',)``` -
How to hide Django Admin from the public on Azure Kubernetes Service while keeping access via backdoor
I'm running a Django app on Azure Kubernetes Service and, for security purposes, would like to do the following: Completely block off the admin portal from the public (e.g. average Joe cannot reach mysite.com/admin) Allow access through some backdoor (e.g. a private network, jump host, etc.) One scenario would be to run two completely separate services: 1) the main API part of the app which is just the primary codebase with the admin disabled. This is served publicly. and 2) Private site behind some firewall which has admin enabled. Each could be on a different cluster with a different FQDN but all connect to the same datastore. This is definitely overkill - there must be a way to keep everything within the cluster. I'm think there might be a way to configure the Azure networking layer to block/allow traffic from specific IP ranges, and do it on a per-endpoint basis (e.g. mysite.com/admin versus mysite.com/api/1/test). Alternatively, maybe this is doable on a per-subdomain level (e.g. api.mysite.com/anything versus admin.mysite.com/anything). This might also be doable at the Kubernetes ingress layer but I can't figure out how. What is the easiest way to satisfy the 2 requirements? -
Calculate Average rating of 5 star rating
i want to get average of all ratings related to user class UserRating(models.Model): User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE) Rating = models.IntegerField( default=1, validators=[MaxValueValidator(5), MinValueValidator(1)] ) def __str__(self): return str(self.User_Name) class UserRatingViewSet(viewsets.ViewSet): def create(self,request): try: User_Name=request.data.get('User_Name') Rating=request.data.get('Rating') new=UserRating() new.User_Name=MyUser.objects.get(user_name=User_Name) new.Rating=Rating new.save() return Response({"Data":"Delivered"}) except Exception as error: return Response({"message":str(error),"success":False}) def list(self,request): ashu=UserRating.objects.all() print(ashu) a=[] for i in ashu: a.append({ "User_Name":i.User_Name.user_name, "Rating":i.Rating, }) return Response({"message":a}) -
I am doing ecommerce site using django framework. I want post as well as get in same view as I need to add brand and list from the same page
This is how my template looks like. Here I need to add brand and list them -
Django - Signup redirect to login page not working
My Signup view looks like below from django.contrib.auth.forms import UserCreationForm from django.views import generic from django.urls import reverse_lazy class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' My urls.py has below redirect rules from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] My signup.html template looks like below {% extends 'base.html' %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock content %} I am trying to redirect to login page once signup completed. But its not working, and one more observation is I see the POST request status as 200, but if I go to login page, I am unable to login with those new credentials. What error I am doing, any help appreciated. Thank you. I am using Django 2.1.5 with Python 3.7.4 -
Dango bootstrap styling shows up fine on dev-box, not on production
I've got a Django site which uses the "django-machina" forum software, which in its latest incarnation apparently uses Bootstrap4 styling. After installing the package according to directions, it looks beautiful on my development box. But, when I deploy exactly the same software on production, Bootstrap obviously isn't running because nothing is properly styled. There are no 404's and no console messages. *(Yes, I remembered to run manage.py collectstatic ...) There are some stylesheets complaints from Firefox but they're identical in both cases. But ... the display is not! Can anyone suggest what I might do in order to solve this problem? I'm stumped! -
How to get list of all fields corresponding to a model saved in content type framework in django
I have this requirement in which I have to show two dropdown fields on Django admin page. The first field will be the dropdown of all the table names available in my project, and the second field will be a dropdown all the available fields of the table selected in 1st dropdown. The second field will be dynamic based on the selection of the first dropdown. I am planning to handle this by overriding change_form_template. Now, I can show the dropdown of table names by fetching them through content type Django model, But not able to fetch corresponding fields as content type model save the model name as a string. So is there any way not necessarily using Content-Type to achieve such a requirement? Any help around that will be highly appreciated. Thank you. -
Saving many-to-many fields from the excel file in Django
I'm trying to save the student data from an excel file. I'm reading the excel file row-wise and mapping the data to the model fields. Now the problem is that there is a foreign key and a many-to-many field which I don't know how to save. Though I figured out the foreign key part but not able to solve the second part. Here are the files. views.py def fileUpload(request): if request.method=="POST": form= UserDataUploadView(request.POST, request.FILES) try: excel_file= request.FILES["excel_file"] except MultiValueDictKeyError: # In case the user uploads nothing return redirect('failure_page') # Checking the extension of the file if str(excel_file).endswith('.xls'): data= xls_get(excel_file, column_limit=10) elif str(excel_file).endswith('.xlsx'): data= xlsx_get(excel_file, column_limit=10) else: return redirect('failure_page') studentData= data["Sheet1"] print("Real Data", studentData) # reading the sheet row-wise a_list= studentData list_iterator= iter(a_list) next(list_iterator) for detail in list_iterator: # To find out empty cells for data in detail: if data==" ": print('A field is empty') return redirect('user_upload') print("DATA: ", detail) user=User.objects.create( firstName = detail[6], lastName = detail[7], password = detail[8], username = detail[9], ) # instance=user.save(commit=false) # Student.batch.add(detail[0]) student=Student.objects.create( user = user, email = detail[1], rs_id = detail[2], dob = detail[3], address = detail[4], age = detail[5], ) student.save() return render(request, 'classroom/admin/success_page.html', {'excel_data':studentData}) # iterating over the rows and # getting … -
I cannot understand that how to change font family in forms in django
how do I change the font family in the content portion ? -
Django Error Module 'Whitenoise' not found
I'm using whitenoise to deploy static files in prod, so according to whitenoise's docs, it's recommended to use it in development too. So I followed the documentation and added the following to my settings.py file: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', ...other ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ...other ] But when I run the server using python manage.py runserver 0.0.0.0:8000, I get the error ModuleNotFoundError: No module named 'whitenoise' Full stack trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/path/to/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path/to/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/path/to/venv/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'whitenoise' I checked using pip freeze … -
Migrations Error = No changes detected in app 'myapp'
I have included 'myapp' at myproj/setting.py INSTALLED APP, and I have tried to add some model and stuff but it still return the error No changes detected in app 'myapp', what should I do????? this is the step that lead to the error hostname $ python pip install django hostname $ django-admin startproject myproj hostname $ cd myproj hostname $ python manage.py startapp myapp hostname $ python manage.py makemigrations myapp -
django @login_required decorator for a last_name, only users with last_name == 'kitchen' entry
Is there a decorator in django similar to @login_required that also tests if the user has lastname == kitchen? Thanks -
Django + Apache(httpd): Error loading MySQLdb module
I have tried to figure this out for a day now and cannot seem to make any headway. I'm getting the following Apache error: [wsgi:error] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. [wsgi:error] Did you install mysqlclient? [wsgi:error] [remote 10.10.10.90:35990] mod_wsgi (pid=14165): Target WSGI script '/var/www/vhosts/project_vision/web/web/wsgi.py' does not contain WSGI application 'application'. File structure is this (web is the name of the Django project within the larger Project_vision project): /var/www/vhosts/project_vision |- venv/ |- web/ |- static |- templates |- vision_web |- models/ |- migrations/ |- ... |- web |- settings.py |- wsgi.py |- ... /var/www/vhosts/project_vision/web/web/wsgi.py import os import signal import sys import time import traceback from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/vhosts/project_vision') sys.path.append('/var/www/vhosts/project_vision/web') sys.path.append('/var/www/vhosts/project_vision/venv') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web.settings') try: application = get_wsgi_application() except Exception: # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) /etc/httpd/conf.d/vision.conf <VirtualHost *:80> ServerName my_project_vision.com DocumentRoot /var/www/vhosts/project_vision/web Alias /static/ /var/www/vhosts/project_vision/web/static/ <Directory /var/www/vhosts/project_vision/web/static> Require all granted </Directory> WSGIDaemonProcess my_project_vision.com \ processes=2 threads=15 display-name=%{GROUP} \ python-home=/var/www/vhosts/project_vision/venv \ python-path=/var/www/vhosts/project_vision/web WSGIProcessGroup my_project_vision.com WSGIApplicationGroup %{GLOBAL} # Insert the full path to the wsgi.py-file here WSGIScriptAlias / /var/www/vhosts/project_vision/web/web/wsgi.py <Directory /var/www/vhosts/project_vision> AllowOverride all Require all granted Options FollowSymlinks </Directory> </VirtualHost> Where in the world am I going wrong? It must be something minor but important... -
how to share DB connection across threads in Django out of standard request/response thread
Thanks for reading this. I understand that in the Django request/response framework, connection is controlled by Django. Such as closing connection basing on the CONN_MAX_AGE. our project has backend and GUI. GUI part is ok, connection is handled by Django. The backend uses too many connections. As Django will create new connection for each new thread. and never close it. So I am trying to share db connection across threads in backend. I create a global connection(with allow_thread_sharing=True) and guard it with Threading.RLock. The issue now is when to acquire and release this lock. I still get SEGMENTATION fault with acqure/release around get_queryset, execute_sql: Manager.get_queryset = share_conn_decorator(Manager.get_queryset) SQLCompiler.execute_sql = share_conn_decorator(SQLCompiler.execute_sql) SQLUpdateCompiler.execute_sql = share_conn_decorator(SQLUpdateCompiler.execute_sql) SQLInsertCompiler.execute_sql = share_conn_decorator(SQLInsertCompiler.execute_sql) Can you suggest that whether sharing db connection is doable? if so when/where should I lock the connection? Thanks -
Starting with Django: can't raise 404 or find the questions
i'm totally new to Django and i'm doing the tutorial. My issue is that I cannot find the questions that I've created, when i go to the URL http://127.0.0.1:8000/polls/1/ it won't show neither the question nor the 404 error that I coded. These are the relevant files (please say so if I'm missing one) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] models.py from django.db import models import datetime from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Thanks in advance! -
Want to execute a function after keyboard interrupt(CTRL+C) in django?
Basically I write data to file after processing using python script in django but I want to call that write to file function even after I press press keyboard interrupt. How to achieve this as on pressing ctrl+c django closes -
Django Rest universal linking -- json file path not found
I have a Django REST framework that is integrating universal app linking for iOS https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html The main point is that I have a json file called "apple-app-site-association" in my root directory (as instructed) that controls the redirect. When I put this through an aasa validator https://branch.io/resources/aasa-validator/ it returns a 400. My server logs show Not Found: /.well-known/apple-app-site-association I can't find any resources doing this with django, so I'm a little stuck on what to try or do next. -
expecting one result, but django .filter() returns multiple
I am chaining the filters and expecting one result to return -because according to the conditions result should be one- but it returns related rows as well... // taking the ID from the parent table. pid = Budgets.objects.filter(project_name=direct["project_name"]).values("id")[0]["id"] // checking the row exist or not. exists = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").exists() if exists == True: // if it's exist then return it with the according criterias value = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").values_list("ad_kind", flat=True)[0] print(value) // the problem occurs here. normally filter(ad_kind="gsn") should filter it till gsn left. But it doesn't. And it return other kinds too... Any idea what can be causing this problem?