Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting a "Cannot return null for non-nullable field" error when doing a query?
**FOLDER STRUCTURE ** models.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Director filter_fields = { "name": ["exact", "icontains", "istartswith"], "first_directed_episode__name": ["exact", "icontains"], "last_directed_episode__name": ["exact", "icontains"], "age": ["exact"], } fields = "__all__" interfaces = (relay.Node,) types.py import graphene from graphene import ObjectType, relay from graphene_django import DjangoObjectType from general.models import Character, Director, Episode class CharacterType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) class Meta: model = Character filter_fields = { "name": ["exact", "icontains", "istartswith"], "character_species": ["exact", "icontains"], "location": ["exact"], "status": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class EpisodeType(DjangoObjectType): pk = graphene.Int(source="pk") class Meta: model = Episode filter_fields = { "name": ["exact", "icontains", "istartswith"], "directed_by__name": ["exact", "icontains"], "aired_date": ["exact"], } fields = "__all__" interfaces = (relay.Node,) class DirectorType(DjangoObjectType): pk = graphene.Int(source="pk", required=True) … -
Django filters startswith
filters by creating a very simple site. There is a view and the user searches an object that I added as an admin. Views.py from django.shortcuts import render from .filters import * def home(request): myqs = Kati.objects.all() myFilter = SearchForm(request.GET, queryset=myqs) return render(request, 'home.html', {'myFilter':myFilter}) Models.py class Kati(models.Model): name = models.CharField(max_length=200) product = models.CharField(max_length=200) timi = models.CharField(max_length=200) Filters.py import django_filters class SearchForm(django_filters.FilterSet): class Meta: model = Kati fields = ['name','product','timi'] Html <form action='' method='get'> {{myFilter.form}} <button>OK</button> </form> {%for i in myFilter.qs%} <p>{{i.name}}</p> <p>{{i.product}}</p> <p>{{i.timi}}</p> {%endfor%} It works but is there a way to show an object just by typing the first letter. For example if the name is abcd show the object if you write ab. Like __startswith__. -
Django Celery show return value of task
i have a problem to display the return value of my celery task to the client. Redis is my result backend. I hope someone can help me. Thats the code: tasks.py: @shared_task def create_task(task_type): sleep(int(task_type) * 5) data={ 'test':'test' } return data The task should return the data after sleep for the given time. views.py: def home(request): return render(request, "async_project/home.html") @csrf_exempt def run_task(request): if request.POST: task_type = request.POST.get("type") task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result, } return JsonResponse(result, status=200) urls.py: from django.urls import path from . import views urlpatterns = [ path("tasks/<task_id>/", views.get_status, name="get_status"), path("tasks/", views.run_task, name="run_task"), path("home", views.home, name="home"), ] settings.py: # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' home.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django + Celery + Docker</title> <link rel="stylesheet" type="text/css" href="/staticfiles/bulma.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> </head> <body> <section class="section"> <div class="container"> <div class="column is-two-thirds"> <h1 class="title">Django + Celery + Docker</h1> <hr><br> <div> <h2 class="title is-2">Tasks</h2> <h3>Choose a task length:</h3> <div class="field is-grouped"> <p class="control"> <button class="button is-primary" data-type="1">Short</button> … -
Using signals in django while extending user model
Basically I have 2 models that are 1 to 1 related with User model, First model in Employee and second one is Customer. I am also using signals for updates #Signal functions inside each model @receiver(post_save, sender=User) def create_customer(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def update_customer(sender, instance, created, **kwargs): if created == False: instance.customer.save() When I register a user it gets duplicated both in customer and employee. Is there a way to prevent this? -
Customize group permissions in django?
I need to make role-based authentication. Firstly, I made group permissions for all my apps. I assigned some of them to role according to role's ability. from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group class Role(models.Model): title = models.CharField(max_length=32) groups = models.ManyToManyField(Group) def __str__(self) -> str: return self.title Here you can a see driver role which has access on some group permissions (in fact they are just names of groups) Now I have a user model: class Users(AbstractUser): role = models.ForeignKey( Role, on_delete=models.CASCADE, related_name='roles', blank=True, null=True) def __str__(self): return (self.username) I don't want to pick group permissions every time when I created a new staff user. I just want to set a role to a user and it should automatically pick all permissions based on selected role's groups. How to customize groups in django models? -
Post a CharField to an ArrayField in from React to Django using Axios
I am trying to create a feature where if a user writes a post the ID of the post goes into an ArrayField in the User model so a list of their writing can be accessed. I introduced a new column in the User database, made the necessary migrations and trialed this feature just saving one post ID which worked fine. The issue arose when I made the model field an ArrayField. Now when I do the POST request I get an error response : "{\"posts_written\":{\"0\":[\"Expected a list of items but got type \\\"str\\\".\"]} Currently I am writing the REQUEST as let newPost = new FormData() newPost.append('title', title) newPost.append('content', content) updatePostList.append('posts_written', id + ',') await API.patch(`/profile/user/${loggedInProfile.id}/update/`, updateArticleList, { headers: { 'Authorization': `Token ${sessionToken}`, 'Content-Type': 'multipart/form-data', }, }) I am unsure of how to write the POST request to work with the ArrayField, I have looked online for answers but can't find anything. Here is the User model class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) profile_image = models.ImageField(upload_to='profile_images', default='/profile_images/DefaultAvatar.png') bio = models.CharField(max_length=500, default='', blank=True, null=True) display_name = models.CharField(max_length=250, blank=True, null=True) articles_written = ArrayField( ArrayField(models.CharField(max_length=36, blank=True, null=True)), ) Thank you -
Django Ninja API framework ValueError: Cannot assign "*": "*.*" must be a "*" instance
My project running Django 4.1 and Ninja 0.19.1. I'm trying to make a post request via Swagger or Postman and getting an error ValueError: Cannot assign "115": "Offer.currency_to_sell" must be a "Currency" instance. Post data is: { "currency_to_sell_id": 115, "currency_to_buy_id": 116, "user_id": 1, "amount": 100, "exchange_rate": 10 } Endpoint in api.py @api.post("/add_offer/") async def add_offer(request, payload: OfferIn): offer = await Offer.objects.acreate(**payload.dict()) return {"id": offer.pk} schemas.py class OfferIn(ModelSchema): class Config: model = Offer model_fields = [ "currency_to_sell", "currency_to_buy", "user", "amount", "exchange_rate", ] What am I doing wrong? I tried different approach with Schema instead of ModelSchema and it worked. class OfferIn(Schema): currency_to_sell_id: int = None currency_to_buy_id: int = None user_id: int = None amount: float -
Django like system
I'm doing a blog project, but I have a problem, I'm doing a liking system on the blog, but it gives an error def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return reverse('main:post_detail') path('blog/like', views.like_post, name='like-post'), class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) <form action="{% url 'main:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> <button class="btn btn-primary" type="submit"> Like</button> <br> <strong>{{ post.liked.all.count }} Likes</strong> </form> That's the mistake I got. https://prnt.sc/y6AHr4buWReN -
MultiValueDictKeyError for multiple file uploads
Goal: I'm looking to have multiple file upload fields from one model, under one view and in one template. The issue is that I get this error: 'MultiValueDictKeyError' when submitting the post request. I have searched https://stackoverflow.com/search?q=MultiValueDictKeyError+file+upload but none of the responses appear to be applicable - as they only cover one field file uploads. Some context: Not all file uploads are required and some can be blank. The user just uploads whatever files are applicable. models.py def user_directory_path(instance, filename): return 'PDFs/{1}'.format(instance.user, filename) class PDFUpload(models.Model): class Meta: verbose_name_plural = 'PDF Uploads' user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) pas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) add_pass = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) gas_safe = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) oftec = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) hetas = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) bba = models.FileField(upload_to=user_directory_path, null=True, blank=True, validators=[FileExtensionValidator(['pdf'])]) forms.py class PDF(forms.ModelForm): class Meta: model = PDFUpload fields = ['pas', 'add_pass', 'gas_safe', 'oftec', 'hetas', 'bba'] widgets = { 'pas': ClearableFileInput(attrs={'multiple': True}), 'add_pass': ClearableFileInput(attrs={'multiple': True}), 'gas_safe': ClearableFileInput(attrs={'multiple': True}), 'oftec': ClearableFileInput(attrs={'multiple': True}), 'hetas': ClearableFileInput(attrs={'multiple': True}), 'bba': ClearableFileInput(attrs={'multiple': True}), } labels = { "pas": "PAS", "add_pass": "Additional PAS (if applicable", "gas_safe": "Gas Safe", "oftec": "OFTEC", "hetas": "HETAS", "bba": "BBA", } views.py @login_required def upload(request): if request.method == 'POST': pdf_upload = … -
In the following code I write the Login API but when I print the user it's give me None result
In the following code I created a Login API but when I hit the request in Postman it's always give me Error Response anyone help me out to rectify the problem. I post all of the code and dependencies so anyone can check and give me the solutions. This is my views.py file from django.shortcuts import render from rest_framework.permissions import AllowAny from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer, RegisterSerializer, UserLoginSerializer from django.contrib.auth.models import User from rest_framework import generics, permissions from rest_framework import status from django.contrib.auth import authenticate,login from django.contrib import auth # from knox.models import AuthToken # Create your views here. from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view #Login Credentials "//Create a Login API in Django?" class UserLoginView(APIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def get(self,request,format=None): serializer=UserLoginSerializer(data=request.data) # print(serializer.is_valid(raise_exception=True)); if serializer.is_valid(raise_exception=True): email = serializer.data.get('email') password = serializer.data.get('password') print(email) print(password) user=authenticate(email=email,password=password) print(user) if user is not None: login(request, user) return Response({'msg':'Login Success'},status=status.HTTP_200_OK) else: return Response({'msg':{'Email or Password Does not match'}},status=status.HTTP_404_NOT_FOUND) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #This is my serializer.py file. class UserLoginSerializer(serializers.ModelSerializer): email=serializers.EmailField(max_length=200) class Meta: model = User fields= ['email','password'] When I hit the request then its always give me error so please check my login api … -
Django-Tenant-User Circular Dependency Error during setup
I got issues doing the migrations after setting up django-tenant-user. Just using django-tenant was no issue. Everytime I run python manage.py migrate I get the following circular dependency error: django.db.migrations.exceptions.CircularDependencyError: users.0001_initial, client.0001_initial My settings.py from pathlib import Path import os from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv() SECRET_KEY = os.getenv('DJANGO_SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] # Application definition SHARED_APPS = [ 'django_tenants', # Django Shared Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tenant_users.permissions', 'tenant_users.tenants', 'client', 'users', ] TENANT_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'tenant_users.permissions', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_USERS_DOMAIN = "localhost" AUTHENTICATION_BACKENDS = ( 'tenant_users.permissions.backend.UserBackend', ) AUTH_USER_MODEL = 'users.TenantUser' TENANT_MODEL = "client.Client" # app.Model TENANT_DOMAIN_MODEL = "client.Domain" # app.Model MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', '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 = 'good_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'good_django.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases print(os.getenv('DB_NAME')) print(os.getenv('DB_USER')) DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } DATABASE_ROUTERS = … -
DecimalField validation error, returns incorrect value Django
Ive got a DecimalField in one of my forms where a user enters a price. Say the user enters 11.00, now when i retrieve it as in (priceform.cleaned_data) it returns Decimal('11.00') so it looks like price = Decimal('11.00') which triggers a validation error when i try to insert it into the database. I'm coming up blank to any solutions for this -
How to copy multiple files from a directory in Dockerfile in one go?
Inside my Django project I have a directory for requirements that are separated for different environments which contains three files dev.txt, common.txt and prod.txt. in Dockerfile I just wanna copy only two of them dev.txt and common.txt into /app/requirements directory inside docker container in one go. FROM python:3.9.15 WORKDIR /app COPY /requirements/common.txt /requirements/dev.txt /requirements/ RUN pip install -r /requirements/dev.txt COPY . /app EXPOSE 8000 I have copied them in this way. but I think there is a better and more readable way. If you know a better way, please tell me. -
Django field choices doesn't appear
I want to appear the issubmitted_choice in my list but it doesn't appear. Can someone has a solution? -
Custom GL Lines Plug-in creates error on paid in full invoices
I created a script that re-books certain transactions depending on the account they were booked to. The script is running fine on all invoices and creating the expected outcome except when an invoice has the status "paid in full". The error states Cannot use 0 as input to setDebitAmount(). Amount to debit must be positive. Already tried the script on the same invoice with different statuses - same outcome. Why does the invoice status make a difference here? /** * Custom GL lines Plug-In Implementation for rebooking Invoices (articles and discounts) * Configuration of Plug-In Implementation: * Transaction Type: Invoice * Subsidiaries: MTE * @param {*} transactionRecord * @param {*} standardLines * @param {*} customLines */ function customizeGlImpact( transactionRecord, standardLines, customLines ) { function sign(x) { // If x is NaN, the result is NaN. // If x is -0, the result is -0. // If x is +0, the result is +0. // If x is negative and not -0, the result is -1. // If x is positive and not +0, the result is +1. return ((x > 0) - (x < 0)) || +x; } if (standardLines.getCount() > 0) { var tranid = transactionRecord.getFieldValue("tranid"); var customername = … -
Importing and transposing data from web link in R
Dear Colleagues I think this message fund you well. I would like to request your assistance to have an R script that will allow me to Importing and transposing data from web link below: Link: https://unstats.un.org/sdgapi/v1/sdg/Series/Data?seriesCode=SL_DOM_TSPD When i try to import i get 0 observations out of 11 variables, and the tables are empty. I do not understand why that is happening and how can i fix it. This is my code: dataf <- ("https://unstats.un.org/sdgapi/v1/sdg/Series/Data?seriesCode=SL_DOM_TSPD") df <- data.table::fread(dataf) df <- fread(dataf) Thank you for your help. When i try to import i get 0 observations out of 11 variables, and the tables are empty. -
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': …