Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form and ModelForm errors Translation
I understand I can create custom error messages for each individual Form / ModelForm (Django custom error message). I understand I can create translations files to use in the templates (Django internationalization minimal example). The question is how can I create files to make my own translations of Form / ModelForm errors like LANGUAGE_CODE = 'pt-br' do but with my own translation. -
Django: Using the html to change a django model
I'm trying to make a button/image on a certain HTML change a particular value of a specific pre-existing model passed to that HTML page with Django. How I set it up is that we get a request to for a specific URL and it goes to our views.py which tells us to grab three random and unique models. We pass those three unique models into the .html page specified in render() and the .html page takes care of what attributes it wants to show about those models. index.html {% load static %} <figure><img src="/media/{{ f1.Img }}" width="200" height="180" alt=""> <figcaption> <h2>{{ f1.Desc }}</h2> <p>Score: {{ f1.Score }}</p> <footer class="bottomButton"><img src="{% static 'site-logo.jpg'%}" width="50%" height="50%" alt=""></footer> </figcaption> </figure> The figcaption is the container for both the content I want modified and the button/image to modify it. The footer is where I'm putting the image/button that you can click on. The figure is where I'm putting the actual model image, which doesn't need to be changed. So far though, the issue has been trying to find a way to change the value of a particular model's value for Score. I am trying to make the image itself have a property to do … -
Django - recreate database from migration files | Sync production and development databases
My situation is the following: I have a Django project in a production environment which uses a mysql database. Also, I have a copy of the same Django project in a local environment which uses a mysql database too. What I want to do is set the following workflow to deploy database changes into production: Make changes in local models. Run makemigrations. Run migrate. Add, commit and upload the migration file to production. Run simply "migrate" in production environment to update the production database. Actually, for some past reason both databases aren't completetly synced and for do this workflow, I need both databases works with same migration files and keep synced. Any help on how to do that? How can i create this local database fully synced with production? I tried the following things: Create an empty local database and simply apply the "migrate" command. Export the production database schema and create a local database based on it. None of the above worked because when i try to run locally the django server, first he says that i have 100 migrations unaplied and, when i do the migrate says... django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [] This can happen if you … -
Django Not Showing Template For Loop By Default In Search Form After Attempting Validation
Code: https://dpaste.org/6xSL I want to add some validation to my search form. For example, when a user enters a very large number in the visited_times__lte field, I get "OverflowError: Python int too large to convert to SQLite INTEGER". I want to prevent this from happening. I tried to correct this problem with my code above, but it caused other undesirable effects where it is not showing the template for loop search results by default on page refresh. The search acts similarly to how Google search does but it only works and shows the template for loop results if visited_times__lte has a value greater than 5. I would like to have template for loop results show with or without form submission. With a form submission, then filter the results that are already on the page based on what the user types into the form. The next thing I want to do is make sure that the form submits no matter what the user types into the form. However, if the user does type in a number into the visited_times__lte I want to display a message saying something like "number is too large" or "number is too small" or "number must be … -
Django, React-Native Connection Network Request Failed
I'm working on a react-native-based mobile application and doing some operations with python in the background. I wanted to do both these transactions and connect to the database via Django rest api. But I get connection error. I have used other rest-api and tried it. I also tried the rest api on the postman and it worked smoothly. I tried everything, but I couldn't find a solution. local rest url: http://localhost:8000/api/venues/ and fetch code: componentDidMount() { return fetch('http://localhost:8000/api/venues/?format=json') .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ isLoading: false, dataSource: responseJson, }, function(){ }); }) .catch((error) =>{ console.error(error); }); } -
How to send command line input responses in Django tests
I have a Django management command that will ask for command line input (y/n) and I'm now writing a test for this. Currently when I run the test (as is now), the test will stop and wait for the y/n input. But how can I write/update my test so that I can send a y/n response to the call_command function? For info, my management command code is (imports removed - but full code at: https://github.com/DigitalCampus/django-oppia/blob/master/oppia/management/commands/remove_duplicate_trackers.py): class Command(BaseCommand): help = _(u"Removes any duplicate trackers based on UUID") def handle(self, *args, **options): """ Remove page/media/quiz trackers with no UUID """ result = Tracker.objects.filter(Q(type='page') | Q(type='quiz') | Q(type='media'), uuid=None).delete() print(_(u"\n\n%d trackers removed that had no UUID\n" % result[0])) """ Remove proper duplicate trackers - using min id """ trackers = Tracker.objects.filter(Q(type='page') | Q(type='quiz') | Q(type='media')) \ .values('uuid') \ .annotate(dcount=Count('uuid')) \ .filter(dcount__gte=2) for index, tracker in enumerate(trackers): print("%d/%d" % (index, trackers.count())) exclude = Tracker.objects.filter(uuid=tracker['uuid']) \ .aggregate(min_id=Min('id')) deleted = Tracker.objects.filter(uuid=tracker['uuid']) \ .exclude(id=exclude['min_id']).delete() print(_(u"%d duplicate tracker(s) removed for UUID %s based on \ min id" % (deleted[0], tracker['uuid']))) """ Remember to run summary cron from start """ if result[0] + trackers.count() > 0: print(_(u"Since duplicates have been found and removed, you \ should now run `update_summaries` … -
Create JSON nested output from two different Django Models
I am a newbie to django-rest-framework and I would like to create a JSON output from by combining two different models data like the input JSON I supply. The models are as below: Banks class Banks(models.Model): country = models.CharField(max_length=255, null=False) bank_name = models.CharField(max_length=255, null=False) min_amount = models.FloatField(max_length=255, null=False Rates class Rates(models.Model): term = models.IntegerField(null=True) band = models.CharField(max_length=255, null=True, blank=True) rate = models.FloatField(null=True) bank = models.ForeignKey(Banks, related_name='rates', on_delete=models.CASCADE, null=True, blank=True) Basically the idea is that banks can have multiple rates for different periods. I created a serializer which allowed me to POST in a nested JSON and it loaded the bank data and rate data properly. Serializer classes as below: class RatesSerializer(serializers.ModelSerializer): class Meta: model = Rates fields = ("id", "term", "band", "rate", "bank") class BanksSerializer(serializers.ModelSerializer): rates = RatesSerializer(many=True) class Meta: model = Banks fields = ("id", "country", "bank_name", "rates", "min_amount") def create(self, validated_data): rates_data = validated_data.pop('rates') bank = Banks.objects.create(**validated_data) for rate_data in rates_data: Rates.objects.create(bank=bank, **rate_data) return bank However I am stuck and do not know how to retrieve say banks and their rates for a specific country. I am posting the following: { "country": "CN", "bank_name": "CNBC", "rates": [ {"term":1, "band":"0-10000", "rate":0.025}, {"term":1, "band":"10000-50000", "rate":0.03}, {"term":1, "band":"50000-100000", "rate":0.035}, {"term":1, "band":"100000-250000", … -
Reverse for 'product' with no arguments not found. 1 pattern(s) tried: [u'products/(?P<product>[-\\w]+)/$']
So, ive been trying to link to a page created in the django admin using the slugField. I have done this before in the same project but for some reason I am getting this error when linking to this one URL. Index File calling the URL {% for item in products %} <div class="col-sm-12 col-md-4 col-lg-4"> <div class="box"> {% if item.image_one %} <div class="image"> <img src="{{ item.image_one.url }}" alt="{{ item.name }}"> </div> {% endif %} <div class="content"> <h4>{{ item.name }}</h4> <a href="{% url 'products:product' item.slug %}" class="button">View Product</a> </div> </div> </div> {% endfor %} urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<product>[-\w]+)/$', views.product, name='product'),] Views.py def product(request, product): product = get_object_or_404(Product, slug=product) return render(request, 'products/product.html',{ 'product':product, }) -
Django showing 500 Internal Server Error on HTTPS
I am getting the following error in error.log in apache2 directory : Segmentation fault (11), possible coredump in /etc/apache2. I have the following configuration in my example-instance.conf : ErrorDocument 404 "/error-pages/404.html" ErrorDocument 500 "/error-pages/500.html" ErrorDocument 403 "/error-pages/403.html" # Change the following three lines for your server ServerName example.app SetEnv HTTP_HOST "example.app" ServerAdmin admin@example.com SetEnv LC_TIME "en_GB.UTF-8" SetEnv LANG "en_US.UTF-8" SSLEngine on SSLCertificateFile "path/to/certificate" SSLCertificateChainFile "path/to/certificate" SSLCertificateKeyFile "path/to/private_key" WSGIScriptAlias /app "path/to/wsgi_prod.py" # Comment next 2 lines if using older Apache than v2.4 WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess instance1_wsgi python-path="__PATH_TO_ENV_SITE-PACKAGES_FOLDER__" WSGIProcessGroup instance1_wsgi # Comment 'Require all granted' for older Apache than v2.4 <Location "/"> Require all granted Options FollowSymLinks </Location> Alias /static/ "path/to/static/" Alias /app/static/ "path/to/static/" <Directory "path/to/static/"> Require all granted Options -Indexes </Directory> Alias /data/ "path/to/data/" <Directory "path/to/data/"> Require all granted Options -Indexes </Directory> ErrorLog ${APACHE_LOG_DIR}/example-instance-error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/example-instance-access.log combined The site worked perfectly fine on http however on configuring it for https, I am getting 500 Internal Server Error. The landing page of the site is perfectly fine, which indicates that https is working. -
Middleware redirect loop: how to check for requested path
I have a custom middleware that checks if the current logged-in user is at the correct sub-domain but it sometimes (not always) gets stuck in a redirect loop.. class TenantUserRedirectMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_superuser: # allow superusers through if request.user.is_authenticated: # check if user is logged in if request.user.tenant != request.tenant: # check if user domain in url return HttpResponseRedirect('//' + request.user.tenant.get_primary_domain().domain + ':8000/login/') else: print('User is logged out') response = self.get_response(request) return response I see another post using request.path to check that the requested path is not the one the middleware is requesting but when I add: if not request.path('//' + request.user.tenant.get_primary_domain().domain + ':8000/login/'): I get: TypeError at /check-phone-verified/ 'str' object is not callable which seems to be another view called after someone logs in. Is the redirect loop caused by the order of operations in the middleware? Being that it goes down to this middleware, gets a redirect, then starts over - causing a loop? -
Specifying a namespace in include() without providing an app_name. Giving app_name also doesn't work
from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from carts.views import cart_home from .views import home_page, about_page, contact_page, login_page, register_page app_name = 'products' urlpatterns = [ url(r'^$', home_page, name='home'), url(r'^about/$', about_page, name='about'), url(r'^contact/$', contact_page, name='contact'), url(r'^login/$', login_page,name='login'), #url(r'^cart/', include("carts.urls"), url(r'^register/$', register_page, name='register'), url(r'^bootstrap/$', TemplateView.as_view(template_name='bootstrap/example.html')), url(r'^products/', include("products.urls", namespace='products')), url(r'^admin/', admin.site.urls), ] Please Help. I am getting this error : 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. -
Why is Python giving me an AttributeError even if I have defined that particular class
I just got started with classed based views in Django. When I try to start the servers, I get this error: path('/', views.FoodDetail.as_view(), name = "detail" ), AttributeError: module 'food.views' has no attribute 'FoodDetail' Here's my code: urls.py from . import views from django.urls import path app_name = 'food' urlpatterns = [ path('', views.IndexClassView.as_view(), name = 'index'), path('item/', views.item, name = 'item'), path('info/', views.info, name = "info"), path('<int:pk>/', views.FoodDetail.as_view(), name = "detail" ), #add form path('add', views.create_item, name = "create"), #edit item path('update/<int:id>/', views.update_item, name = 'update_item'), #delete item path(r'^delete/<int:id>/', views.delete_item, name = 'delete_item') ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Item from django.template import loader from .forms import ItemForm from django.views.generic.list import ListView from django.views.generic.detail import DetailView from djange.views.genereic.edit import CreateView class IndexClassView(ListView): model = Item template_name = 'food/index.html' context_object_name = 'item_list' def detail(request, item_id): item = Item.objects.get(pk = item_id) context = { 'item' : item, } return render(request, 'food/detail.html', context) class FoodDetail(DetailView): model = Item template_name = 'food/detail.html' ... How is it possible that food.views had no attribute called FoodDetail when it is defined in front of my eyes!? -
Pass auth token from Django to React/Redux frontend
My situation is kind of unique. The website I'm working on originally used Django for both frontend and backend. Now, the Django website is also being used as a backend for a React/Redux frontend, and also uses the default Django token authentication for API calls. This is all fine so far. The problem is, I'm trying to make sure the React/Redux application doesn't load unless the user is logged in on the Django website first. Basically you would have to login to the Django website first, in order to access the React/Redux application, otherwise you would be redirected back to the login screen of the Django application. I'm wondering if there is a way to send the current user's Django authentication token through the request, to be received and stored by the React/Redux app in order to make API calls back to the Django application? I've searched up online and all I can find is tutorials using a login page in the React/Redux app which is not what I want. Any help would be appreciated. Thank you! -
SAML error with https url in HUE djangosaml2
I am trying to enable SAML in Hue™ 4.1 and have an error. The issue is the connection goes from https to http as the below setup: user–>https://hue.xyz.com:8889 --> LTM loadbalancer --> http://ip-addr:8889 (no SSL enabled in HUE). The SAML IDP login pages comes up and when trying to login HUE returns error: Bad Request (400) . In the /var/log/hue/runcpserver.log I see below errors. The /saml2/metadata xml shows http not https in the ACS url <md:AssertionConsumerService Binding=“urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST” Location=“http://hue.xyz.com:8889/saml2/acs/” index=“1”/>. Any thoughts? [17/Dec/2019 09:58:58 -0800] response ERROR https://hue.xyz.com:8889/saml2/acs/ not in [‘http://hue.xyz.com:8889/saml2/acs/’] [17/Dec/2019 09:58:58 -0800] views WARNING Invalid SAML Assertion received (unknown error). [17/Dec/2019 09:58:58 -0800] middleware INFO Processing exception: : Traceback (most recent call last): File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/core/handlers/base.py”, line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/db/transaction.py”, line 371, in inner return func(*args, **kwargs) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/views/decorators/http.py”, line 41, in inner return func(request, *args, **kwargs) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/Django-1.6.10-py2.7.egg/django/views/decorators/csrf.py”, line 57, in wrapped_view return view_func(*args, **kwargs) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/djangosaml2-0.16.4-py2.7.egg/djangosaml2/views.py”, line 276, in assertion_consumer_service return fail_acs_response(request, status=400, exc_class=SuspiciousOperation) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/djangosaml2-0.16.4-py2.7.egg/djangosaml2/utils.py”, line 85, in fail_acs_response return failure_function(request, *args, **kwargs) File “/opt/cloudera/parcels/CDH-5.15.1-1.cdh5.15.1.p0.4/lib/hue/build/env/lib/python2.7/site-packages/djangosaml2-0.16.4-py2.7.egg/djangosaml2/acs_failures.py”, line 22, in exception_failure raise exc_class SuspiciousOperation [17/Dec/2019 09:58:58 -0800] access INFO 10.83.175.203 -anon- - “POST /saml2/acs/ HTTP/1.1” returned in 72ms -
How to check user is at correct domain using Django middleware
Using Django middleware to check if logged-in users are at the correct sub-domain (for security reasons) but finding a security issue. First, my middleware: class TenantUserRedirectMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_superuser: # allow superusers through if request.user.is_authenticated: # check if user is logged in if not request.user.tenant.get_primary_domain().domain in request.META['HTTP_HOST']: # check if user domain in url print('Wrong tenant domain: ' + request.user.tenant.get_primary_domain().domain + ' not in ' + request.META['HTTP_HOST']) logout(request) # logout user or redirect to tenant domain else: print('Correct tenant: ' + request.user.tenant.get_primary_domain().domain + ' in ' + request.META['HTTP_HOST']) else: # anonymous user stuff happens here print('User is logged out') response = self.get_response(request) return response Currently this checks: that the user is authenticated that the user's tenant's domain exists in the current URL if it does not then it logs the user out I have a couple questions/issues here: 1.) If we check that the current user's tenant's domain exists in the current URL this way it allows subdomains of similar shorter names to get through. e.g. test.localhost:8000 will work to access information at testing.localhost:8000 because test exists in testing. 2.) How secure is handling access this way? I want all users … -
How do I fix this error in my Django settings.py?
I am trying to make some translations using the i18n. I have imported some libraries in my TEMPLATES in the setting.py file. The problem is that if I import django.core.context_processors.i18n my Iapp shows an error and it wont work. my TEMPLATES in settings.py file TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.i18n', #i18n ], }, }, ] If I import the last line my app shows this error: ModuleNotFoundError at /myapp2/ No module named 'django.core.context_processors' Thank you in advance -
Django mail_admins sending from multiple email backends
I've overwritten the django EmailBackend to use email credentials that are set in a model so that my clients can use their own address to send email out to their customers. I have written this in smpt.py in the same directory as settings.py, and then call it in the settings.py like this: EMAIL_BACKEND = 'smtp.MyEmailBackend' this works and emails are being sent from my client's address. I also have a default hardcoded set of email settings in settings.py, for sending error logs to myself, using the default django email backend: 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'email_backend':'django.core.mail.backends.smtp.EmailBackend', } }, This also works, and my hardcoded email_host is sending me error emails. Problem is that my client's email_host is also sending me error reports, and I can't work out why. Any ideas? -
How can I append a CSV file to an existing zip archive in Python?
I am calling an API which returns a zip file back. Before sending this to the client for download, I want to append a csv file I'm creating to it. Below is how I am creating the CSV and my attempt at appending it, but I just get the error 'bytes' object has no attribute 'seek'. Code to generate CSV in memory transactions_csv = io.StringIO() writer = csv.DictWriter(transactions_csv, fieldnames=all_parsed_transactions[0].keys()) writer.writeheader() for transaction in all_parsed_transactions: writer.writerow(transaction) return transactions_csv Code attempting to append to existing zip export = request.export_data() #This is a zip response transaction_csv = request.export_transactions() #This calls the code above if transaction_csv is not None and export is not None: new_zip = zipfile.ZipFile(export, "a", zipfile.ZIP_DEFLATED) new_zip.write(transaction_csv) new_zip.close() return HttpResponse(new_zip, content_type='application/zip') -
Static files configuration in AWS not working
I currently have an multi-docker container application (nginx, postgres RDS, Django) running on Elastic BeanStalk and I am able to use it but the static files (CSS files and JS scripts) are not loaded. This is my current configuration: nginx setup file user nginx; worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100M; server { listen 80; charset utf-8; server_name mydashboard.com; access_log /dev/stdout; error_log /dev/stdout info; location /media/ { alias /var/www/media/; } location /static/ { alias /var/www/static/; } location / { proxy_pass http://web:8888; proxy_set_header host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } .ebextensions (folder) django.config (file) option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "mydashboard.settings" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: mydashboard/mydashboard/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' If I remove the folder .ebextensions folder and load the app, it will work without displaying the static files but if I add the folder with the django.conf file the app won't deploy and I will encounter the error: Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python:staticfiles', OptionName: '/static/'): Unknown configuration setting. In one post I found (Serving static files in Django) it is mentioned that … -
Getting cannot import name urlresolvers error when running manage.py
I understand that I asked this question an hour or so ago, but it was closed as a duplicate. I have however tried the solutions suggested in the other question, including upgrading my django, making changes to models and utils.py #from from django.core import urlresolvers #to from django.urls import reverse but still getting 'cannot import name urlresolvers' as an error when I try run manage.py runserver. This is the full error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inne r self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\comman ds\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init __.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", lin e 114, in populate app_config.import_models() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python37\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 967, in _find_and_load_unlocked File "<frozen … -
DJango NoModuleFoundError
I'm getting ModuleNotFoundError in my Django project, I have done a lot of research on similar posts and made project relevant changes, but no luck! and unable to resolve the error, so it made me post this. Project structure Screenshot -> Project structure Stacktrace for reference. 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 "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/Users/prithvi/pyhtonprojects/DjangoProjects/doc_app/venv/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, … -
Django ORM left join and group by
I have to do left join and group by using Django ORM. My expected SQL query is SELECT "equipments_heatsmokefixture"."indication_code", t."status", t."remark", "account_account"."first_name", "account_account"."last_name",max(t."create_at") as create_at, "equipments_heatsmokefixture"."page", "equipments_heatsmokefixture"."area_number", "equipments_heatsmokefixture"."soft_area", "equipments_heatsmokefixture"."sub_area" ,count("equipments_heatsmokefixture"."indication_code") as "times" FROM "equipments_heatsmokefixture" LEFT OUTER JOIN "equipments_heatsmokerecord" t ON ("equipments_heatsmokefixture"."id" = t."item_id" AND (t."monthlyset_id" = 8)) LEFT OUTER JOIN "account_account" ON (t."inspector_id" = "account_account"."id") WHERE ("equipments_heatsmokefixture"."effective_date" <= "2019-12-01" AND "equipments_heatsmokefixture"."expiration_date" >= "2019-12-01") GROUP by "equipments_heatsmokefixture"."indication_code" ORDER BY "equipments_heatsmokefixture"."area_number" ASC, "equipments_heatsmokefixture"."soft_area" ASC SQLite return Column and Row Return I have tried different query set allfixture = heatsmokefixture.objects.annotate(t=FilteredRelation('heatsmokerecord', condition=Q(heatsmokerecord__monthlyset=month)),latest=Max('t__create_at')) .values('indication_code', 't__status', 't__remark', 't__inspector__first_name', 't__inspector__last_name','t__create_at','page', 'area_number', 'soft_area', 'sub_area','latest') .filter(effective_date__lte=month.start_date, expiration_date__gte=month.start_date) .order_by('-latest') but Django ORM Group by everything that I don't want except "equipments_heatsmokefixture"."id" SELECT "equipments_heatsmokefixture"."indication_code", t."status", t."remark", "account_account"."first_name", "account_account"."last_name", t."create_at", "equipments_heatsmokefixture"."page", "equipments_heatsmokefixture"."area_number", "equipments_heatsmokefixture"."soft_area", "equipments_heatsmokefixture"."sub_area", MAX(t."create_at") AS "latest" FROM "equipments_heatsmokefixture" LEFT OUTER JOIN "equipments_heatsmokerecord" t ON ("equipments_heatsmokefixture"."id" = t."item_id" AND (t."monthlyset_id" = 8)) LEFT OUTER JOIN "account_account" ON (t."inspector_id" = "account_account"."id") WHERE ("equipments_heatsmokefixture"."effective_date" <= 2019-12-01 AND "equipments_heatsmokefixture"."expiration_date" >= 2019-12-01) GROUP BY "equipments_heatsmokefixture"."id", <<<<<<<<<<<<<<< I only want this line in GROUP BY "equipments_heatsmokefixture"."qr_link", "equipments_heatsmokefixture"."page", "equipments_heatsmokefixture"."area_number", "equipments_heatsmokefixture"."soft_area", "equipments_heatsmokefixture"."indication_code", "equipments_heatsmokefixture"."area_id", "equipments_heatsmokefixture"."sub_area", "equipments_heatsmokefixture"."effective_date", "equipments_heatsmokefixture"."expiration_date", t."status", t."remark", "account_account"."first_name", "account_account"."last_name", t."create_at" ORDER BY "latest" DESC I tried annotate values annotate and then values allfixture = heatsmokefixture.objects.annotate(t=FilteredRelation('heatsmokerecord' , condition=Q(heatsmokerecord__monthlyset=month))) .values('indication_code','page', … -
Launching celery task_monitor in django
Looking at the celery docs i can see that the task monitor is launched in a script (see below). In an implementation of django (as is my understanding), this won't be the case, as I'll have to launch the task monitor in a thread. Currently I'm launching the monitor the first time i run a job, then checking its state each subsequent time i run a job (see further below). This seems like a bad way to do this. What is the correct way to instantiate the task monitor for celery in a django project? It seems I'm missing something really obvious. # docs example from celery import Celery def my_monitor(app): state = app.events.State() def announce_failed_tasks(event): state.event(event) # task name is sent only with -received event, and state # will keep track of this for us. task = state.tasks.get(event['uuid']) print('TASK FAILED: %s[%s] %s' % ( task.name, task.uuid, task.info(),)) with app.connection() as connection: recv = app.events.Receiver(connection, handlers={ 'task-failed': announce_failed_tasks, }) recv.capture(limit=None, timeout=None, wakeup=True) if __name__ == '__main__': app = Celery(broker='amqp://guest@localhost//') # LAUNCHED HERE my_monitor(app) # my current implementation # If the celery_monitor is not instantiated, set it up app = Celery('scheduler', broker=rabbit_url, # Rabbit-MQ backend=redis_url, # Redis include=tasks ) celery_monitor = … -
How to send real time data from django mqtt to React?
developers. I'm developing arbitrage system in Django-React stack development now. I can take realtime data through mqtt from arbitrage engine, but I don't know how to send this data to React. If you are experienced in this problem, please help me. -
Adding a specific quantity of the product to the cart in django
I have a problem because I have no idea how to implement 'adding a specific amount of product to cart'. Currently, after pressing the 'Add to cart' button, a single quantity of product is added. cart/views.py except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() I don't know how to relate to this in the view and the template. cart/views.py def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() return redirect('cart:cart_detail') cart/models.py class Cart(models.Model): cart_id = models.CharField(max_length=250, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() active = models.BooleanField(default=True) class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product templates/shop/product.html <div class="float-right"> <div class="float-left"> <input type="number" value="1" aria-label="Search" class="form-control" style="width: 100px"> </div> <a class="btn send-click btn-md my-0 p" href="{% url 'cart:add_cart' product.id %}">Add to Cart</a></div>