Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct use of pytest fixtures of ojects with Django
I am relatively new to pytest, so I understand the simple use of fixtures that looks like that: @pytest.fixture def example_data(): return "abc" and then using it in a way like this: def test_data(self, example_data): assert example_data == "abc" I am working on a django app and where it gets confusing is when I try to use fixtures to create django objects that will be used for the tests. The closest solution that I've found online looks like that: @pytest.fixture def test_data(self): users = get_user_model() client = users.objects.get_or_create(username="test_user", password="password") and then I am expecting to be able to access this user object in a test function: @pytest.mark.django_db @pytest.mark.usefixtures("test_data") async def test_get_users(self): # the user object should be included in this queryset all_users = await sync_to_async(User.objects.all)() .... (doing assertions) ... The issue is that when I try to list all the users I can't find the one that was created as part of the test_data fixture and therefore can't use it for testing. I noticed that if I create the objects inside the function then there is no problem, but this approach won't work for me because I need to parametrize the function and depending on the input add different groups … -
simpleJWT confirm password field
I'm creating a small app that uses simpleJWT. I want the user to retype their password when registering. Currently, I'm sending data like this { "email":"test", "user_name":"test3", "password":"b12@wsqp" } But what I want to validate is { "email":"test", "user_name":"test3", "password":"b12@wsqp", "password2":"b12@wsqp" } What i have now is class CustomUserCreate(APIView): permission_classes = (AllowAny,) def post(self, request): reg_serializer = RegisterUserSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: return Response(status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So my guess is to do class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2') extra_kwargs = {'password': {'write_only': True}, 'password2':{'write_only': True}} def create(self, validated_data): password1 = validated_data.pop('password1', None) password2 = validated_data.pop('password2', None) instance = self.Meta.model(**validated_data) if password1 is not None and password2 is not None: if password1 == password2: instance.set_password(password) else: #return some error instance.save() return instance How can I validate if the password are matching? -
Chrome Extension Requesting django server
I am creating a chrome extension that requires a back end server for processing. I would like it to send data to the server, the server will process this data and send some other data back to the user. Preferably this back end server should be in python as there are libraries I would like to use. Any idea how to go about this? I was thinking to use a django server with rest API but I'm not sure what would be best. If anyone could provide a tutorial link or briefly explain the code behind this idea it would be brilliant. -
permission for show media folder in django, python
I want set permission for show media folder images. for example, I want show my images to users who are staff. When user in not staff, show 404 Error Thanks -
Django filter objects and do not select objects if there are objects that were created before them with same field value
I'm trying to do a get_queryset for ModelList view, but I only want to select those records that don't have other records with the same event_id in front of them. For example, we have two records. The second record is a child of the first one, and therefore, I don't want to select this second record from the database because it will already be in the children field of the first record. The children field is generated in the serializer, and does not exist in the database. Dataset [ { "event_id": "63395", "operation_id": "25180328", "time_created": "2023-01-12T09:16:11.873700+01:00", "children": [ { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] }, { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] View class ModelList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = Model.objects.all() serializer_class = ModelSerializer def get_queryset(self): return Model.objects.filter( ~Q( Q(event_id=F('event_id')) & Q(operation_id__gt=F('operation_id')) ) ) -
How can I update specific field after retrieved in django rest framework
How can I update specific field after retrieved in django rest framework # Models.py class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() view = models.IntegerField(default=0) def __str__(self): return self.title I want to update view after read a specific data. # Views.py class ArticleDetail(generics.RetrieveUpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer # Update view + 1 # serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = "__all__" Please help me -
How to display not id but another value in ForeignKey
This is my code for the hotel website models.py class Rooms(models.Model): room = models.BigIntegerField(verbose_name='Комната', unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория', related_name='wer') room_bool = models.BooleanField(verbose_name='Статус', default=True) price = models.BigIntegerField(verbose_name='Цена', null=True,blank=True) class Registrations(models.Model): room_num = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', related_name='ertgdb', limit_choices_to={'room_bool': True}) first_name = models.CharField(max_length=250, verbose_name='Имя') last_name = models.CharField(max_length=250, verbose_name='Фамилия') tel_num = models.BigIntegerField(verbose_name='Номер телефона') img = models.FileField(verbose_name='Паспорт', null=True, blank=True) visit_date = models.DateField(default=now, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, help_text='Дата отбытия') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_relevant = models.BooleanField(default=False, verbose_name='Статус') price = models.BigIntegerField(verbose_name='Цена', default=100) serializers.py class RegistrationSer(serializers.ModelSerializer): class Meta: model = Registrations fields = ('id', 'room_num', 'first_name', 'last_name', 'tel_num', 'img', 'visit_date', 'guest_count', 'room_relevant') I need the room_num field (in the picture) to have not Id but room_num as in the Input form SlugRelatedField doesn't work because I can't make POST PUT requests later -
Django - ValueError: could not convert string to float: ''
Learning Django with tutorial and have error. File "F:\Python\COTSW\teashop\main\views.py", line 98, in cart_list total_amt+=int(item['qty'])*float(item['price']) ValueError: could not convert string to float: '' Views.py def cart_list(request): total_amt = 0 for p_id, item in request.session['cartdata'].items(): total_amt+=int(item['qty'])*float(item['price']) return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt}) Custom.js $(document).on('click', ".add-to-cart", function(){ var _vm=$(this); var _index=_vm.attr('data-index'); var _qty = $(".product-qty-"+_index).val(); var _productId = $(".product-id-"+_index).val(); var _productTitle = $(".product-title-"+_index).val(); var _productImage = $(".product-image-"+_index).val(); var _productPrice = $(".product-price-"+_index).text(); var _productSlug = $(".product-slug-"+_index).val(); console.log(_productPrice) // Ajax $.ajax({ url:'/add-to-cart', data:{ 'qty':_qty, 'id':_productId, 'title':_productTitle, 'image':_productImage, 'price':_productPrice, 'slug':_productSlug, }, dataType:'json', beforeSend:function(){ _vm.attr('disabled', true); }, success:function(res){ $(".cart-list").text(res.totalitems); _vm.attr('disabled',false); } }); Before changes var _productPrice = $(".product-price").text(); was var _productPrice = $(".product-price").text(); and worked. Console.log showing correct price 500.00, but total_amt+=int(item['qty'])*float(item['price']) taking an empty string. Everything works correctly in the tutorial and I don't understand what could be wrong. -
Django: how to filter the inbox messages that belong to a user?
I am trying to get the messages that belongs to a user, something that look like this I am finding it difficult to write the filter query, according to this Answer, i wrote a query that looks like this class MyInbox(generics.ListCreateAPIView): serializer_class = MessageSerializer def get_queryset(self): user_id = self.kwargs['user_id'] messages = ChatMessage.objects.filter(Q(sender__in=user_id) | Q(reciever__in=user_id)).order_by("-date") return messages This is my response what i am trying to do is this, get the latest message that i had with sam, also the latest message that i had with moz and not all the messages. I am trying to get this messages because i want to loop through the message just like in the screenshot above. This is my model class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="user") sender = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="reciever") message = models.CharField(max_length=10000000000) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) mid = ShortUUIDField(length=10, max_length=25, alphabet="abcdefghijklmnopqrstuvxyz") Please how do i go about this? -
Add method imports to shell_plus with alias
I have a model naming collision in my django models, with 2 models called Tag in separate modules. That looks something like this: . ├── conversations/ │ └──models.py <- contains a model called Tag └── dogs/ └──models.py <- contains a model called Tag In shell_plus I want to import each module with an alias in SHELL_PLUS_POST_IMPORTS so that it's available when I start the shell. How can I do this? As an example, if i were doing this manually in shell_plus I'd write: # These are the imports I want to happen automatically: from conversation import models as conversation_models from dogs import models as dog_models # Then I can write: conversation_models.Tag() dog_models.Tag() -
How to add faker data in django in place of foreign key field
All i need is that user field of Product com from the foreign key of User model How can i add daker data here it gives me this error Product.objects.create( Product_name=fake.name(), Product_desc = fake.text(), Price=fake.random_int(3000, 10000), user=1 ) class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=300, null=True, blank=True) password = models.IntegerField() def __str__(self): return self.name class Product(models.Model): Product_name = models.CharField(max_length=30) Product_desc = models.CharField(max_length=300, null=True, blank=True) Price = models.IntegerField() user=models.ForeignKey(User, on_delete=models.CASCADE,related_name='set_user') def __str__(self): return self.Product_name Here is the error -
python request para aplicativo da minha empresa
Tenho três tabelas em uma aplicação python que precisam ser relacionadas para criar uma lista com nomes advindos de um resultado de uma querie, porém em uma das tabelas só há um argumento que conecta todas. Tenho tentado reproduzir essa querie sql no python porém sem mt sucesso "select * from sicei.lotamento as lotamento, sicei.estagiario as estagiario where estagiario.status='1' and lotamento.status='1' and lotamento.lotacao_id='1'; " e utilizado uma função com get_object_or_404, semelhante a este exemplo abaixo: def det_vagas(request, ): est = get_object_or_404(Lotamento, ) lotamento=Lotamento.objects.filter() estagiario = Estagiario.objects.filter() context={'lotamento': lotamento, 'estagiario':estagiario} return render(request, 'mapas_de_vagas/detalhes.html', context) mas não to conseguindo fechar a querie, por dificuldade em entender a lógica relacional mesmo, sendo que a terceira tabela, só cria uma lista aonde eu deveria capturar o valor de uma coluna (lotacao_id) para obter o resultado que preciso. Será que conseguem me ajudar? Meio desesperado pq não to conseguindo. '-' Tentei utilizar uma função baseada em classe, mas o filtro deu ruim, e tentei trocar os argumentos porém sem resultados. -
In Django, passenger_wsgi.py is calling itself creating infinite processes
We are using Angular JS for frontend and Django framework at backend. Whenever a request comes from the front-end, passenger_wsgi file receives the request. It processes the request and returns the expected response. However, passenger_wsgi calls itself, which calls itself. This happens recursively, in an loop causing infinite processes and server to overload. Appreciate your comments and a fix. Below is the current passenger_wsgi. import os import sys import django.core.handlers.wsgi from django.core.wsgi import get_wsgi_application # Set up paths and environment variables sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # Set script name for the PATH_INFO fix below SCRIPT_NAME = os.getcwd() class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) # Set the application application = get_wsgi_application() application = PassengerPathInfoFix(application) I have tried changing the last 2 lines. In this scenario, passenger_wsgi is not able to serve the request and frontend received 500 Server Error. -
Is there a form field in Django that allows you to enter multiple values one at a time?
I could also use a TextField, but that's not ideal from UX point of view. I would like to know if there's a field that allows the user to enter multiple custom strings (not from a pre-defined list of options), one at a time, where, to enter a string, one needs to press enter, these values are then passed as a list of strings (or other types) to the model, which defines an ArrayField. I've searched for some time, but I couldn't find it. I'm not really an expert in Django, but I suppose such a field must exist. If not, I suppose I could create a custom form field that does that. Here's what I mean. In the example, 1 was written, then the user pressed ENTER, and the option was added; then the same thing happened to add 2; the important thing to note is that 1 and 2 do not come from a predefined set of values, but were custom strings entered by the user, which can also be removed after having been entered. -
After executing an api in django rest, the RAM remains high
After executing an api in django rest in production mode, the following method is called and executed. After each execution of this method, the amount of RAM usage goes up and up and does not go down, and I don't understand where the problem is. def download(self): try: if self.adjust: path = Path(UPLOAD_DIR / 'yf_history' / self.market / 'adjusted') else: path = Path(UPLOAD_DIR / 'yf_history' / self.market) path.mkdir(parents=True, exist_ok=True) data = yfinance.download( progress=False, tickers=self.ticker_list, period=self.period, interval=self.interval_period, group_by='ticker', auto_adjust=self.adjust, prepost=False, threads=True, proxy=None ).T for ticker in self.ticker_list: try: data.loc[(ticker,),].T.dropna().to_csv(path / f'{ticker}{self.suffix}.csv') except: pass del data except Exception as error: return False, error else: return True, 'Saved successfully' I don't have this problem with any other function Python==3.9 Django==3.2.9 djangorestframework==3.13.1 yfinance==0.2.10 Thank you for your advice on the problem and solution. -
How can we sync different databases and application in django
How can we access other database tables into django application database. Here 'default' database is main application and 'cl_db' is other application which is developed in asp.net but using same database server here how can we sync 'cl_db' database into 'default' database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fail_over', 'USER': 'SomeUser', 'PASSWORD': 'SomePassword', 'HOST': '127.0.0.1', 'PORT': '', }, 'cl_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cl_dev', 'USER': 'SomeUser', 'PASSWORD': 'SomePassword', 'HOST': '127.0.0.1', 'PORT': '', }, } -
How do I use the onsubmit function in Django to switch pages?
I'm trying to create a page that, once a form submit button is clicked, will redirect to the home page. I'm using the 'onsubmit' function for that, but it isn't working. HTML code {% extends 'base.html' %}{% load static %} {% block head %} <link rel="stylesheet" href="{% static 'login.css' %}" /> <script src="{% static 'login.js'}"></script> {% endblock %} <!-- page code --> {% block pagename %} <p>SIGN IN</p> {% endblock %} {% block content %} <div class="contentContainer"> <p>Please enter your competition ID:</p> <form class="form" onsubmit="pageSwitch()"> <input type="text" id="entry" placeholder="ID ENTRY HERE..."> <a name="container"></a> <input type="submit" id="entrySubmit" value="SUBMIT"> </form> </div> {% endblock %} JS Code function pageSwitch(){ window.location.replace("{% url 'home %'}"); } urls.py Code from django.contrib import admin from django.urls import path from files import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('test/', views.test, name='test'), path('', views.login, name='login'), path('home/', views.home, name='home'), path('leaderboard/', views.lboard, name='lboard'), path('scorecard/', views.score, name='score'), path('submit/', views.submit, name='submit'), path('base/', views.base, name='base'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 'views.py' Code from django.shortcuts import render # Create your views here. def test(request): return render(request, 'test.html') def base(request): return render(request, 'base.html') def login(request): return render(request, 'login.html') def home(request): return render(request, 'home.html') def lboard(request): return render(request, 'leaderboard.html') def … -
after uploading a file in Django Firebase "Storage", how can I download that file by clicking the HTML button?
when I upload any type of file by clicking the "Send" button, that file will be uploaded, and get the URL of that file. then renders the URL through the context in HTML. But here, my problem is when I click the "Download" button the file opens up in that tab instead of being downloaded. How can I solve this? Where I am use python-pip Pyrebase4==4.6.0 Firebase Connection class Firebase: def __init__(self): firebaseConfig = { 'apiKey': "_____", 'authDomain': "____", 'projectId': "___", 'storageBucket': "_____", 'messagingSenderId': "______", 'appId': "___________", 'measurementId': "_______", 'databaseURL': '__________', 'serviceAccount': 'service.json' } firebase = pyrebase.initialize_app(firebaseConfig) self.fireStorage = firebase.storage() My Views from django.shortcuts import render from django.core.files.storage import default_storage from . models import Firebase def index(request): if request.method == 'POST': file = request.FILES['file'] file_save = default_storage.save(file.name, file) # save the file as temporary firebaseObj = Firebase() firebaseObj.fireStorage.child(f'files/{file.name}').put(f'medias/{file.name}') URL = firebaseObj.fireStorage.child(f'files/{file.name}').get_url(None) delete = default_storage.delete(file.name) # delete the temporary file return render(request, 'index.html', context={'fileurl':URL}) return render(request, 'index.html') In HTML <div> <form method="post" action="{% url 'index' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" id="fileid" required> <br> <button type="submit">Send</button> </form> <a href="{{ url }}" download> <button> Download Now </button> </a> </div> -
CORS failed for React + Django
For my django application, I use django-cors-headers to enable cross-platform requests. I use the library in that way. settings.py ... ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'accounts', "corsheaders", ] 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', ] CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:3000"] CORS_ALLOWED_HEADERS = list(default_headers) + ['content-type'] ... That's how i do post requests let response = await fetch("http://localhost:8000/auth/signup/", {"method": "POST", "body": { "username" : "test", "password": "test" }, "headers" : { 'Conent-Type': "Application/json" }, } ) Error: Access to fetch at 'http://localhost:8000/auth/signup/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Request header field conent-type is not allowed by Access-Control-Allow-Headers in preflight response. I also checked the OPTION requests that the browser sends to check the 'cors' headers and discovered that the response allows the 'content-type' header. There is response headers for option request. Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: http://127.0.0.1:3000 Access-Control-Max-Age: 86400 Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Thu, 16 Feb 2023 12:36:55 GMT Server: WSGIServer/0.2 CPython/3.9.2 Vary: Origin I looked into how to enable cors for Django. -
Getting error "'list' object is not callable" for authentication_classes
I have following method: @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries def get_xyz(self, request, pk=None): # ... Inside this method, request.user was always AnonymousUser. I felt that it was because I did not specify any kind of authentication for this method. I skipped through codebase and found other developers using decorator. So, I tried by adding a decorator @authentication_classes([TokenAuthentication,]) as follows: @action(detail=False, permission_classes=(IsOwnerOrReadOnly,)) @debugger_queries @authentication_classes([TokenAuthentication,]) def get_xyz(self, request, pk=None): # ... But it started me giving 'list' object is not callable error on this newly added line. What I am missing here? PS: I am trying to hit url from postman. I have logged in my website from the browser, copied csrftoken and sessionid from browser to postman. -
Django and Docker Compose access media folder between containers
I'm working on a docker-compose app using Django and a container to check images validity, here's the project structure: |-- backend | |-- backend | | |-- asgi.py | | |-- celery.py | | |-- __init__.py | | |-- settings.py | | `-- urls.py | |-- manage.py | |-- media | | `-- temp | | `-- image.png | |-- profiles |-- docker-compose.yml |-- Dockerfile |-- README.md |-- requirements.txt Here's the docker-compose configuration of django and nsfw: app: build: . volumes: - .:/app env_file: - ./.env/prod.env ports: - 8000:8000 depends_on: - database nsfw: image: eugencepoi/nsfw_api logging: driver: none ports: - "5000:5000" depends_on: - app environment: - PORT=5000 And here's the code I'm using to exchange the image between containers: url = "http://app:8000/media/temp/image.png" response = requests.get(f"http://nsfw:5000/?url={url}") And here's the settings.py configuration: MEDIA_URL = "/media/" # prints app/backend/media MEDIA_ROOT = os.path.join(BASE_DIR, "media") And finally urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm using django in production mode, but I can't use NGINX to serve images because they are shared locally by containers. Are there errors in my code? Thank you -
Combine two django models with shared ids into a single viewset
I have two django models in two independent apps, who use the same user ids from an external authentication service: In app1/models.py: class App1User(models.Model): user_id = models.UUIDField(unique=True) app1_field = models.BooleanField() In app2/models.py: class App2User(models.Model): user_id = models.UUIDField(unique=True) app2_field = models.BooleanField() I would like to have a combined viewset that can make it seem like these two are a single model with a list response as follows: [ { 'user_id': ..., 'app1_field': ..., 'app2_field': ... }, ... ] If I create or update with this viewset, it should save the data to each of the two models. -
Sentry: rate limit errors sent to prevent depletion of error quota
When an infrastructure incident happens, the application will start to generate thousands of occurrences of the same error. Is it possible to configure some kind of rate limiting or anything like that on the sentry client (or server) to avoid depleting the error quota? I'm using Python, Django and Celery mostly. -
PDF generation from an existing PDF using python/django
im using Django api, the user will upload an invoice im converting it to html using PDF.js and the user will label the invoice number, the buyer name, the buyer address then i will take a json response to generate 100 pdfs from the pdf that the user uploaded after i modified the values i got in the json response with the faker library in python. i made the task work but only with pdf 1.3 the code i used for pdf1.3 the Object of a PDF 1.3 7 0 obj << /Length 676 >> stream 2 J BT 0 0 0 rg /F1 0027 Tf 57.3750 722.2800 Td ( Simple PDF File 2 ) Tj ET BT /F1 0010 Tf 69.2500 688.6080 Td ( ...continued from page 1. Yet more text. And more text. And more text. ) Tj ET BT /F1 0010 Tf 69.2500 676.6560 Td ( And more text. And more text. And more text. And more text. And more ) Tj ET BT /F1 0010 Tf 69.2500 664.7040 Td ( text. Oh, how boring typing this stuff. But not as boring as watching ) Tj ET BT /F1 0010 Tf 69.2500 652.7520 Td ( paint dry. … -
AJAX code doesnt working with Django project
enter code hereIm making sort of a game where users can create or join a room with code and play a game...For now i only want to show all the users that are in the one room and i dont want the page to refresh when someone new enters. I asked few guys on reddit and they said i should use AJAX so i watched some tutorials but it doesn show anything. here is my code: views.py from asyncio.windows_events import NULL from hashlib import new from django.shortcuts import render, redirect from .models import Room, User from django.contrib import messages from random import randint from django.http import JsonResponse def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) def index(request): return render(request, 'index.html') def checkroom(request): if request.method == "POST": Uspeo = False username = '' code = 0 # join with code if 'dugme1' in request.POST: username = request.POST["username"] no1 = request.POST["no1"] no2 = request.POST["no2"] no3 = request.POST["no3"] no4 = request.POST["no4"] no5 = request.POST["no5"] no6 = request.POST["no6"] number = no1+no2+no3+no4+no5+no6 if len(username) == 0: messages.info(request, 'Enter your name!') return redirect('/') else: if Room.objects.filter(Room_code=number).exists(): user = User.objects.create(username=username, code=number) user.save() return redirect('/room/?code=' + number + '&username=' + username) else: messages.info(request, 'Code not …