Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dealing rest api with huge data using mySQL, Django, vueJS
Circumstance: VueJS request to Django for get all Data where in mySQL. Load mySQL-data (The files-ize is approximately 8GB as CSV) with Django will do. Django make response with this data and send it back to vueJS. The problem is 3. Eventually the Front-End(vueJS) has to not only achieves all the data without loss but also show it to user. Is there some way to make it faster? In my opinion, API Chaining way is a bit useful like bellow. Request) let amout_rows = 20 axios.get("url/" + amout_rows) .then((res) => { if (res.data.status === 200) { axios.get("url/" + amout_rows+20) { .then((res) => {.. continues}.catch(()=>{}) } } }).catch((err) => { console.log(err) }) Django collect data from mySQL response(data=data, status=200) In this opinion occurs API(transaction) frequently so I think it is very bad for solve the issue that give all the data to Front-End. I don't know any other idea and logics. It will be very helpful if there is other way thanks. -
Direct assignment to the reverse side of a related set is prohibited. I added a property and got this error
I don't understand why i got this error, I just added a new foreign key property to Rest model and it doesn't work: Error TypeError: Direct assignment to the reverse side of a related set is prohibited. Use exercises.set() instead. I don't know if the name "rest" is causing I already changed the name of the property but I can't make it work. models.py class Routine(models.Model): name = models.CharField(max_length=30) creation_date = models.DateField(auto_now_add=True) class Workout(models.Model): name = models.CharField(max_length=30) creation_date = models.DateField(auto_now_add=True) routine = models.ForeignKey(Routine, related_name='workouts', on_delete=models.CASCADE) class Exercise(models.Model): index = models.IntegerField() video_url = models.URLField(max_length=200) workout = models.ForeignKey(Workout, related_name='exercises', on_delete=models.CASCADE) class Rest(models.Model): index = models.IntegerField() duration = models.IntegerField() workout = models.ForeignKey(Workout, related_name='rests', on_delete=models.CASCADE) routine = models.ForeignKey(Routine, related_name='rests', on_delete=models.CASCADE) serializers.py class WorkoutSerializer(serializers.ModelSerializer): exercises = ExerciseSerializer(many=True) rests = RestSerializer(many=True) class Meta: model = Workout fields = ['id', 'name', 'creation_date', 'exercises', 'rests'] def create(self, validated_data): exercises_data = validated_data.pop('exercises') rests_data = validated_data.pop('rests') workout = Workout.objects.create(**validated_data) for exercise_data in exercises_data: Exercise.objects.create(workout=workout, **exercise_data) for rest_data in rests_data: Rest.objects.create(workout=workout, **rest_data) return workout class RoutineSerializer(serializers.ModelSerializer): workouts = WorkoutSerializer(many=True) rests = RestSerializer(many=True) class Meta: model = Routine fields = ['id', 'name', 'creation_date', 'workouts', 'rests'] def create(self, validated_data): workouts_data = validated_data.pop('workouts') rests_data = validated_data.pop('rests') routine = Routine.objects.create(**validated_data) for workout_data in workouts_data: Workout.objects.create(routine=routine, … -
AUTH_USER_MODEL error in production only: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed
I have my app working on localhost but when i deploy to production (Heroku), I get this error: File "./blog/models.py", line 6, in <module> 2021-03-24T23:31:05.696194+00:00 app[web.1]: User = get_user_model() 2021-03-24T23:31:05.696219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 162, in get_user_model 2021-03-24T23:31:05.696372+00:00 app[web.1]: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL 2021-03-24T23:31:05.696397+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed I have tried countless configurations, such as setting AUTH_USER_MODEL = 'auth.User' in settings after doing from django.contrib.auth.models import User and: from django.contrib.auth import get_user_model User = get_user_model() but nothing works. settings.py """~~~NOTES~~~ - procfile could use channel_layer instead of channels - AUTH_USER_MODEL could be 'django_project.User'. Worked locally but not on heroku - django.setup() seems ok at bottom of settings.py - If have to """ import django from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application # from django.contrib.auth.models import User #todo: this causes ImproperlyConfigured: SECRET_KEY MUST NOT BE EMPTY import os import django_heroku DJANGO_SETTINGS_MODULE = 'django_project.settings' SECRET_KEY = 'asdaf123$9pv98=e6p^gl(-eoj' #todo: test removing this in own deployment # AUTH_USER_MODEL=User # todo: this causes RuntimeError: populate() isnt reentrant #SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = 'True' ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.auth', 'blog.apps.BlogConfig', #allows Django to correctly search … -
How to access Postgresql database from multiple threads in a Django test?
I have a Django website with a PostgreSQL database that runs some background tasks with multithreading. However, I am having troubles testing this multithreading part. I followed https://docs.djangoproject.com/en/3.1/intro/tutorial01/ and https://docs.djangoproject.com/en/3.1/intro/tutorial02/ to start a new Django website. Then I added polls/tests.py as follows: import datetime from django.test import TestCase, TransactionTestCase from django.utils import timezone from .models import Question import threading, time class QuestionModelTests(TransactionTestCase): # line 10 # class QuestionModelTests(TestCase): # line 11 def test_was_published_recently_with_future_question(self): Question(question_text='asdf', pub_date=datetime.datetime.now()).save() print('a', Question.objects.filter()) def thread1(): print('b', Question.objects.filter()) t = threading.Thread(target=thread1, daemon=True) t.start() time.sleep(1) assert not t.is_alive() I also changed settings.py to switch to the new database: if 'POSTGRESQL': # line 79 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mysite', 'USER': 'postgres', 'PASSWORD': 'my_postgresql_password', 'HOST': '127.0.0.1', 'PORT': '5432', } } else: # line 90 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } However, if I run python3 manage.py test, I get this error: (tmp) [user@localhost mysite]$ python3 manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_mysite" already exists Type 'yes' if you would like to try deleting the test database 'test_mysite', or 'no' to cancel: yes Destroying old test database for alias 'default'... … -
Python/Django - How to submit a form, within a form, through a modal?
Scenario I have two forms. In my case, I want to submit a second form through a modal, while being in the first form template. Instead of this, modal pops up as it should be when I click the link, but when I hit the submit button, the modal form is not submitted, but the main form is. I created a minimized project that simulates the problem. Code # models.py class TestModel1(models.Model): name = models.CharField(max_length=20) class TestModel2(models.Model): name = models.CharField(max_length=20) # forms.py class TestModel1Form(forms.ModelForm): class Meta: model = TestModel1 fields = ["name", ] class TestModel2Form(forms.ModelForm): class Meta: model = TestModel2 fields = ["name", ] # views.py class TestModel1Create(CreateView): model = TestModel1 form_class = TestModel1Form template_name = 'mytestapp/testmodel1_form.html' success_url = '/testmodel1/create' class TestModel2Create(CreateView): model = TestModel2 form_class = TestModel2Form template_name = 'mytestapp/testmodel2_form.html' success_url = '/testmodel1/create' Here is the "main" form, testmodel1_form.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script> <a href="/testmodel2/create/" class='li-modal'>Goto form 2</a> <div id="theModal" class="modal fade text-center"> <div class="modal-dialog"> <div class="modal-content"></div> </div> </div> <script> $('.li-modal').on('click', function(e){ e.preventDefault(); $('#theModal').modal('show').find('.modal-content').load($(this).attr('href')); }); </script> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> </body> </html> And here is the modal … -
Cannot use sync_to_async decorator after raising asyncio.CancelledError
import asyncio from asgiref.sync import sync_to_async @sync_to_async def sync_func(): print("sync_func() was CALLED (good!)") async def async_func(): print("async_func() was CALLED (good!)") async def test(excep_type: type = asyncio.CancelledError): print(f"\nException Type: {excep_type}") try: raise excep_type except: await async_func() try: await sync_func() except asyncio.CancelledError: print("sync_func() was CANCELLED (bad!)") asyncio.run(test(excep_type=ValueError)) asyncio.run(test()) Hi there. I have a simple example test is an async function which does nothing but raise a provided error type and then await both async_func and sync_func inside. sync_func is a synchronous function made asynchronous with sync_to_async of the asgiref package. Running this gives the following output: Exception Type: <class 'ValueError'> async_func() was CALLED (good!) sync_func() was CALLED (good!) Exception Type: <class 'asyncio.exceptions.CancelledError'> async_func() was CALLED (good!) sync_func() was CANCELLED (bad!) In the first case, ValueError is raised and inside the exception clause, I can await async_func and sync_func like normal. However in the second case, I have behaviour I wouldn't expect. I should be able to await sync_func like normal, but it instead raises asyncio.CancelledError as indicated by the printout. In reality I haven't changed anything between the two calls, except changed the type of error which was originally raised and caught by the exception clause. However the type of raised error … -
When are signals executed in Django?
I want to override a save() method that is connected to a signal, if I do, when will the signal be executed? When the method ended or when I call super? Here I explain my question with code: def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) self.__original_field = self.field def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.__original_field < self.field: # Do something # The signal will be executed after this line? super(Model, self).save(force_insert, force_update, *args, **kwargs) # Or after this line? self.__original_field = self.field -
Can I use a ModelViewSet for POST and GET of a parent of self in a model in Django REST?
Hello I have the following structure: class Category(models.Model): model.py """Class to represent the category of an Item. Like plants, bikes...""" name = models.TextField() description = models.TextField(null=True) color = models.TextField(null=True) # This will help to anidate categories parent_category = models.ForeignKey( 'self', on_delete=models.SET_NULL, null=True, ) Then I serialize it: serializers.py: class CategorySerializer(serializers.ModelSerializer): """Serializer for Category.""" class Meta: # pylint: disable=too-few-public-methods """Class to represent metadata of the object.""" model = Category fields = ['id', 'name', 'description', 'color', 'parent_category'] And I Create my endpint views.py: class CategoryViewset(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors """API Endpoint to return the list of categories""" queryset = Category.objects.all() serializer_class = CategorySerializer pagination_class = None Well this seems to work as expected to make a post request, for example sending this: { "name": "Plants", "description": null, "color": "#ef240d", "parent_category": 1 } But when I make a request of this I want to see the parent category and not have to do two requests. So I found from other questions that I could use an external library: serializer.py from rest_framework_recursive.fields import RecursiveField class CategorySerializer(serializers.ModelSerializer): """Serializer for Category.""" parent_category = RecursiveField(many=False) class Meta: # pylint: disable=too-few-public-methods """Class to represent metadata of the object.""" model = Category fields = ['id', 'name', 'description', 'color', 'parent_category', 'category_name'] … -
Django Production - Google SMTP Authentication Error 7th March Update
Hello so I was using the gmail SMTP server for a while and sent tons of mails through this service then suddenly on 7th it sent the last email then it stopped working. I have no idea why. I get this error: smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv\n5.7.14 A7X9QB3AzCPb4vHySkYB4aVpADCYZPn1JuCKOGPei_Eub1JLK52vyXy9DlvMA8TlxJQld\n5.7.14 btXh92Arc91oACfm5Hh99IrUFVacZWZPsnUYjINPOKHDndJvV4lGRF96ynwYiIib>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 o125sm2227199qkf.87 - gsmtp') I am using Django and this is my config for the smtp: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@addres.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False It is very strange the fact that when I'm using my app in localhost, it does work, but in production(hosted on pythonanywhere.com) I get this random error. Any ideas why? -
I am getting an error when importing sklearn
i am getting an error when trying to import import sklearn.metrics.pairwise as pw full error: ImportError: DLL load failed while importing _arpack: The specified procedure could not be found. import: import sklearn.metrics.pairwise as pw traceback: Traceback (most recent call last): File "C:\Users\Humza\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Humza\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Humza\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Humza\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Humza\anaconda3\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Humza\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Humza\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Humza\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Humza\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\Humza\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Humza\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Humza\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Humza\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Humza\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in … -
Psycopg2 Error When Running Django Via Serverless
File "/var/task/django/db/backends/postgresql/base.py", line 29, in raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory I'm receiving the following error after deploying a Django application via Serverless. If I deploy the application via our Bitbucket Pipeline. Here's the Pipeline: - step: &Deploy-serverless caches: - node image: node:11.13.0-alpine name: Deploy Serverless script: # Initial Setup - apk add curl postgresql-dev gcc python3-dev musl-dev linux-headers libc-dev # Load our environment. ... - apk add python3 - npm install -g serverless # Set Pipeline Variables ... # Configure Serverless - cp requirements.txt src/requirements.txt - printenv > src/.env - serverless config credentials --provider aws --key ${AWS_KEY} --secret ${AWS_SECRET} - cd src - sls plugin install -n serverless-python-requirements - sls plugin install -n serverless-wsgi - sls plugin install -n serverless-dotenv-plugin Here's the Serverless File: service: serverless-django plugins: - serverless-python-requirements - serverless-wsgi - serverless-dotenv-plugin custom: wsgi: app: arc.wsgi.application packRequirements: false pythonRequirements: dockerFile: ./serverless-dockerfile dockerizePip: non-linux pythonBin: python3 useDownloadCache: false useStaticCache: false provider: name: aws runtime: python3.6 stage: dev region: us-east-1 iamRoleStatements: - Effect: "Allow" Action: - s3:GetObject - s3:PutObject Resource: "arn:aws:s3:::*" functions: app: handler: wsgi.handler events: - http: ANY / - http: … -
How to query a Django model (table) and add two related fields from another model (table)? - annotate - left outer join
I want to get one specific row (object) from the Movie model(table) and add the maximum rating and the user who posted the maximum rating. Like so: movie.id | movie.title | movie.description | movie.maximum_rating | movie.maximum_rating_user Below is is the code I tried. Unfortunately, my query is returning a queryset which the get() method is not able to work with. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name="ratings") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ratings") score = models.DecimalField(decimal_places=2, max_digits=9) class Movie(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=4096) views.py from django.http import HttpResponse from django.shortcuts import render from .models import User, Movie, Rating from django.db.models import Max, F def index(request, movie_id): movie = Movie.objects.all().annotate( maximum_rating=Max('ratings__score'), maximum_rating_user=F('ratings__user') ).get(pk=movie_id) return HttpResponse(movie) Can anyone tell me how to make the proper query so I can get one specific movie (object/row) with the two add fields from the Ratings model? -
Django CSRF token: Set and Validate of Different Servers?
Say that I have multiple Django servers running on a distributed system. Is it possible to assign the CSRF token on one server and then validate it on another? Would having the same SECRET_KEY on all servers be sufficient? Do I need another CSRF-token system altogether? -
Passing image to modal django with jquery
I'm trying to pass data on the modal with the help of jquery. I was successful passing all text related data but I'm unsure how would it work for images. As we use the {% static %} tag to show the images. It wouldn't just show on the passed modal. Loop from where the data is being taken. <div class="animals" id="cats" > {% for animals in cats %} <div class="animalInfo" id="animalInfoID" data-image = "{{ animals.image.url }}" data-name="{{ animals.name }}" data-ageyears="{{ animals.age }}" data-agemonths="{{ animals.age_months }}" data-gender="{{ animals.gender }}" data-description="{{ animals.description }}" onclick="showContainer()"> <img class="animalPic" src="{{ animals.image.url }}" alt=""> <div class="animalDesc"> <h1>{{ animals.name }}</h1> <p>{{ animals.description }}</p> </div> </div> {% endfor %} </div> Modal where data is passed <div class="mainAdoptionPopContainer" id="mainAdoptionContainerId" style="display: none;"> <img src="{% static 'adoptions/imgs/close-container.png' %}" onclick="hideContainer()" class="closeContainer" id="closeContainerID" alt="Close Pop Up"> <div class="adoptionPopImageContainer"> <img id="adoptionPopImage" src=""></img> </div> <div class="adoptionPopAnimalInfo"> <div class="adoptionPopAnimalInfoTitle"> <span id="adoptionPopName"><b></b></span> | <span id="adoptionPopGender"><b></b></span> | <span><span id="adoptionPopAge"></span> Year <span class="adoptionPopAgeMonths"></span>Months</span> | <span id="adoptionPopBreed"><b></b></span> </div> <span class="adoptionDescription" id="adoptionDescriptionID"></span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function() { $('.animalInfo').click(function(){ $("#adoptionPopName").html($(this).data("name")); $("#adoptionPopImage").html($(this).data("image.url")); $("#adoptionPopGender").html($(this).data('gender')); $("#adoptionPopBreed").html($(this).data('breed')); $("#adoptionPopAge").html($(this).data('ageyears')); $("#adoptionPopAgeMonths").html($(this).data('agemonths')); $("#adoptionPopBreed").html($(this).data('breed')); $("#adoptionDescriptionID").html($(this).data('description')); }); }); </script> -
Assign value to variable in settings.py file
I am trying to use flash text in django. I think that KeyWordProcessor should be called only once. So i have defined it in settings.py file as this: settings.py KEYWORD_PROCESSOR = NONE Then i am calling function KeywordProcessor() on app start like this: apps.py from django.apps import AppConfig class MywebappConfig(AppConfig): name = 'mywebapp' def ready(self): import mywebapp.signals from flashtext import KeywordProcessor from django.conf import settings from mywebapp.utils import add_all_kewords_to_flash_text import threading settings.KEYWORD_PROCESSOR = KeywordProcessor() add_all_kewords_to_flash_text() t1 = threading.Thread(target=add_all_kewords_to_flash_text) t1.start() utils.py def remove_keyword_from_flash_text(keyword_obj): if not settings.KEYWORD_PROCESSOR: raise ValueError("Flash text is None") removed = settings.KEYWORD_PROCESSOR.remove_keywords_from_dict( {keyword_obj.keyword: [keyword_obj.keyword]+keyword_obj.tags} ) def add_keyword_to_flash_text(keyword_obj): if not settings.KEYWORD_PROCESSOR: raise ValueError("Flash text is None") added = settings.KEYWORD_PROCESSOR.add_keywords_from_dict( {keyword_obj.keyword: [keyword_obj.keyword]+keyword_obj.tags} ) def add_all_kewords_to_flash_text(): add_all_kewords = [add_keyword_to_flash_text(k) for k in KeyWord.objects.all()] But i am getting this error: ValueError: Flash text is None -
Why I am getting this Error while I am trying to use another model via through in django models
I'm trying to make a calorie counter project. In django models, I used 3 classes (Food, Profile, PostFood). The profile class has the 'all_food_selected_today' field, and there is the 'through' option. When I try to run the project, I get this error: The model is used as an intermediate model by 'AplicationC.Profile.all_food_selected_today', but it does not have a foreign key to 'Profile' or 'Food'. Why it happends ? There is my django models.py file from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here class Food(models.Model): name = models.CharField(max_length=200, null=False) quantity = models.PositiveIntegerField(null=False, default=0) calorie = models.FloatField(null=False, default=0) person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Profile(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) calorie_count = models.FloatField(default=0, null=True, blank=True) food_selected = models.ForeignKey (Food, on_delete=models.CASCADE, null=True, blank= True) quantity = models.FloatField(default=0, null=True) total_calorie = models.FloatField(default=0, null=True) date = models.DateField(auto_now_add=True) calorie_goal = models.PositiveIntegerField(default=0) all_food_selected_today = models.ManyToManyField(Food, through='PostFood', related_name='inventory') def save(self, *args, **kwargs): if self.food_selected != None: self.amount = (self.food_selected.calorie/self.food_selected.quantity) self.calorie_count = self.amount*self.quantity self.total_calorie = self.calorie_count + self.total_calorie calories = Profile.objects.filter(person_of=self.person_of).last() PostFood.objects.create(profile=calories, food=self.food_selected, calorie_amount=self.calorie_count, amount = self.quantity) self.food_selected = None super(Profile, self).save(*args, **kwargs) else: super(Profile, self).save(*args, **kwargs) def __str__(self): return str(self.person_of.username) class PostFood(models.Model): profile = models.ForeignKey(Profile, … -
Uncaught SyntaxError: Unexpected identifier. Trying to create a comment form in django with ajax. Encountered this error and need help solving it [closed]
I am following this django tutorial and I am trying to create a form for users to make comments using ajax. I am getting the error above and I don't seem to understand what could be wrong with my code. <script src="{% static 'jquery-3.6.0.min.js' %}"></script> <script> $(document).ready(function(){ $(".save-comment").on('click',function(){ var _comment=$(".comment-text").val(); var _answerid=$(this).data('answer'); // Ajax $.ajax({ url:"/save-comment", type:"post", data:{ comment:_comment, answerid=_answerid, csrfmiddlewaretoken:"{{csrf_token}}" }, dataType:'json', beforeSend:fuction(res) $(".save.comment").addClass('disabled').text('saving...'); }, success:function(res){ console.log(res); $(".save-comment").removeClass('disabled').text('Submit'); } }); }); }); -
Difficulty in saving data in Crispy forms usung ModelForm in django
Saving data in django on a formn rendered by {{ form|crispy}} works fine but when I render the template using {{ form.ShowStatus|as_crispy_field}} nothing gets saved. Data is initially loaded into form with no problems, this is an update issue. Am I missing something? Django==3.0, django-crispy-forms==1.9.2, Bootstrap version 4.3.1, Python 3.8.5 Am I missing something? This works.... loads existing data into Show_form.html {% extends "fungi/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Filter</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-primary" type="submit">Create filter</button> </div> </form> </div>loads {% endblock content %} Traceback for working code [24/Mar/2021 19:57:01] "GET /testform/show/3/ HTTP/1.1" 200 5065 [24/Mar/2021 19:57:06] "GET /testform/show/3/update/ HTTP/1.1" 200 11845 [24/Mar/2021 19:57:14] "POST /testform/show/3/update/ HTTP/1.1" 302 0 [24/Mar/2021 19:57:14] "GET /testform/show/3/ HTTP/1.1" 200 5062 This doesn't work.... loads existing data but doesn't save when submit button clicked Show_form.html {% extends "fungi/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.ShowAll|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowFungi|as_crispy_field}} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowHabitat|as_crispy_field}} </div> <div class="form-group col-md-4 mb-0"> {{ form.ShowStatus|as_crispy_field }} … -
How to use inner join on Subquery() Dajngo ORM?
I have to models class FirstModel(models.Model(): some_fields... class SecondModel(models.Model): date = models.DateTimeField() value = models.IntegerField() first_model = models.ForeignKey(to="FirstModel", on_delete=models.CASCADE) and I need query select sum(value) from second_model inner join ( select max(date) as max_date, id from second_model where date < NOW() group by id ) as subquery on date = max_date and id = subquery.id I think I can do it using Subquery Subquery(SecondModel.objects.values("first_model") .annotate(max_date=Max("date")) .filter(date__lt=Func(function="NOW"))) and F() expressions but it only can resolve model fields, not subquery Question is it possible to implement using django ORM only? also evaluate sum of values from secondModel for all values in first model by annotate this value? -
How to rewrite similar functions in Django
I have a python/django view function where it returns items from a model. I am creating a view with filters to see the data I want. Most of the time it only means changing one word in the function to get the filtered data I need. Is this best practice or should I be using some other programming construct? Here is an example of the function, in this case I have to create 3 functions/views and 3 urls to one for risk=high, risk=medium, risk=low, yada yada yada def Criticals(request): # YOU CAN NEGATE THE Q WITH THE TILDA#### items = ScanData.objects.filter(Q(Project_Assigned__icontains="Hooli") & (Q(Risk__icontains="Critical"))) numberIPs = items.count() Criticals = ScanData.objects.filter(Q(Risk="Critical") & (Q(Project_Assigned__icontains="Hooli"))) Highs = ScanData.objects.filter(Q(Risk="High") & (Q(Project_Assigned__icontains="Hooli"))) Mediums = ScanData.objects.filter(Q(Risk="Medium") & (Q(Project_Assigned__icontains="Hooli"))) Lows = ScanData.objects.filter(Q(Risk="Low") & (Q(Project_Assigned__icontains="Hooli"))) numberCriticals = Criticals.count() numberHighs = Highs.count() numberMediums = Mediums.count() numberLows = Lows.count() context = { 'items': items, 'header': 'The Hooli Project', 'numberIPs': numberIPs, 'numberCriticals': numberCriticals, 'numberHighs': numberHighs, 'numberMediums': numberMediums, 'numberLows': numberLows, } return render(request, 'index.html', context) -
Flatten Django Queryset that is using select_related() and full join
my goal is to union two querysets, however, they only match columns after the first queryset has been joined with it's foreign key table. Let me explain. Say I have three models like this: Models.py class Data(models.Model): name = models.TextField() extra_data = models.OneToOneField(Extra, on_delete=models.CASCADE) class Extra(models.Model): age = models.IntegerField() class FullData(models.Model): name = models.TextField() age = models.IntegerField() Then I am trying to do something like this: data = Data.objects.select_related() fullData = FullData.objects.all() queryset = data.union(fullData) This returns an error of: django.db.utils.OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns The two issues here are: data does not get the columns if there is no related row in the Extra table The columns from select_related are only accessible by doing data.extra_data.age, meaning the left side of the union won't have the same number of columns. I want to utilize django, but it's not giving me the same results as a query like: SELECT * FROM Data LEFT JOIN Extra on Data.extra_data = Extra.id Please note I am using sqlite which is why the above query is written with a LEFT JOIN. Any thoughts on how I can get select_related() to return null … -
How to counting time in django
I have table like this: id | name | time | 1 | aaaa | 00:36:00 | 2 | aaaa | 01:00:00 | 3 | cccc | 00:10:00 | 4 | bbbb | 00:30:00 | 5 | cccc | 00:30:00 | How can I count the time grouped for each name in Django like this: name | time | aaaa | 01:36:00 | bbbb | 00:30:00 | cccc | 00:40:00 | It is possible in Django ?? Thanks for any help! -
Django SQL - query returns AttributeError module '__main__' has no attribute 'df'
The above error is returned when I run the code below. views.py import pandas as pd import sqldf import numpy as np from django.http import HttpResponse def test(request): # Create a dummy pd.Dataframe df = pd.DataFrame({'col_1': ['A', 'B', np.NaN, 'C', 'D'], 'col_2': ['F', np.NaN, 'G', 'H', 'I']}) # Define a SQL (SQLite3) query query = """ SELECT * FROM df WHERE col_1 IS NOT NULL; """ # Run the query print(sqldf.run(query)) return HttpResponse('Success!') urls.py from django.urls import path from .views import test urlpatterns = [ path('test/', test), ] However, the following script returns the expected response without errors: import pandas as pd import sqldf import numpy as np df = pd.DataFrame({'col_1': ['A', 'B', np.NaN, 'C', 'D'], 'col_2': ['F', np.NaN, 'G', 'H', 'I']}) query = """ SELECT * FROM df WHERE col_1 IS NOT NULL; """ # Run the query df_view = sqldf.run(query) print(df_view) How come there is an error when I execute the above script through my django website but not when I execute the script by running it on the terminal? -
Difference between two values in choices tuple
Below I have a Car class, I have a tuple for choosing from a list of brands. My question is what is the difference between the two values? In ('DODGE', 'Dodge') can I just name both Dodge or does one need to be uppercase? class Car(models.Model): BRAND_CHOICES = ( ('DODGE', 'Dodge'), ('CHEVROLET', 'Chevrolet') ) title = models.CharField(max_length=255) brand = models.CharField(max_length=255, choices=BRAND_CHOICES) def __str__(self): return self.title -
Python: asynchronically ssh to multiple servers and execute commands, then save result into database
I've searched extensively on Google and stackOverflow but cannot find relevant answer. So asking here. Hope you can kindly demo how to do it. My use case is as follows: User put in ip addresses in a django form field (e.g. 12.12.12.12, 13.13.13.13, 14.14.14.14) django take ips and ssh to those machines and execute predefined script if script runs successfully, then django saves the result to database django display each server's execution results (successful, failed) I can achieve the above function using sync methods, but the wait time is unbearably long. Trying to use asyncio.run to improve it but tried and failed repetatively. :S Here is my code: in views.py def create_record(request): record_form = RecordForm() if request.method == 'POST': record_form = RecordForm(request.POST) if record_form.is_valid(): ips = record_form.cleaned_data['ip'].split(',') start_time = time.time() for ip in ips: record_form = RecordForm(request.POST) record = record_form.save(commit=False) record.ip = ip record = asyncio.run(run_script(record)) # this function ssh to server and execute commands if record is correct: record.save() messages.success(request, ip + ' execution success') else: messages.error(request, ip + ' execution failed') total = time.time() - start_time print('total:', total) return redirect('create_record') context = {'record_form': record_form} return render(request, 'record-form.html', context) in install_script.py async def run_script(record): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) …