Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to architecture a Python Backend with constant Background Taks
i would like to design a Python Backend where i have one Task that is running the whole time logging data from several Serial ports. Also there should be other background tasks running when there are certain request and they would accedd the data from the constant background task (maybe over an db). So there are some questions: I have a little experience in Flask so i would like to use it, but i stumbled across FastAPI which has backgroundjobs already implemented. So which Framework would you recommend? For the background tasks or threads what is the best Solution? Celery? Or should i outsource the constant background task to its own standalone python app? Thanks for your help! -
Django - How to import a model from another app into another app's views
I am working in an app called 'lineup', and I have another app called 'market' that has a model called 'Inventory' which I need to import into the lineup app's views.py How can I do that? -
TypeError: unsupported type for timedelta hours component: NoneType
I am getting this error in production (heroku/postgres) but not in local(sqlite). class ModelC(models.Model): model_c_field_1 = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) class ModelB(models.Model): model_c_field_2 = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) model_c_field_1= models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) def function(request, userprofile_id): latest_model_object = ModelB.objects.filter(user=userprofile_id).order_by('-id')[:1] time_delta = () for ModelB in latest_model_object: time_delta = timezone.now() - modelb.created_at time_delta_rule = ModelC.objects.filter(venue=request.user.userprofile.venue) timedelta_test=timedelta() for ModelC in time_delta_rule: timedelta_test = timedelta(hours = ModelC.timeframe) print(timedelta_test) examples of print result: 0:00:00 or 1 day, 0:00:00 Giving the below error. 2023-04-14T04:26:40.379344+00:00 app[web.1]: timedelta_test = timedelta(hours = modelc.timeframe) 2023-04-14T04:26:40.379344+00:00 app[web.1]: TypeError: unsupported type for timedelta hours component: NoneType -
How to use a dictionary with annotate in django?
I have a model: class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) and a dictionary: sample_dict = { 1: 'A', 2: 'B', 3: 'C' } I tried to use annotate like below: hero = Hero.objects.annotate(sample_id=Value(sample_dict[F('id)], output_field=CharField())) but there is an key error <django.db.models.expressions.Subquery object at 0xffff8d014438> I want to use value of field 'id' of Hero model as a key of sample_dict. but Subquery does not return a value. -
Email verification error in Django registration
I am creating an application using Django. The user registration page includes email verification, but I am encountering an error here. When a user registers for the application by providing their email address and password, an email verification is triggered, and a verification code URL is sent to the user's email from the Django application. However, when the user clicks on this URL, an ERR_CONNECTION_TIMED_OUT error occurs. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Displaying nested dictionary data without known key names in html table using Django
Using Django 3.0.6 I am trying to display this dictionary in a html table. data = { 'Exception': { 'business': { 'Renewed': 73, 'Manual': 15, 'Automatic': 3}, 'Aviation Sector': { 'Automatic': 6, 'Renewed': 6, 'Manual': 2} } } The names of these values (for easier understanding) are: Task is 'Exception' Products are 'Business', 'Aviation Sector' Classifications are 'Renewed', 'Manual', 'Automatic' And the numbers are how many times that classification occurred for that Product. I need the table to look like the attached image WITHOUT hardcoding any of the values as the values will change every time the function pulls new data. I can modify the dict if needs be before sending to the html page. The code that creates the initial dict is set up so if a different type of 'Task' were pulled in the query it would be the main key for another set of key values so the table html code would create a second table under the first with the same format just different task name. I cannot upgrade my version of django and I cannot use template filters that are not standard with Django. Here is what the table should look like Ive tried too … -
Page not found 404 Django The current path , didn’t match
I tried to run Django for the first time and got this Request Method: GET Request URL: http://127.0.0.1:8000/hello/new Using the URLconf defined in test.urls, Django tried these URL patterns, in this order: hello/ [name='index'] hello/ [name='new'] admin/ The current path, hello/new, didn’t match any of these. hello/views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("hello, 1") def new(request): return HttpResponse("hello, 2") hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('', views.new, name='new') ] urls.py in my project directory urlpatterns = [ path('hello/', include('hello.urls')), path('admin/', admin.site.urls) ] -
How to login with multiple email addresses when using django-allauth
I have a django project with the django-allauth app. I want to authenticate by username or emailA or emailB. I set ACCOUNT_AUTHENTICATION_METHOD to username_email and I confirmed that I can authenticate by username or email address. Reading the documentation, it looks like I can use ACCOUNT_MAX_EMAIL_ADDRESSES, but I don't know how to use it. the documentation django-allauth: ACCOUNT_MAX_EMAIL_ADDRESSES(=None) The maximum amount of email addresses a user can associate to his account. It is safe to change this setting for an already running project – it will not negatively affect users that already exceed the allowed amount. Note that if you set the maximum to 1, users will not be able to change their email address as they are unable to add the new address, followed by removing the old address. I am new to django and am struggling with this. Can someone provide an example? -
django - Load template and add a load spinner while Django data is loading
When I open my Django project, I want first to load body.html and then dashboard.html. dashboard.html is a heavy file as its working with python dataframes in the script tag. So first I want to display body.html and once body.html is render, add a load spinner while dashboard.html and its python Django data are loading This actual code is not showing the Highcharts data as the body Class (DashboardGraphs) does not contain the Django data so there's no data for show in body.html So, the question is how can I load first body.html AND then dashboard.html which Is inside body.html (dashboard-container). With the code I showed, that Is happening but the charts are not showing data. Thanks. # urls.py ########################################## path('dashboard_graphs', DashboardViewFinal.as_view() , name='dashboard_graphs'), path('dashboard', DashboardGraphs.as_view() , name='dashboard'), # views.py ########################################## class DashboardViewFinal(LoginRequiredMixin, TemplateView): def __init__(self): self.dashboard_view_23 = DashboardView(2023,'2023') self.year_int_2023 = 2023 self.year_str_2023 = str(2023) self.dashboard_view_22 = DashboardView(2022, '2022') self.year_int_2022 = 2022 self.year_str_2022 = str(2022) template_name = 'dashboard.html' @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) # ----------------------------------------------- # Conexion con HTML # ----------------------------------------------- def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['panel'] = 'Panel de administrador' context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['alumnos_mens_total_valor_2022'] = self.dashboard_view_22.get_graph_alumnos_mensual() context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total() context['ingresos_total_2022'] = self.dashboard_view_22.get_ingresos_total()[0] context['egresos_total_2022'] … -
Django dictionary key value access
I got the below response via api to a text field, how can I access the pin and reference no.. I tried separating it but it's not looking safe I want to be able to access the pin with key "pin" Thanks in anticipation { "success":"true", "message":"E-pin was Successful", "pin":"1211ggg3322", "amount":775, "transaction_date":"29-03-2023 12:18:33 pm", "reference_no":"I11767", "status":"Successful" } -
Django: how to generate random number inside a slug field
I have a model called Product, when the user create an objects inside a Product model, I want to generate some random number inside a Product model field Slug like this: https://stackoverflow.com/questions/76010275/cryptography-python-installation-error-with-rush-airgapped-installation Take a look at this Stack Overflow question, you may see the domain name at first, and some path name called questions, and some random number at the end of the questions, I think it should look like this in django path: path('question/random_number/<slug:slug>/', views.some_views_name, name='Redirect-name') All the examples i found in the internet does not do something like this, so how can i do this in django? model: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(upload_to='product-image') price = models.FloatField(max_length=11) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(max_length=100, unique=True) def get_user_public_url(self): return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return str(self.user) -
Nested Relationships in DRF Serializers
AttributeError at /api/register/ Got AttributeError when attempting to get a value for field user_profile on serializer UserRegistrationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserProfile instance. Original exception text was: 'UserProfile' object has no attribute 'user_profile'. UserProfile model looks like this from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE) date_of_birth = models.DateField() phone_number = models.CharField(max_length=20, blank=False) is_phone_verified = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) phone_code = models.CharField(max_length=20, blank=False) email_code = models.CharField(max_length=20, blank=False) serializers.py file looks like this from django.contrib.auth.models import User from .models import UserProfile from django.core.exceptions import ValidationError from datetime import datetime from rest_framework.validators import UniqueValidator from rest_framework import serializers from django.core import validators class UserModelSerializer(serializers.ModelSerializer): first_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) last_name = serializers.CharField( required=True, max_length=50, error_messages={ 'required': 'Please enter your name.', 'max_length': 'Please enter a valid name.' } ) username = serializers.CharField( required=True, max_length=30, validators=[UniqueValidator(queryset=User.objects.all())], error_messages={ 'required': 'Please enter a username.', 'max_length': 'Username should be no more than 30 characters.', 'unique': 'This username is already taken. Please choose a different one.', } ) email = serializers.EmailField( … -
Using dynamic select2 field within formsets in Django
I use django-formset-js-improved which works nicely to add, delete and reoreder my formsets. However, I would like to have a dynamic select2 formfield. I looked into different packages (i.e. django-autocomplete, django-select2), but they seem to work with forms. I was thinking of getting the form fields id, by listening on the trigger 'formAdded' and working from there. However, this seems not to be fired (see: django-formset-js-improved not firing 'formAdded' event). Any idea on how to solve this? -
Can't find sqlite version 3.9 or greater for djano install
I tried installing Django on my AWS linux AMI machine. Right off the bat, I got errors that the current version of Django required sqlite version 3.9 or greater. So I went about trying to install a version of sqlite that matched the requirements, but had no luck. So, to get around the issue, I downgraded the Django version to 2.15 which was compatible with the version of sqlite and everything worked just peachy. Then I wanted to add bootstrap to the project, so I installed with the following command: pip install django-bootstrap3 That package required a later version of Django, so it uninstalled 2.15 and installed Django 3.2.18. When I try to run the server, I get the that incompatiblity message with the Django version and sqlite. (By the way, the exact version of bootstrap was 3-23.1) I am able to install sqlite via pip: pip install db-sqlite3 But that gives me something earlier than 3.9 which is needed. So, I could either find an earlier version of bootstrap that works with Django 2.15, or find a later version of sqlite. Obviously the best fix would be to get a more current version of sqlite. Any suggestions? Thanks -
django-formset-js-improved not firing 'formAdded' event
I use django-formset-js-improved to dynamically add, delete and reorder formsets. All works fine, except for the event 'formAdded' appears not to be triggered. I copied the script from the GitHub repo (https://github.com/pretix/django-formset-js/blob/master/example/example/templates/formset.html): <script> jQuery(function($) { $('#formset').formset({ 'animateForms': true, 'reorderMode': 'animate' }).on('formAdded', function() { console.log("Form added", this, arguments); }).on('formDeleted', function() { console.log("Form deleted", this, arguments); }); }); </script> However, nothing is logged to the console on 'add' or 'delete'. Am I missing something? -
Python Django templates not found
I'm having trouble with connecting django templates. django.template.loaders.filesystem.Loader: E:\CS\Udemy\Python and Django Full Stack\Django\charity\templates\posts\post_base.html (Source does not exist) Actually it has to be charity\posts\templates\post_base.html In my settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") MEDIA_DIR = os.path.join(BASE_DIR, 'media') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'posts', 'comments', 'rest_framework', 'bootstrap4', 'django.contrib.humanize', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'django_session_timeout.middleware.SessionTimeoutMiddleware', # 'charity.middleware.SessionExpiredMiddleware', ] ROOT_URLCONF = 'charity.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], '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', ], }, }, ] What I expected is django loads templates in a separate app. -
Image in HTML isn't displayed using Flask
So I tried to display all images in my directory with flask on a website but all I get is the raw HTML code () This is a cut down version of my code import flask import os import sqlite3 app = flask.Flask(__name__) @app.route("/") def pic(): base_path = "uploads/" image_extensions = ['.jpg', '.jpeg', '.png', '.gif'] images = [] for file_name in os.listdir(os.path.join(base_path)): if file_name.lower().endswith(tuple(image_extensions)): file_path = os.path.join(base_path, file_name) images.append(f'<img src="{file_path}" width="150" height="150">') #<a href="{file_path}" target="_blank"> return flask.render_template('x.html', images=images) app.run(port=8000, debug=True) and this the html part <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <table> <tr> {% for image in images %} <td>{{ image }}</td> {% endfor %} </tr> </table> </body> </html>``` -
How to reference a Many to Many field in django that takes various Users
Im building a Django model for creating Polls with various users where they can invite each other. Models.py class Participant(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) class DateTimeRange(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() class AvailabilityPoll(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) duration = models.TimeField() datetime_ranges = models.ManyToManyField(DateTimeRange, related_name='datetime_ranges') deadline = models.DateTimeField() participants = models.ManyToManyField(Participant, related_name='participants') def is_expired(self): return self.deadline <= timezone.now() def get_participant_count(self): return self.participants.count() I made a view and a serializer for a POST api using Django Rest Framework to create this view: Views.py class AvailabilityPollView(APIView): permission_classes = (IsAuthenticated, ) serializer_class = AvailabilityPollSerializer @swagger_auto_schema(request_body=serializer_class, responses={201: serializer_class}) def post(self, request): poll = request.data serializer = self.serializer_class(data=poll) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model from polls.models import AvailabilityPoll, DateTimeRange User = get_user_model() class ParticipantsSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email'] class DateTimeRangeSerializer(serializers.ModelSerializer): class Meta: model = DateTimeRange fields = '__all__' def create(self, validated_data): range = DateTimeRange.objects.create(start_time=validated_data['start_time'], end_time=validated_data['end_time']) range.save() return range class AvailabilityPollSerializer(serializers.ModelSerializer): datetime_ranges = DateTimeRangeSerializer(many=True) participants = ParticipantsSerializer(many=True) class Meta: model = AvailabilityPoll fields = '__all__' def create(self, validated_data): datetime_ranges_data = validated_data.pop('datetime_ranges') participants_data = validated_data.pop('participants') poll = AvailabilityPoll.objects.create(**validated_data) for range in datetime_ranges_data: poll.datetime_ranges.add(DateTimeRangeSerializer.create(self, validated_data=range)) for participant in participants_data: user = … -
What does the DJANGO_TEST_RANDOM_STATE environment variable do?
I'm not able to find anything on the DJANGO_TEST_RANDOM_STATE environment variable in Django's official docs. What is this environment variable used for? -
Basic conceptual question about ending a chatbot function/process with python / django
I'm creating a chatbot in django (using django for frontend and backend). My frontend calls this django function (in views.py, views.start_convo) to start the chatbot. This works fine. However, I also want to be able to send a request to STOP the chatbot. I'm not sure the best way to implement this functionality. Also, Latency is also very important to me, so I don't want the loop to waste much time checking something. Thoughts on the best way to approach / re-architect for this? Some ideas I've thought through / have: Use a global variable for start/stop, so instead of 'while True:', change to 'while_my_global_variable is True:'. Send a request from my frontend javascript that edits the global variable. This seems back because it is not thread safe for multiple users. Have the start_convo and stop_convo requests update a database with a boolean on whether to continue or not, and change 'while True:' to check that database row for whether the conversation should stop. Something with async / await, but I couldn't figure out how to set that up to do what I wanted. Ideally, send some time of signal to kill the function immediately (as opposed to the function … -
Django + Vite + Vue with Router does not work
I am trying to run the basic Vite default app with router to run a vue 3 front end along with Django. However I am receiving the following error which generally doesn't come when running only a Vite with vue router app. Uncaught SyntaxError: Unexpected token 'export' (at index-2331cb67.js:5:33627) Uncaught SyntaxError: Cannot use import statement outside a module (at AboutView-d0a85a00.js:1:1) I have updated the code here. Please guide. -
python manage.py migrate --fake-initial errors on initial migration
I have a new Django app pointing to an existing django database and so I want to skip some initial migrations. However, even running fake-initial still tries to run the initial migrations: raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration donate.0001_initial is applied before its dependency campaign.0003_remove_medicalcenter_npi_num_and_more on database 'default'. What's the point of python manage.py migrate --fake-initial then?? -
Used code found here for django site for encryption. But I don't get any data
I am calling a module I wrote in python to generate some data that I need to pass to a user. When I call that module it works fine, except when I run it via the django framework. When I run it under django I get an error that the data set is empty. I checked the variables and there is indeed data there, however, when I try to get the first block of data it yields an empty data set: block_size 16 cipher <Crypto.Cipher._mode_cbc.CbcMode object at 0x7f0cd9dff940> data ['\x13\x91Õ\x13Ïßû!-\x02&[èWÒ\x8e'] enc b'\x13\x91\xd5\x13\xcf\xdf\xfb!-\x02&[\xe8W\xd2\x8e' self <btc_leak_app.scripts.mymodule.AESCipher object at 0x7f0cd9dbc910> to_decrypt b'' Here is the code in question: class AESCipher(object): def __init__(self, key): self.bs = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(bytes(iv.decode("latin-1") +";;;;"+ cipher.encrypt(raw.encode()).decode("latin-1"), "latin-1")) def decrypt(self, enc): enc = base64.b64decode(enc).decode("latin-1") data = enc.split(";;;;") iv = data[0].encode("latin-1") enc = data[1].encode("latin-1") cipher = AES.new(self.key, AES.MODE_CBC, iv) to_decrypt = enc[AES.block_size:] return self._unpad(cipher.decrypt(to_decrypt)).decode('latin-1') def _pad(self, s): return str(s, "utf-8") + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) @staticmethod def _unpad(s): print("unpad", s) return s[:-ord(s[len(s)-1:])] Lastly, I'm going to link where I got the code from -
Can my django website run other scripts that interact with the same database?
I am wanting to run another script (from within the django app?) that can parse some text files to put values into the mysql database my django website uses. Then a webpage loads it would grab those values and display them. I am not sure the right way to go about this, ideally I can just create a python script that runs as a cron job and does standard mysql stuff to get and change the data in the same table the django app reads, or is there a more django way to do this? from within the django app? I am not sure how to run scripts 'on the side' or 'like a cron job' from within django. -
Performance issues when using Solr, Django-Haystack, and standard Django filter query
I am working with Solr via Django-Haystack to refine a basic Django queryset by text-searching a large data table. My primary database is postgresql. I have approximately 3 million rows of Record objects and 13 million rows of Info objects. These will both grow over time, so I'm using Solr to index the description field. I am running into significant performance issues when I try to work with the Solr results in Django. Here are the models (abbreviated): class Record: name = models.CharField() class Info: record = models.ForeignKey(Record...) description = models.CharField() I'm starting with a queryset of all Records. The goal is to filter it down using a text query against descriptions in the Info model. queryset = Record.objects.all() When I query Solr, using Django-Haystack, I can get a list of Info objects pk's that match the query string: sqset = SearchQuerySet().filter(text=query_string).values_list('pk', flat=True) sqset can be 500+ items in length. So when I attempt to use it in a standard query using __in in Django, I end up executing a massive SQL query with hundreds of ORs: queryset = queryset.filter(info__id__in=sqset) Django Debug Toolbar tells me the SQL is performant (approx 60ms on average). The Solr portion of the query also …