Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load a list when a page is shown
I've have tried to do this for hours and decided to ask help.. In my views.py i've got a list list = ['ananas', 'bananas', 'apples'] def listView(request): return JsonResponse({'list' : [{'name': l} for l in list]}) My .html file has a function that should fetch and print the list as the page gets loaded <script inline="javascript"> function loadList() { // How do I fetch and print the list? } </script> and I call loadList function like this as the page loads window.onload = function () { loadList(); }; Inside the function I should have something like this, but I'm not able to fetch the list.. function loadList() { var list = document.querySelector("#list").value; var http = new XMLHttpRequest(); http.open("GET", 'list', true); } -
Fill out the form and save it in db base
I am working on a Django project and I want to fill out a form and save the data in the db database and then be able to show it on another page, I managed to create the form, but it does not write me anything in the database. Here's how I currently have things: forms.py from django import forms from .models import AusenciasForm from django.contrib.auth.models import User class AusenciasForm(forms.ModelForm): class Meta: model = AusenciasFormulario fields = '__all__' widgets = {'fecha': forms.DateInput(attrs={'type': 'date'})} models.py from django.db import models from django.utils import timezone import datetime from django.contrib.auth.models import User from django.urls import reverse class AusenciasFormulario(models.Model): #razon = models.ModelChoiceField(label="Razón", queryset=razones.object.all()) fecha = models.DateField(("Date"),default=datetime.date.today)#label="Fecha", required=True razon = [ ('Estudios/Examen','Estudios/Examen'), ('Enfermedad','Enfermedad'), ('Lesión','Lesión'), ('Motivos personales','Motivos personales'), ('Motivos familiares','Motivos familiares'), ('Otros','Otros') ] motivo = models.CharField(max_length=100, choices=razon, default='Otros') comentarios= models.CharField(max_length=200,blank=True) jugador = User views.py class FormularioAusenciaView(HttpRequest): def index(request): AusenciasFormulario = AusenciasForm() return render(request, 'blog/formularioAusencia.html', {'form':AusenciasFormulario}) def procesar_formulario(request): AusenciasFormulario = AusenciasForm() if AusenciasFormulario.is_valid(): AusenciasFormulario.save() AusenciasFormulario = AusenciasForm() return render(request, 'blog/formularioAusencia.html', {'form':AusenciasFormulario, 'mensaje': 'ok'}) I hope someone can help me -
for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable
I encountered a problem to migrate this model and this admin python manage.py makemigrations This error occurs for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable this is my admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import User, Province class MyUserAdmin(UserAdmin): fields = ( (None, {'fields': ('username', 'password')}), 'Personal info', {'fields': ('first_name', 'last_name', 'phone_number', 'email')}, 'Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}, 'Important dates', {'fields': ('last_login', 'date_joined')}, ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'phone_number', 'password1', 'password2'), }), ) list_display = ('username', 'phone_number', 'email', 'is_staff') search_fields = ('username_exact',) ordering = ('-id',) def get_search_results(self, request, queryset, search_term): queryset, my_have_duplicates = super().get_search_results( request, queryset, search_term ) try: search_term_as_int = int(search_term) except ValueError: pass else: queryset |= self.model.objects.filter(phone_number=search_term_as_int) return queryset, my_have_duplicates admin.site.unregister(Group) admin.site.register(Province) admin.site.register(User) admin.site.register(MyUserAdmin) But the program has encountered an error for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
Django crispy forms prepend box set width
I am using crispy forms to make a django form which has several rows. The default behaviour is for the prepend box to be just the size of the text within it. However this looks messy when there are several fields and I would prefer the prepend box to be an equal width for all. An ugly hack is to just pad the prepend boxes that contain shorter strings with spaces but this is obviously not ideal. Any advoice on how to adjust the width of the prepend box to make them equal across fields? This if the form helper I have where I define the prepend text self.helper.layout = Layout( Row(Field(PrependedText('field1', 'Field1prependtext &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp', wrapper_class='col-md-4 pe-0'))), Row(Field(PrependedText('field1', 'Field1prependtextlonger ', wrapper_class='col-md-4 pe-0'))),) -
Facing issue : websocket can't establish connection to wss://<websocket consumer url>/
I have been working on deploying a website to AWS using Django, daphne, Nginx, I have been facing an issue connecting to wss:// (WebSocket ) it is working locally, which means the issue is not in the Django code, I think I am missing something on the server side, also, the WebSocket is giving 200 responses is it like this? I'm sharing my server configuration images, I have checked it's running on local , when i add daphne in django installed apps, checked daphne is running, checked redis is also running, daphne config file also has ssh private key and certi key let me know what am i missing here. -
Inserting data into Popup with Django
In my Django project, I want to have the institution selection selected from a list, for this I created a model for the institution name and I want the user to enter it as a pop-up window or a list selection for this: models.py class Institution(models.Model): institutionName = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return self.institutionName views.py def getInstitutionName(request): context = {'institutionName':Institution.objects.all()} return HttpResponse(context) I created it in the form of html, but I'm having trouble with how to integrate the data I bring here with html. In this process, I want to make a form that includes other entries, only the institution entry in this way. My question on this subject is, what action should I take while printing the data I have brought here to the screen. -
Django channel with AWS Elastic cache(cluster mode) docker
We are trying to deploy the Django channel app with docker and AWSElastiCache(cluster enabled) for the Redis cloud. However, we are facing issue Moved IP issue. Can anyone provide the solution for the channel_layer working with AWS elastic cluster mode? FYI we deployed our app on the ec2 server. settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('xxxx.clusterxxx.xxx.cache.amazonaws.com:xxx')], }, }, } docker-compose-yml version: '3.7' services: kse_web: build: . volumes: - "/path:/app/path_Dashboard" command: python /app/path_Dashboard/manage.py runserver 0.0.0.0:8008 ports: - "8008:8008" kse_worker_channels: build: . volumes: - "/path:/app/path_Dashboard" kse_daphne: build: . command: bash -c "daphne -b 0.0.0.0 -p 5049 --application-close-timeout 60 --proxy-headers core.asgi:application" volumes: - "path:/path" ports: - "5049:5049" networks: abc_api_net: external: true -
overredieg jinja2 for customized view on django templates
hi I wanna overriding html.py in venv/Lib/coreschema/encodings/html.py. this is a method to need overriding: def determine_html_template(schema): if isinstance(schema, Array): if schema.unique_items and isinstance(schema.items, Enum): # Actually only for *unordered* input return '/bootstrap3/inputs/select_multiple.html' # TODO: Comma seperated inputs return 'bootstrap3/inputs/textarea.html' elif isinstance(schema, Object): # TODO: Fieldsets return 'bootstrap3/inputs/textarea.html' elif isinstance(schema, Number): return 'bootstrap3/inputs/input.html' elif isinstance(schema, Boolean): # TODO: nullable boolean return 'bootstrap3/inputs/checkbox.html' elif isinstance(schema, Enum): # TODO: display values return 'bootstrap3/inputs/select.html' # String: if schema.format == 'textarea': return 'bootstrap3/inputs/textarea.html' return 'bootstrap3/inputs/input.html' and this lines : if isinstance(schema, Array): if schema.unique_items and isinstance(schema.items, Enum): # Actually only for *unordered* input return '/bootstrap3/inputs/select_multiple.html' I want to modify select_multiple.html to custom_select_multiple.html in templates folder in my project directory. also this solution need to overriding some files and I do that. now its cant understand my custom file because in this method: env = jinja2.Environment(loader=jinja2.PackageLoader('coreschema', 'templates')) def render_to_form(schema): template = env.get_template('form.html') return template.render({ 'parent': schema, 'determine_html_template': determine_html_template, 'get_textarea_value': get_textarea_value, 'get_attrs': get_attrs }) used PackageLoader and jinja2 cant understand where is my file. and now how can I resolve this problem. actually I trying to resolve this with set custom urls but this not working. actually I dont know what I do. -
I have error in Django project when I deploy to elastic beanstalk everything is ok but when I go to my server it gives me internal server error
I need help with my Django project when I deploy to elastic beanstalk everything is ok but when I go to my server it gives me an internal server error I do not know where the error is because everything looks fine here is my server and my code settings.py import os from json.tool import main from pathlib import Path # from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent from datetime import timedelta # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-jkkab)y!n*=e1w9w%1939+cqkj0-_cm(evbc65&-s%qede_9z&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['roshbaw-env.eba-f9y6i6ns.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS = [ 'main', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework_simplejwt.token_blacklist' # 'storages', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = 'new_lms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'new_lms.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'RBCLASSDBEB', 'USER': 'admin', 'PASSWORD':'12341234', 'HOST':'mydb.caw7sl9jtojs.us-west-2.rds.amazonaws.com', 'PORT':'3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
To fix them run 'python manage.py makemigrations --merge
Actually I've created some tables foe employee management system like Employeedetails,intern details,department,designations,teams,etc.. with Django Rest Framework .I've also migrated it in Mysql database and have created all needs of serializers and views and urls required. the urls also running perfectly in my localhost machine. But when it sent to deployment to the server, my DevOps team keeps running an error in Docker as shown below. I even merged the migration as per the error shown, still my system shows "No conflicts detected to merge". Somebody help me out from this Head Scratching. This is the error thrown, I dont know which code to attach here because everything works fine in my laptop, that's why I attached the error message #8 20.76 [notice] A new release of pip available: 22.2.2 -> 22.3.1 #8 20.76 [notice] To update, run: pip install --upgrade pip #8 21.53 CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0003_remove_employee_team_id_employeedetails_team_id_and_more, 0006_alter_employeedetails_created_at_and_more in EmployeeDetails). #8 21.53 To fix them run 'python manage.py makemigrations --merge' -
How to select row by distinct column and max datetime?
Trying to get the last records I inserted in database based on DateTime and distinct column SocialMedia_ID but I get the following error DISTINCT ON fields is not supported by this database backend when it reaches to the below line: accountsTwitter = StatsTwitter.objects.all().order_by('DateTime').distinct('SocialMedia_id') I want to mention that below SQL query is working, and I need to convert it to django. SELECT * FROM stats_Twitter WHERE DateTime IN (SELECT MAX(DateTime) FROM stats_Twitter GROUP BY SocialMedia_ID) -
(django) razorpayx webhook receiving empty queryset instead of any payload
this is my webhook url i am using ngrok service for this https://061c-103-223-8-94.in.ngrok.io/intg/rzpwhook/ when i try to change any payout status. i am getting empty queryset instead of any payload this is my view == @csrf_exempt def RazorWebhook(request): print('webhook alert=============',request.POST) return render(request,'intg/rzpweebhook.html') in terminal what i got : is there anything that i am missing ? -
Django - separate serializer data in single call
I have an API call to create a customer in my system. But my customer data is divided in 2 tables for reasons. class BaseUser(AbstractUser): email = models.EmailField(max_length=255, unique=True) phone_number = models.CharField() profile_img = models.ImageField() class Customer(models.Model): user = models.OneToOneField(BaseUser) first_name = models.CharField() middle_name = models.CharField() last_name = models.CharField() dob = models.DateField place_of_birth = CountryField I receive all the data in a single call and want to use the DRF serializer to create both instances with some added actions to each record after being created. Is there a way to give a set of request data to 1 serializer and another set to the other serializer? -
Service Django is not running container
I try to debug an app inside of the container and I need to run django to run tests I do that by: docker-compose exec django bash But as a result I get: service "django" is not running container #1 I don't really understand what this response means and I didn't find any information regarding that. This issue prevents me from being able to debug a code inside of the container with the database up and running. -
Django REST framework - Edit data if there is such a record, create - if not
I'm new to DRF, writing an api for later use in Vue.js . Help me understand how to make it so that when adding a nomenclature, he checks if there is one, and if there is, he edits the quantity by adding to the previous quantity. I am also interested in the question of how, when adding changes to the nomenclature, the number of positions taken was subtracted from the current number of nomenclature. Is it possible to do this by means of DRF or is it possible to implement it in Vue.js, checking and sending POST/PUT requests depending on whether there is or not? My models.py: class Nomenclature(models.Model): nameNom = models.CharField(max_length=150,verbose_name = "Название номеклатуры") numNom = models.CharField(max_length=50,verbose_name = "Номер номеклатуры",primary_key=True) quantity = models.IntegerField(verbose_name="Количество") numPolk = models.CharField(max_length=150,verbose_name = "Номер полки/места") class Changes(models.Model): numNomenclature = models.ForeignKey(Nomenclature, on_delete=models.CASCADE,related_name="chamges") quantity = models.IntegerField(verbose_name="Количество") location = models.CharField(max_length=50,verbose_name = "Место установки") fullname = models.CharField(max_length=150,verbose_name = "ФИО") appointment = models.CharField(max_length=50,verbose_name = "Назначение") def __str__(self): return '%s: %d,%s,%s' % ( self.fullname,self.quantity, self.location, self.appointment) My serializers.py class CheckSerializer(serializers.ModelSerializer): class Meta: model = Changes fields = '__all__' class NumSerializer(serializers.ModelSerializer): chamges = serializers.StringRelatedField(many=True) class Meta: model = Nomenclature fields = ('numNom','nameNom','quantity','numPolk','chamges') My views.py: class CreateNumList(ModelViewSet): queryset = Nomenclature.objects.all() serializer_class = serializers.NumSerializer … -
Initialize django Point in queryset annotate
I have a model with latitude and longitude as DecimalFields. I am trying them to Point instance of postgisand then transform to reqd CRS. I have written the queryset for that but I am getting the following error: TypeError: Invalid parameters given for Point initialization. Queryset list(Geo.objects.filter().values("latitude", "longitude").annotate(float_long=ExpressionWrapper(F('longitude'), output_field=FloatField()), float_lat=ExpressionWrapper(F('latitude'), output_field=FloatField())).annotate(wgs_84=Transform(Point(F('float_long'), F('float_lat'), srid=srid), 4236) )) Here I am trying to add a value wgs_84 which will be the transformed value in wgs84 system. The error I am getting is related to passing F('float_long'), F('float_lat') as params to Point. How can I rectify this error? -
How do I implement a plus/minus function in django forms
how do i implement this in django-form? 2/3: 2 is current picked amount of item, 3 is maximum This form does not work with the model, it will send data after clicking to the redis server -
How can I download this file and copy it into my directory path?
This is what I get as a response from the api : "{\"url\":\"https://thecloud-result.s3.amazonaws.com/2022-11-10/1638463716789.mp3\"}" My view: class ListUserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) data = response.text return Response(data) My directory path: def user_directory_path(filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> if locally return f'{filename}' what is the best way to do it ? So far I only managed to store a file that has the url inside, but I would like to store is as an audio file. Got the media file settings set up already. -
Django multitenant site with different login page for some tenants?
We want to create a multitenant website in Django but I want to have for some tenants different (HTML) login page. How to do that? I am not a Django master but when reading about Django tenants application I thought we can use middleware or a custom tenant-aware loader for finding and loading Django templates or urlpatterns I was thinking of using urlpatters in such way that the path for login would be dependent on the current tenant. urlpatterns = [ path('login/', login.currenttenant_login.urls), path('', home, name='home'), ] Is that possible. Note that only some of the tenants could have different login page. -
Django Rest Framework - Create Form in the backend? [closed]
I work on Django app, I need to create form which contain fields such as f_name, l_name, ..., etc. and send this form to user through email. there is way to create this form in backend? or which best practice to do that? I tried to create this form in the backend, but I'm not sure if that best practice or not. -
How the login, authentication, tokens works? if a user login to any application and till he logout how the requests know that the user is logged in
I'm just trying to make a small ecommerce web application by using Django, Django Rest Framework, I completed registration and login views(not used Django inbuilt authentication) just saving the users information in database and validating those details when the user login, now I'm confused that how actually login works, how the user stay connected till he log out, how the server knows that the user is still logged in, how each request knows that the user is already logged in, Once I tried login by using Django OAuth token, also simple JWT tokens, but when I used to login along with the username and password I also send the token from the postman, but users doesn't login through postman in real world, then how the tokens are handled, who passes the tokens along with the parameters while login, how tokens are passed along with the credentials in real projects, how all these handled in real projects, also what happens when user clicks on logout, what will happen in the backend when user clicks on logout, can anyone please clear this question Thanks. Please help me understanding of this concept -
How I can use one js code of a django template for different content
I am working on a web application using Django I have faced one problem in that and that's I wrote one html template in Django and in that template I also has been written the code of js for that template. I want to use that js code for all the different kinds of content that is represented using that template in the front of the user.but that js code is not working for all kinds of content similarly. Problem in brief I am making a commerical web application for a Project like amazon.in and flipkart.com and I have writen a template for a product view page for all kinds of Product that is shown using that template. I has been made a button in that product view page template. Button is Add to Cart and I have written JavaScript code in that template for add to Cart button to store the product in the cart when the user click the button. I made my cart using LocalStorage and i will store the products in it. but the problem is when I initialzed my site and click on the product and goes to the product view page and click to … -
How to add a model instance (not from db) to queryset
Let's say I have a model called Schools. And also I have a Schools instance that I don't want to store in my database. temp_school = Schools(school_id='temp_1') Also I have all schools schools = Schools.objects.all() Now, how can I add my temp_school to the schools, so that I can use it as my new queryset in my view? -
How to add an extra field in auth user model in django admin?
I want to customize my existing auth user model. I need the command or code for executing the solution? -
in vuejs styling ag-grid's cell data
what am I doing is combine some key value pairs and bold the value in that pair and put it in ag-grid rowData , my problem is bold() method adds the tag to that value it is not getting bold