Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django authenticationform and active users
If I change a current user's status to inactive, they are not able to login. This is expected. However, the error message they receive is to enter in a proper username and password. I expect that they should get the inactive login message. I am subclassing the authentication form: class CustomAuthenticationForm(AuthenticationForm): """Sub-class authentication form to remove whitespace""" def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') username = ''.join(username.split()) password = " ".join(password.split()) if username is not None and password: self.user_cache = authenticate( self.request, username=username, password=password) print("tried again") if self.user_cache is None: print("self cache") raise self.get_invalid_login_error() else: print("self confirm") self.confirm_login_allowed(self.user_cache) return self.cleaned_data When I try to log in as a user that has a username and password but it now inactive, the tried again and self cache get printed to the console. Since the user is inactive I would expect the self confirm statement to be printed to the console, and this would lead to the confirm_login_allowed function and the correct ValidationError. For what its worth, I am subsclassing this form because I had some users that could not login using their Android phone - their web browser was inserting whitespace. My CustomAuthenticationForm removes this whitespace. -
Validating the current state of a model using DRF?
Our application allows users to specify which fields are required for a particular model. This model also has a status field. There can be different requirements based on the status. For example, status = foo and status = bar will require a different set of fields to be set. The challenge is how to validate that these fields have been set. If we simply had to validate that the required fields were set when creating a new instance, we could set required=True at runtime. However, because it's based on the status, we need to be able to validate an arbitrary model instance against a list of required fields and verify that those fields are set. As an example, suppose we are patching an existing model instance. Even if we know what the required fields are, patching by design does not support required=True. The patch may change a field to be empty, so we need to validate how the model looks after the patch is applied. One idea is to serialize the model instance, then have a function that takes the serialized dict and the list of required fields, and checks each one by hand. This approach is straightforward, but I'd … -
Heroku Free Database Issues
if I use the free version of Heroku where can i find the database, cause in Resources -> add-ons there is nothing I need to get a database to use it on a local server -
Would Postgres data base break if I change a model field name? (heroku)
Feels like a silly question, but I cannot seem to find an answer. I have a number of changes that I need to migrate. Amongst those changes, I have a model field name that has been changed. On local, Django worked out the model field just changed name (simply asked confirmation that old field = new field). I know Postgres and Heroku sometimes behave differently. I left the code below, it's quite simple but the possibility to lose the database worries me. Below is what the local migration look like on local class Migration(migrations.Migration): dependencies = [ ('main', '0085_modelname_timeframe'), ] operations = [ migrations.RenameField( model_name='modelename', old_name='timestamp', new_name='created_at', ), ] and this is the model.py class ModelName(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) Does Heroku work out field name changes easily, or is it something to avoid? -
Form field on front end that allows for decimal input while storing integer value in database
While using Django Forms I have no solution for converting a decimal number to an integer. Use case: input field on a HTML form generated by Django should allow for decimals. The database will only allow for integers. As Django builds the form using javascript for this is not so straightforward. I found Django creating a custom model field but with so many new tools around with Django haven't been able to get it working. Has anybody an advice of how to get this done with a custom model field? Thanks, Gert --- update --- currently everything works as it should. Though I'm re-writing this app in Django form another framework. In that framework I used JavaScript to tackle converting decimals to integers. I'd prefer just to have integer or text values in the database as using the date in different systems might give me problems if I start to use decimals. What I currently have: models.py ----------- from django.db import models from django.urls import reverse from datetime import date CHOICES_PERSONEN = ( (1, "1"), (2, "2"), ) class Nota(models.Model): name = models.CharField(max_length=255) d_s = models.PositiveSmallIntegerField( choices = CHOICES_PERSONEN, default = 2, ) # amount = models.IntegerField(null=True, blank=True) amount = … -
Can I pass dynamic variables to placeholders that are defined in the msgstr, but not in the msgid in Django i18n?
In Django I have a .po file that contains translations in this format: msgid "delete-comment-description" msgstr "Are you sure you want to delete this comment?" There are also translations that require a dynamic value: msgid "hello-user-title" msgstr "Hello, %(user)s. I hope you are fine." How can I pass the variable user to use hello-user-title in a template? I've tried things like: {% blocktranslate with user="my_username" %} hello-user-title {% endblocktranslate %} and {% translate "hello-user-title" user="my_username" %} But both are not working. The reason the msgid is more of a variable name is because this application is partly in React and partly in Django. React is leading for most frontend parts, but some parts are generated by Django templates. I18n was already enabled for React and all translations are managed using a SaaS (Lokalise). Lokalise is also the source of Django's .po files, as I want this service to be the central point of managing translations. This is also relevant to reduce work. Both "delete-comment-description" and "hello-user-title" are also used (and already translated) for react. Translation naming is different between Django's approach and other approaches like the i18n-next approach we use for React. In short: it is not an option for …