Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django aws static file error on https while making request on swagger root
vendors.bundle.js:61 Mixed Content: The page at 'https://api.ereturns.co/' was loaded over HTTPS, but requested an insecure resource 'http://api.ereturns.co/register/'. This request has been blocked; the content must be served over HTTPS. Hi, i have deployed my django project on aws ec2(ssl added) . but, when i am going to swagger root and making request it is throwing error failed to fetch and showing above error in console of chrome browser. It is beacuse of one js file What does that mean how can i fix it ? -
Django: failed to config/start Supervisor -> FATAL/BACKOFF Exited too quickly
I try to deploy my django project on a test server (Ubuntu) using Nginx/Gunicorn/Supervisor but i made error in the intensetbm-gunicorn.conf files and firt had this error: FATAL can't find command '/home/test/env/bin/gunicorn' So I modify with the correct path and run cmd and get the trace bellow with a final error: sudo supervisorctl reread intensetbm-gunicorn: changed sudo supervisorctl update intensetbm-gunicorn: stopped intensetbm-gunicorn: updated process group sudo supervisorctl status > BACKOFF Exited too quickly (process log may have details) my project architecture: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | ... intensetbm_static /etc/supervisor/conf.d/intensetbm-gunicorn.conf [program:intensetbm-gunicorn] command = /home/test/envs/envTbm/bin/gunicorn intenseTBM_eTool.wsgi.application user = test directory = /home/test/intensetbm_app/intensetbm-etool autostart = true autorestart = true -
How to update existing data and create new one django base command?
i am trying to store data in from json file and i added its not a problem to add data but when i trigger data again again they copy data and create same new one that i don't want , i want that it will update existing data and if there will new data in json file it will add in model . here is my django base command code. from django.core.management.base import BaseCommand import requests from demo.models import CoronaAge, CoronaSex, CoronaComorbidity class Command(BaseCommand): def handle(self, *args, **kwargs): url = 'https://api.the2019ncov.com/api/fatality-rate' r = requests.get(url) titles = r.json() print(titles) # For between age for title in titles['byAge'] or []: CoronaAge.objects.update_or_create( age=title['age'], rate=title['rate'] ) context = {'titles': CoronaAge.objects.all()} # for sex wise male and female for title in titles['bySex'] or []: CoronaSex.objects.update_or_create( sex=title['sex'], rate=title['rate'] ) context = {'titles': CoronaSex.objects.all()} for title in titles['byComorbidity'] or []: CoronaComorbidity.objects.update_or_create( condition=title['preExistingCondition'], rate=title['rate'] ) context = {'titles': CoronaComorbidity.objects.all()} -
Continously running Celery Task in Django
I've a Django app which should constantly listen for messages from Kafka and then send them via WebSocket to client. Problem is how to setup constant listener. For future scalability we decided to bring Celery in project to manage these issues with scaling. My task actually look like: class ConsumerTask(Task): name = 'consume_messages' def run(self, *args, **kwargs): consumer = get_kafka_consumer(settings.KAFKA_URL, settings.FAULT_MESSAGES_KAFKA_TOPIC, 'consumer_messages_group') logger.info("Kafka's consumer has been started") while True: messages = consumer.poll() for _, messages in messages.items(): messages, messages_count = self.get_message(messages) if messages_count > 0: messages = save_to_db() send_via_websocket_messages(messages) It properly saves and sends messages via WS, but problems comes from infinite loop in task. For some reason (probably task timeout constraint) task pop out if queue and never runs again. I am not sure that daemonizing celery workers will solve this problem. Could you please provide some strategies now organize "Constantly running part" of this process? -
Difference between add() and create() functions and the functionsality of save() method
I have been trying to understand the difference between .add() and .create() functions through django documentation. As far as I have understood is that: add() function with Foreign Key just updates the model and with m2m relation it does the bulk creation which eventually doesn't call for any save method. create function will create the instance of the object and save it. My doubt is: What does actually save does? If only create an instance without saving it, what does it mean? What is the main difference between add() and create() functions? -
Passing model instance's id in Django modelformset_factory
I am using modelformset_factory to be able to edit one parameter for all instances of a model. It works but I would like to display in the template the id of each individual model instance. How can I do that ? The view (the post request is handled by an other view): def habits(request): HabitFormSet = modelformset_factory( Habit, extra=0, form=HabitModelForm) context = { 'formset': HabitFormSet( queryset=Habit.objects.filter(user=request.user)) } return render(request, 'habits.html', context) the form: class HabitModelForm(MyFormMixin, forms.ModelForm): class Meta: model = Habit fields = [ 'name', ] the template: <form action="{% url 'bulk_edit' %}" method="post"> {% csrf_token %} <div class="table-responsive"> {{ formset.management_form }} <table> <tbody> {% for form in formset %} <tr> <td>test {{form.instance_id}}</td> / This would be ideal but not working {% for field in form %} <td>{{ field }}</td> {% endfor %} </tr> {% endfor %} <tr> <td> <button type="submit" class="btn btn-success text-right" value="Update">Update</button> </td> </tr> </tbody> </table> </div> </form> Thank you ! -
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