Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Graphql middleware decode token
In my project I use Django and GraphQl for building API. The user will be authenticated by API Gateway in AWS, and send to backend an JWT token, with uuid username body, included in the request headers. I need to decode that token and get an username value, that will be next used in the resolvers. I planned to use something similar as G object in Flask or something similar using Rack (Djangos middleware) https://github.com/RenoFi/rack-graphql#example-using-context-handler-for-jwt-authentication but I'm struggling how to do it in Django. Do you have any ideas? -
Annotate queryset with count of elements from another queryset
I have two models connected to User model: class Comment: author = FK(User) ... class CourseMembership: user = FK(User, unique=True) ... I want to annotate each item in CourseMembership.objects.all() with number of comments created by corresponding User. I tried something like this: course_comments = Comment.objects.filter(author=OuterRef("user")) cm = CourseMembership.objects.annotate(comments_count=Count(Subquery(course_question_comments))) but I receive only errors. Can someone help me? -
Same databses for ruby and django
I have same database for ruby and django. Ruby stores user data using bycrypt algorithm(i.e using devise gem): ex : $2a$10$5JhrmU73vXEJWyoBQqYaKeM6a5KwxTfTrfARJmyyl.E8Tir3Q0nlG But to authenticate same user in django,my django bicrypt algorithm should also output same text that is: $2a$10$5JhrmU73vXEJWyoBQqYaKeM6a5KwxTfTrfARJmyyl.E8Tir3Q0nlG. How to do this? It's exactly opposite of this question: Migrate django users to rails -
when a user creates an account,how do i convert the email to all lower case before saving to models?
class GetLoanRepaymentHistoryView(ListAPIView): """Get all loan repayment history.""" serializer_class = LoanRepaymentSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, AdminDashboardPermission,) class GetLoanRepaymentHistoryView(ListAPIView): """Get all loan repayment history.""" List item serializer_class = LoanRepaymentSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, AdminDashboardPermission,) def get_queryset(self): try: loan = Loan.objects.get(id=self.kwargs.get('id')) except Loan.DoesNotExist: return Response({'non_field_errors': ['Loan does not exist']}, status=status.HTTP_404_NOT_FOUND) return LoanRepayment.objects.filter(loan=loan) -
How to construct a Django model that is purely made from other models related by ticker?
How to make up a "parent" model that is solely composed of other models ? I am currently thinking to use foreignkey relationships but I don't believe this is the right way to do so. class BalanceSheet(models.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="balance_sheets" ) assets = models.ForeignKey(Assets, on_delete=models.CASCADE) liab_and_stockholders_equity = models.ForeignKey(LiabAndStockholdersEquity, on_delete=models.CASCADE) def __str__(self): return f"{self.ticker} Balance Sheet" class Assets(model.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="assets") balance_sheet = ???????????????????????????? class Assets(model.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="liab_and_stockholders_equity") balance_sheet = ?????????????????????????? -
CV2.VideoCapture(0) is not working for Django+openCV deployment on AWS EC2
I am building face recognition web application using Django and opencv. I have trained ML models. In my development stage i am able to access webcam with cv2.VideoCapture (0). But while i am deployed on AWS. I can't able to get any response from cv2.VideoCapture() . Is there anyway i can get access to user's device webcam when someone visit my website? -
How can i package a fully developed django project and make it installable
I have a fully developed Django python projects that I can install on windows using xampp or wamp and I have a custom browser developed for it using pyqt5, but I want to automate the configuration of the Django app with the following process: Create a .exe file in which a user can click and its will perform the following function in the background download the code from Github using git clone check if python is installed on the system if yes install virtualenv create a virtualenv and install the project requirement file run python manage.py migrate run python manage.py collect static -
Setting up same env variable with different values in different supervisord process
I have two django projects running in same vm, but both apps got crontab requirements. So i created separate worker and beat conf file supervisord place. But i need to export DJANGO_SETTINGS_MODULE value to different in different process. Like below 1.[supervisord] environment=DJANGO_SETTINGS_MODULE='***.settings.azure' [program:coursecelerybeat] directory=/home/***/***/ command=/home/***/***/bin/celery beat --app=***.celery --loglevel=INFO 2.[supervisord] environment=DJANGO_SETTINGS_MODULE='***.settings.azure' [program:usercelerybeat] directory=/home/***/***/ command=/home/***/***/bin/celery beat --app=***.celery --loglevel=INFO In the place ***, i need to add concerned project folder name. But if i set, it's added permanantely. So it's not working as expected. The same problem happened while gunicorn setup time, but in gunicorn we have environmentfile option. That resolved my problem. But in my supervisord, i'm not able to find anything like that. -
Why Heroku won't start the server?
I uploaded the application to heroku, did the migration but when I run heroku open it gives me an error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I checked the log and here is the answer 2020-08-30T14:00:17.028467+00:00 app[web.1]: ModuleNotFoundError: No module named 'myfist' 2020-08-30T14:00:17.028793+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [11] [INFO] Worker exiting (pid: 11) 2020-08-30T14:00:17.135517+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [4] [INFO] Shutting down: Master 2020-08-30T14:00:17.135762+00:00 app[web.1]: [2020-08-30 14:00:17 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-08-30T14:00:17.263710+00:00 heroku[web.1]: Process exited with status 3 2020-08-30T14:00:17.339367+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-30T14:00:18.000000+00:00 app[api]: Build succeeded 2020-08-30T14:01:05.766286+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sheltered-reef-33234.herokuapp.com request_id=0c2820c9-774c-4b3d-86c4-c53e2531f986 fwd="188.163.103.167" dyno= connect= service= status=503 bytes= protocol=https 2020-08-30T14:01:06.363461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sheltered-reef-33234.herokuapp.com request_id=b16b581b-fce7-4dce-bfdd-8707f4ec2433 fwd="188.163.103.167" dyno= connect= service= status=503 bytes= protocol=https But when I run on the local server everything works Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 30, 2020 - 19:01:48 Django version 3.0.3, using settings 'myfirst.settings' Starting development server … -
How to display data from celery task into django template
I am working on a django project. In the project, I am scraping some data from a website and storing the results into a django model. I want to now display this data in a django template as and when it is saved in the model. this is my code so far mainapp/views.py from django.shortcuts import render from .tasks import get_website from .models import Articles def index(request): if request.method == 'POST': website = request.POST.get('website') title = request.POST['title'] author = request.POST['author'] publish_date = request.POST['publish_date'] get_website.delay(website, title, author, publish_date) return render(request, 'output.html') return render(request, 'index.html') def output(request): return render(request, 'output.html') in the index page, I have a form which when submitted starts the scraping process through the celery task get_website(). mainapp/tasks.py @shared_task def get_website(website, title, author, publish_date): ... return save_function(article_list) @shared_task(serializer='json') def save_function(article_list): print('saving extracted data') new_count = 0 for article in article_list: try: new_article = Articles( Title = article['Title'], Link = article['Link'], Website = article['Website'], Author = article['Author'], Publish_date = article['Publish_date'], ) new_count += 1 new_article.save() except Exception as e: print(e) break return print('finished') All of the scraped data is stored in a list article_list and is passed to save_function() to save the data into the django model Articles. I want … -
Incorrect padding
If I would like to go my site and type any of these: www.example.org, example.org, http://example.org, https://example.org, example... I have no problem transferring to my site using internet explorer, google, opera, edge... But, if I open Google (sometimes on the phones using Google too) and type www.example.org, it gives me following: Error at /my_site/ Incorrect padding Request Method: GET Request URL: http://www.example.org/my_site/ Django Version: 3.1 Exception Type: Error Exception Value: Incorrect padding Exception Location: /usr/local/lib/python3.8/base64.py, line 87, in b64decode Python Executable: /home/mysiteorg/pro/my_project/bin/python3 Python Version: 3.8.5 I have no idea what to do with it... Any help, please! Thank you!!! -
found problem Django data transfer by render request to template
I have tried a several times but can't find anything wrong. Here is my code. [This is from views.py][1] [1]: https://i.stack.imgur.com/l0d4a.png This is from html file. -
query ForeignKey of model
**I want get all orders of customer whose id = 3 ** ---------------------------------------------------------------- class customer(models.Model): name = models.CharField(max_length=200,null= True) phone = models.CharField(max_length=200,null= True) email = models.CharField(max_length=200,null= True) date_created = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class order(models.Model): STATUS = ( ('pending','pending'), ('out for delivery','out for delivery'), ('deliveried','deliveried') ) date_created = models.DateTimeField(auto_now_add=True,null=True) status = models.CharField(max_length = 200 , null=True,choices=STATUS) customer= models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product = models.ForeignKey(product,null=True,on_delete=models.SET_NULL) -
Add custom field to Django Admin authentication form
I'm Building an application where the auth process has three fields. subdomain username password Each subdomain defines an isolated space and the username is unique only inside its subdomain For example: the subdomain foo.bar.com has the user jhon_doe with the password secret. It may exists another jhon_doe but in other subdomain. So ... I've created a custom backend authentication and it works well. The problem is that the login Django Admin form have username and password fields by default. I would like to implement a custom Django Admin login form with subdomain username and password fields. -
Using Google docs api with django
Im trying to integrate goofle docs api with django app so that uploaded files can be edited and new files can be created.But im not able to integrate the same .Please Help! -
SSL Bad Handshake, Unexpected EOF when communicating with Sentry
I have been having issues integrating Sentry into a Django application. When I run the application locally with Sentry configured in settings.py (imported and initialised with a modern-style DSN) everything works perfectly with all errors showing up on Sentry as expected. However, when running the application on a server it is rare for errors encountered to actually be reported to Sentry, but it does happen occasionally. Looking at the logs for the docker container the application is running in, I can see the following SSL error occasionally appearing shortly after an error is expected to appear on Sentry (although this doesn't happen very often or account for all the times the error doesn't appear on Sentry): Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')",),)': /api/<hidden_sentry_id>/store/ This is how I have carried out the Sentry initialisation: sentry_sdk.init( dsn="https://<hidden>@<hidden>.ingest.sentry.io/<hidden>", environment="dev", integrations=[DjangoIntegration()], traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True ) With different settings.py files used depending on the environment. Only the value for "environment" has been changed in the configuration on the server. Does anybody have any advice on how … -
django-tables2 Set Column style when using fields of subclasses
I have two Models: from django.db import models class Model1(models.Model): name = models.CharField(max_length = 200) def status(self): return self.model2_set.first() class Model2(models.Model): fe = models.ForeignKey(Model1, on_delete=models.CASCADE) boolean1 = models.BooleanField() boolean2 = models.BooleanField() string1 = models.CharField(max_length=17) Now I want to have a table get all the information just from the Model1 class and set boolean1 and boolean2 as columns.BooleanColumn. My table class looks like this: class Model1Table(django_tables2.Table): class Meta: model = Model1 template_name = "django_tables2/bootstrap.html" fields = ('name', 'status.boolean1', 'status.boolean2, 'status.string1', ) If field would just contain boolean1 i could set boolean1 = django_tables2.columns.BooleanColumn(null=True). If I do this with status.boolean1 it won't work because status is not defined and therefore has no field boolean1. How can I set the column to a boolean column in this case? -
Django - Store list in one model and set values of list in another model
I'm new to Django and a bit confused to how to go about this... I have two models: variant and item. I want the variant to have a list/JSON/w.e that stores "options" - you can also think of this as modifications to each different variant. E.g. class Variant(models.Model): ... options = ArrayField( ArrayField( models.CharField(max_length=100, blank=True), size=20 ), size=20, null=True ) result: ['mod1', 'mod2'] I now want to grab these options and store a bool/Int/w.e. to declare on or off. However, I'm unsure how to reference the Variant.options as choices or what model to use for my item. -
ModuleNotFoundError in django when adding app
Django can't find my app and it shows me "ModuleNotFoundError" when I try to run server my web this is my setting.py : INSTALLED_APPS = [ ...... 'djmoney', 'transition', --> this is my app ] and this is the complete error : Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'transition' -
Django APPS.PY ignored by Apache2
I have a function in apps.py set to run at Apache boot/restart, however it doesn't and it only works after I pull up the index page. However, if I use Django's development environment it works perfectly. APPS.PY from django.apps import AppConfig class GpioAppConfig(AppConfig): name = 'gpio_app' verbose_name = "My Application" def ready(self): from apscheduler.schedulers.background import BackgroundScheduler from gpio_app.models import Status, ApsScheduler import gpio_app.scheduler as sched import logging logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) sched.cancel_day_schedule() sched.get_schedule() sched.daily_sched_update() sched.add_status_db() MOD_WSIG 000-default.conf is as follows: <VirtualHost *:80> ServerName 127.0.0.1 ServerAlias localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /robots.txt /path/to/mysite.com/static/robots.txt Alias /favicon.ico /path/to/mysite.com/static/favicon.ico Alias /static /home/pi/poolprojectdir/static <Directory /home/pi/poolprojectdir/static> Require all granted </Directory> <Directory /home/pi/poolprojectdir/poolproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess poolproject python- home=/home/pi/poolprojectdir/venv python-path=/home/pi/poolprojectdir WSGIProcessGroup poolproject WSGIScriptAlias / /home/pi/poolprojectdir/poolproject/wsgi.py Any ideas as to how I get apps.py recognised by Apache2? -
djnago with google smtp [Errno 11001] getaddrinfo failed
in my settings.py EMAIL_HOST = 'smtp.google.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '*********@gmail.com' EMAIL_HOST_PASSWORD = '************' EMAIL_USE_SSL = True in views.py def sendEmail(request, order_id): order = Inventory_Order.objects.get(id=order_id) orderitems = Order_Item.objects.filter(order=order) try: subject = f"Wiss - New Order {order}" to = [f'{order.customer.email}'] from_email = settings.EMAIL_HOST_USER order_information = { 'order':order, 'orderitems':orderitems } message = get_template('Inventory_Management/email.html').render(order_information) msg = EmailMessage(subject, message, to=to, from_email=from_email) msg.content_subtype = 'html' msg.send(fail_silently=False) print(f'message sent to {order.customer.email}!') except IOError as e: print('Failed') print(e) return e when i call the function i get the following error [Errno 11001] getaddrinfo failed, What's The Problem? Any Help is Appreciated... -
Queryset of model instances based on related model
I've got two models. class Color(models.Model): name = models.CharField(max_length=120, null=True, blank=True) class Car(models.Model): user = models.ForeignKey(Color, on_delete=models.CASCADE, default=None) price = models.DecimalField(max_digits=10, decimal_places=2) How can I get a queryset of Color instances where the Car instances that are related to those Color instances have a price > 1000? Thanks! -
Can't give css class to django error message
I'm trying to format my Django error messages with some css, but i just can't seem to apply it. (The CSS file is added correctly I applied other classes from it, those work just fine). The strange thing about it is that if i try to apply a class from bootstrap like "alert-danger" that works just fine Here's my html code: {% for field in form %} <div class="asd">{{ field.errors}}</p> {% endfor %} And the css as well .asd{ font-size: 1rem; margin-left: 20px; } -
regex query does not work with django-MYSQL
on development I use the default sqlite and I have no issues. this is how I build the query: def similar_names_filter(queryset: QuerySet, name_field: str, name_value: str): filter_key = name_field+"__regex" filter_value = r"{}(?: \([0-9]+\))?".format(name_value) return queryset.filter(**{filter_key: filter_value}).values_list(name_field, flat=True) but on production where we use mysql it does not work and produces the following message: (1139, "Got error 'repetition-operator operand invalid' from regexp") What am I missing? Thanks in advance -
Elasticsearch with Django: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError
I try to itergrate elasticsearch in django project. But when I execute command python manage.py search_index --rebuild it made this error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fde186b2b50>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fde186b2b50>: Failed to establish a new connection: [Errno 111] Connection refused) After run docker-compose, I can access to elasticsearch http://localhost:9200 via chrome. This is setting.py file: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_elasticsearch_dsl', ] ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } And document.py file: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Question @registry.register_document class QuestionDocument(Document): class Index: #name of elasticsearch index name = 'questions' setting = { 'number_of_shard' : 1, 'number_of_replicas' : 0} class Django: model = Question fields = [ 'question_text', 'pub_date', ] How can I resolve it?