Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - extract all variables from a dict into locals
Is there a simple and elegant way to extract all variables from a dict to the current module locals? I am using Django and we would like to load all values of the local_settings.py file which is something like: DEBUG=True KEY="VALUE" NUMKEY=1 ... from a json, which will be compatible: { "DEBUG": true, "Key": "VALUE", "NUMKEY": 1 } so I'm looking for a simple way to extract all in few lines into the local variables of the settings.py file. Thank you! -
Django with Azure blob shared access signature
I am using azure blob storage for my media files in my django application. I need to implement shared access signature. Please help me to proceed. I am unable to find any docs or material to refer. Any help is appreciated. I tried with django-storages[azure] and upload alone works if i set the connection string. -
Django,HTML , connecting template to js,css
I have a Django project that contains a landing page. I worked on it outside the project and the HTML page was able to route to the js and CSS files and it worked great. Once I copied the folder into the project's templates folder (as shown in the structure below), And added routes and views in the project as required The server ran okay and open the page, But it's showing only the HTML and cannot refer to raises errors when trying to refer to the js scripts. for example: Not Found: /templates/js/main.js [19/Mar/2020 08:22:12] "GET /templates/js/main.js HTTP/1.1" 404 2490 # home.hmtl <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="yovelcohen" content="Sumon Rahman"/> <meta name="keywords" content="HTML,CSS,XML,JavaScript"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- Title --> <title>Triangulation Calculator</title> <!-- Plugin-CSS --> <link rel="stylesheet" href=".css/bootstrap.min.css"/> <link rel="stylesheet" href=".css/owl.carousel.min.css"/> <link rel="stylesheet" href=".css/linearicons.css"/> <link rel="stylesheet" href=".css/magnific-popup.css"/> <link rel="stylesheet" href=".css/animate.css"/> <!-- Main-Stylesheets --> <link rel="stylesheet" href=".css/normalize.css"/> <link rel="stylesheet" href=".style.css"/> <link rel="stylesheet" href=".css/responsive.css"/> <script src="js/vendor/modernizr-2.8.3.min.js"></script> </head> <body> <!-- MainMenu-Area-End --> <!-- Home-Area --> <header class="home-area overlay" id="home_page"> </header> <!-- Home-Area-End --> <!-- About-Area --> # some HTML stuff ... <!-- Footer-Area-End --> <!--Vendor-JS--> <script src="templates/js/vendor/jquery-1.12.4.min.js"></script> <script src="templates/js/vendor/jquery-ui.js"></script> <script src="templates/js/vendor/bootstrap.min.js"></script> <!--Plugin-JS--> <script src="templates/js/owl.carousel.min.js"></script> <script src="templates/js/contact-form.js"></script> … -
Permission error in oauath2 using access token django
I am trying to generate an access token like this in django-rest-framework: def generate_access_token(request, user): expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="test") expires = datetime.datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user, application=application, token=random_token_generator(request), expires=expires) token = { 'access_token': access_token.token, 'token_type': 'Bearer', 'expires_in': expire_seconds, 'scope': scopes } return token This is generating an access token, but when I am trying to use that access token to access other protected apis, it is giving me the following error:- { "detail": "You do not have permission to perform this action." } On the other hand, if I generate access token using the TokenView, that token is working fine. I am trying to manually create an access token using a user object returned on user registration and login. How can I get rid of this error, or what is the alternative to achieve this ? -
logout automatically in all tabs when logged out in one open tab with django
Is it possible to auto logout a user from all opened tabs(Popup window), if that user logoout from one of the open tab in the browser in django. If it is possible then How can I implement? Thanks in advance... -
How to properly setup facebook comment moderation tool?
I have added fb comments plugin on my django site, and would like to also use fb's moderation tool to moderate the comments on the pages involved. Previous dev made a mistake of not properly passing appId to the script, and I have rectified that. The problem is, some of the pages (without any comments present) do register new comments on the moderation tool, while others do not even though the its the same template, with the same script. Im including the related html and js code that I am using on the template <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId={{ SOCIAL_AUTH_FACEBOOK_KEY }}&xbfml=true&autoLogAppEvents=1" {% endif %} fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <meta property="fb:app_id" content="{{ SOCIAL_AUTH_FACEBOOK_KEY }}"/> <meta property="og:url" content="{{ article_url }}" /> <meta property="og:type" content="article" /> <meta property="og:title" content="{{ article.title }}" /> <meta property="og:description" content="{{ article.content|striptags|truncatechars:200 }}" /> <meta property="og:image" content="{{ article_full_image_url }}" /> <div id="fb-root"></div> <div class="fb-comments" data-href="https://{{ SITE.domain }}{{ LURL }}{{ request.path_info }}" data-num-posts="2" data-width="100%"></div> So the facebook sharing debugger tool picks up every meta tag properly, just comments are not being picked up on certain pages, while some do show up on the … -
Add interceptor for request in django rest framework like spring boot
I am new to python, I want to add HTTP request interceptor for each request like spring boot in python Django rest framework. where and how I can add in DRF. Anyone can help me ?. -
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