Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
who will serve ASGI and WSGI when i add daphne?
when i add daphne in INSTALLED_APPS how will it work ? does it work itself to serve WSGI and ASGI ? or Does it work alone to serve ASGI only ? and Gunicorn still working to serve WSGI ? if daphne works alone to serve ASGI only, and Gunicorn works alone to serve WSGI only... that means i am running two servers in the same time . right ? i have read the document of Channels and ASGI ... but i did not find any thing talks about this thing .. and how will it act >> or if does it take everything and serve them all. if thet so, then i have to deploy my project on a server and run daphne only right? channels document. ASGI document. -
Deploying Django project in an Amazon EC2 Ubuntu instance
I have developed a Django website and hosted the application in an Amazon EC2 instance. AMI name: ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20231207 Instance type: t2.micro I run the project following these steps: SSH into the EC2 instance from my terminal. I locate into the proper django project folder. I run this command: python3 manage.py runserver 0.0.0.0:8000 Now, following these steps, I'm able to run the project and it works fine. But when I close the cmd opened in my local PC that I used to SSH into the EC2 instance and to run the application, then the application doesn't work anymore. My aim would be to simply run the django project from my cmd once (of course after having SSH to the EC2) and then close my laptop and having the application still alive. Do you know how can I do this? -
How can i make notifications in django?
i have Movie model like This: class Movie(models.Model): title = models.CharField(max_length=50) imdb = models.FloatField(validators=[MaxValueValidator(10), MinValueValidator(0)]) age = models.IntegerField() description = models.TextField() starring = models.TextField() Genres = models.ForeignKey( Category, related_name="category", on_delete=models.CASCADE ) tag = models.ManyToManyField(Category, related_name="tags") file = models.FileField(upload_to="media/movie") trailer = models.FileField(upload_to="media/movie/trailer") poster = models.ImageField(upload_to="media/poster", default="media/hero.png") no_likes = models.IntegerField(default=0) def __str__(self) -> str: return self.title @property def time(self): video = VideoFileClip(self.file.path) duration = video.duration hours = int(duration // 3600) min = int((duration % 3600) // 60) if min == 0: return f"{hours} h" elif hours == 0: return f"{min} min" else: return f"{hours} h {min} min" @property def star(self): return round(self.imdb / 2, 0) and i have a Notifications Model like this: class Notifications(models.Model): user = models.Foreignkey(User,on_delete=models.CASCADE) movie = models.Foreignkey(Movie,on_delete=models.CASCADE) I want to create an object from the notifications model when an object is created from the movie model What should I do? i try use signals but signals not work -
How to connect xhtml2pdf - pisa with the Cyrillic alphabet?
How to connect xhtml2pdf - pisa with the Cyrillic alphabet? I have a code that generates a PDF document, but if the form fields contain Cyrillic, then black squares are displayed in the PDF document. I read a lot of information on the Internet on how to make friends with the Cyrillic alphabet, but not a single answer saved my situation. I placed a font that supports Cyrillic in the static folder, static/fonts/(font name).ttf. I registered this absolute path according to the instructions. I used call_back, but that didn't help either. Perhaps I'm doing something wrong. Please help! Below is my code, if anyone knows how to fix this situation, please make changes to my code and tell me where my mistake is. I will be very grateful. Thank you in advance! `def convert_to_pdf(template_name, **context): template = get_template(template_name) html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding="UTF-8") result.seek(0) response = HttpResponse(result.getvalue(), content_type="application/pdf; charset=utf-8") response["Content-Disposition"] = 'inline; filename="output.pdf"' return response` The example shows my initial code that generates a PDF document. -
Django Test: how to simulate LookupError for django_app.get_model()
I need help to implement a test for my Django app. This is a snippet code from my serializer, that I want to test: try: app_config = django_apps.get_app_config(BcConfig.name) app_model = django_apps.get_model(app_label=app_config.name, model_name=type_model_name) recording = app_model.objects.create(**recording) except LookupError: recording = None as mentioned in Django docs, Raises LookupError if no such application or model exists. How to simulate the LookupError programmatically? I have tried to remove the listed model using ContentType, but django_apps.get_model() was still working. I have tried to remove the model using SchemaEditor, but not working properly for testing in SQLite. I still can not find how to delete the model or disable the Django app programmatically. I appreciate the help. Thank you. -
i'm getting SQL Injection error through Django
`I'm getting this error - ProgrammingError at /databases You can only execute one statement at a time. Request Method: POST Request URL: http://127.0.0.1:7099/databases Django Version: 5.0 Exception Type: ProgrammingError Exception Value: You can only execute one statement at a time. Exception Location: C:\Users\falcon\Desktop\Meity\hawk_v\okii\Lib\site-packages\django\db\backends\sqlite3\base.py, line 324, in execute Raised during: app.views.databases when i give the field, designation as '); DELETE FROM app_databases; --. it should delete the whole database but it says, multiple commands executed. please help me out` -
Data Fetch Failure from Django REST API using useFetch in Nuxt.js: Different Behaviors on Reload and Code Editing
I'm developing with Nuxt.js and attempting to fetch data from a Django REST API. I'm encountering several issues with the following code: <template> <div> {{ posts }} </div> </template> <script setup lang="ts"> const { data: posts, pending, error, refresh } = await useFetch('https://localhost:8000/api/posts/') console.log(posts, error) </script> Here are the problems I'm facing: When using useFetch to retrieve data from the Django REST API, an error occurs. Specifically, the following log is output: Proxy(Object) {mountains: Error: [GET] "https://localhost:8000/api/posts/": <no response> fetch failed at createError (…} If I edit and save the Vue code while the page is displayed, the data loads correctly, and I can see the requests in the server logs. However, when I reload the page, the data does not load. There is no record of the request in the server logs. If I change the URL to https://fakestoreapi.com/products, the data is fetched correctly even on page reload. Could you advise on why the data doesn't load upon page reload and how I might resolve this? Also, if you have any insights into why the problem doesn't occur with a different URL, that would be very helpful. -
Why age field is not rendering in signup page? I have included it in fields in CustomUserCreationForm and Models
` #Code For Custom Forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ("age", ) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields #Code For CustomUser Model from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveBigIntegerField(null=True, blank=True) #Code For SignUpView from django.urls import reverse_lazy from .forms import UserCreationForm from django.views.generic import CreateView class SignUpView(CreateView): form_class = UserCreationForm template_name = 'registration/signup.html' success_url = reverse_lazy('login') #Code Of Signup.html {%extends 'base.html'%} {%block title%}Sign Up{%endblock title%} {%block content%} <h2>Sign Up</h2> <form method="post">{%csrf_token%} {{form.as_p}} <button type="submit">Sign Up</button> </form> {%endblock content%} enter image description here You Can see in the image that age field is not showing up for input. things are working completely fine in admin page.The age is showing on the page but not the input for age is showing in signup page. -
Django login authentication redirect to userlogin
i having problem to login user . if i enterd a valid login username and password it keep redirecting me to the login page instead of index.html page for authenticated user from django.shortcuts import render, redirect from django.http import HttpResponse from django.urls import reverse from django.db import models from django.contrib import messages from django.contrib.auth.models import User from finance.models import User from django.contrib.auth import authenticate, login # Create your views here. def userlogin(request): return render(request,'userlogin.html') def Checklogin(request): if request.method == 'POST': usernmame = request.POST['username'] password = request.POST['password'] user = authenticate(username=usernmame,password=password) if user is not None: login(request, user) return redirect(request,'index.html') else: return render(request,'userlogin.html') -
Not implemented alter command for SQL ALTER TABLE "shops_order" ALTER COLUMN "status" TYPE string
I'm trying to use MongoDB with Django. I did everything according to its official docs. I installed pymongo (v3.12.1)* and djongo (v1.3.6). I tried running python manage.py migrate command. It successfully did some migrations but failed at one of them. here's the whole traceback: Running migrations: Applying shops.0020_alter_product_options_alter_order_status...Not implemented alter command for SQL ALTER TABLE "shops_order" ALTER COLUMN "status" TYPE string Traceback (most recent call last): File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( ^^^^^^ File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() ^^^^^^^^^^^^ File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) ^^^^^^^^^^^^^^^^^^^^^^^^ File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "G:\Fusion\fusionVenv\Lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "shops_order" ALTER COLUMN "status" TYPE string',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "G:\Fusion\fusionVenv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return … -
Auth0 - How to get userID ? StatusCode400 Error
Happy Sundays everyone. Note: Setup is Django-Rest. So I was trying to get user ID because I am going to check the user's roles in the login, and decide whether let them in or not. So currently I can get some information as id_token = token.get('id_token') jwk_set = oauth.auth0.fetch_jwk_set() user_info = jwt.decode(id_token, jwk_set) print(user_info) However, this information has 'nickname, name, picture, email' and so on. Therefore I tried, def get_user_id(): import http.client conn = http.client.HTTPSConnection("cageda.eu.auth0.com") headers = { 'authorization': "Bearer {settings.SOCIAL_MANAGEMENT_TOKEN}" } conn.request("GET", "/api/v2/users/USER_ID", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))``` However, this is returning as: {"statusCode":400,"error":"Bad Request","message":"Bad HTTP authentication header format","errorCode":"Bearer"} I am totally stucked. A help would be a lifesaver. -
django web app accessed by multiple users
I'm trying to implement a web based quiz application I'm currently using django and html / JavaScript – only running on localhost so far (python manage.py runserver) For one single user, the quiz is working fine, but multiple users are not able to play individually atm. How do i handle concurrent access to the quiz? I considered using the request.session data structure but storing the complete quiz in there somehow feels wrong. And different users might play a totally different set of questions … Somehow I'd like to start a new thread each time a user access the webpage and starts the quiz (like I'd do it in some offline application), but im not sure if this is the right approach for web dev. I also read that this is maybe done by the real webserver, e.g. apache? Should I try to put the django app on apache? Also considered docker and started a small tutorial this morning. I can post some code ofc, or provide more implementation details if necessary but at the moment I need to get a basic understanding of web development best practices ;-) Scenario: User A starts quiz and answers the first 5 questions. User … -
why does any interaction with the django site direct you to the data addition form?
The task was given to develop a service for working with the restaurant database on django. Clicking on the corresponding buttons /fields of the data table should redirect to pages with edit/add/delete forms, but any interaction with the site redirects only to the page for adding new data. I've been trying to find the reason for this behavior for several hours, but nothing comes out. Below is the html markup of one of the pages, views, forms and URLs for working with one of the database tables. <body> {% include 'main/navbar.html' %} <h1>restaurants</h1> <div class="add"> <form method="post" action="{% url 'create_restaurant' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Добавить</button> </form> </div> <table class="table"> <ul></ul> <thead> <tr> <th>Address </th> <th>Phone number</th> <th>Delivery area</th> <th>Menu</th> <th></th> </tr> </thead> <tbody> {% for restaurant in restaurants %} <tr data-id="{{ restaurant.id }}"> <td class="editable-field" data-field="address">{{ restaurant.address }}</td> <td class="editable-field" data-field="phone">{{ restaurant.phone }}</td> <td class="editable-field" data-field="district">{{ restaurant.delivery_code.district }}</td> <td class="editable-field" data-field="menu">{{ restaurant.menu_code.name }}</td> <td> <button class="btn btn-danger" data-toggle="modal" data-target="#confirmDeleteModal{{ restaurant.id }}"> delete </button> <div class="modal" id="confirmDeleteModal{{ restaurant.id }}" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="confirmDeleteModalLabel">Confirmation of deletion</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div … -
Django Admin not working on Azure App service
I have a Django Restful API hosted on Azure App Server. For Admin page, all static files are generated and place on a folder which configure on settings.py. BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") But when try to access admin page from browser static files return with 500 http status code. Backend logs shows AttributeError: This FileResponse instance has no `content` attribute. Use `streaming_content` instead. Can some one help on this please? -
Django Admin filter DateRangeFilter preserve date after search
I have used django filter in admin with list filter in django below is my search filter form image what issue I am facing is that whenever I filter using date ranges like (from and to) date filters works fine but 1 issue is that the date filters gets wiped after 1 search meaning If i click search button the date forms becomes empty like above I need to prevent this i have my code here any way to preserve search if date is provided in form so that upon clicking the search button does not gets cleared again from rangefilter.filters import DateRangeFilter @admin.register(UserPolicy) class UserPolicyAdmin(BaseModelAdmin): change_form_template = "payment/unsubscribe_button.html" change_list_template = 'common/download_csv.html' form = UserPolicyModelForm list_filter = ( ('created', DateRangeFilter), 'is_archived', 'is_active', ) list_display = ( 'policy', 'users', 'payments', 'payment_logs', 'start_date', 'is_active', 'end_date', 'payment_mode' ) search_fields = ( 'user__phone_number', 'registration_id' ) -
Write unittest case if a method or function returns array or list?
Here the question is that how to write test case for a Model mothod or function who returns an array or list? from django.db import models class Task(models.Model): title = models.CharField(max_length=100, blank=True) desc = models.TextField(blank=True) tags = models.TextField(null=True, blank=True) # function to split tags def tag_list(self): taglist = self.tags.split(',') return taglist Here tag_list is that function who returns list of tags Here i am expecting to write a unittest case for tag_list method -
login with superuser nog working in django admin panel
So I built this custom auth model because I want to use the email instead of the username field which is default for django. AUTH_USER_MODEL = 'customers.Customers' This I have in my settings.py from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.contrib.auth.models import UserManager # Create your models here. class CustomerManager(UserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Customers must have an email address') user = self.model( email=email, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, name, last_name, email, phone, password, **kwargs): kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_staff', True) return self._create_user(email, password, **kwargs) class Customers (AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(blank=False, unique=True) phone = models.CharField(max_length=15) password = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(blank=True, null=True) objects = CustomerManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name', 'last_name', 'phone'] class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' def get_full_name(self): return self.name + ' ' + self.last_name def get_short_name(self): return self.name def check_password(self, password): return self.password == password This is my custom auth model. I have succesfully created … -
How to write unit test case for due date validation ? How to unit test DateField or DateTimeField validation?
Here main question is that how to write unittest cases for due date validation with DateField or DateTimeField we can do it through multiple methods & i will answer you those methods So basically in models.py from django.db import models from django.forms import ValidationError class Task(models.Model): title = models.CharField(max_length=100, blank=True) desc = models.TextField(blank=True) time_stamp = models.DateField(auto_now_add=True, null=True, blank=True) due_date = models.DateField(null=True, blank=True) # logic for due_date def clean(self): super().clean() if self.due_date < self.time_stamp: raise ValidationError("Due date must be greater than current date") I am expecting to test this clean() validation method, in case when due date is less then start_date or time_stamp it should through ValidationError -
ordering = ['-date_posted'] does not work
I have this class and I wanted to sort the posts of my blog by date posted but it does not work and gives me this error what should I do? Thanks in advance FieldError at / Cannot resolve keyword 'date_posted' into field. Choices are: author, author_id, body, id, title views.py from django.shortcuts import render, redirect from django.http import HttpResponse from datetime import datetime from posts.models import post from django.contrib.auth import authenticate, login from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic import ListView # Create your views here. class PostListView(ListView): model = post template_name = 'website/welcome.html' context_object_name = 'posts' ordering = ['-date_posted'] urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users.views import signup, profile from django.contrib.auth import views as auth_views from posts import views from website.views import index from website.views import PostListView urlpatterns = [ path('admin/', admin.site.urls), path('', PostListView.as_view(), name='home'), path('posts/', include('posts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path('profile/',profile, name='profile'), path('', index, name='index'), ] -
Psycopg[binary] and psycopg2 not working in my virtual enviornment for my django project
When I try to run the command docker-compose exec web python3 manage.py startapp accounts This command outputs the following complete error message. Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 58, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.10/site-packages/django/db/models/options.py", line 243, in contribute_to_class self.db_table, connection.ops.max_name_length() File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 193, in create_connection backend = … -
Issue with requests from Nuxt.js not adding cookies to Django server
I'm working with a Nuxt.js frontend and a Django backend and encountering an issue where cookies are not being set correctly after JWT authentication. My Nuxt.js app is running on https://localhost:3000 and the Django server is on https://localhost:8000. Despite successful authentication using JWT tokens, when I make a request to the server, the cookies are not being attached. Checking the Network tab, I noticed that the client-side isn't sending cookies. Here's my Django settings related to CORS and cookies: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "https://localhost:3000", ] # Other settings... SESSION_COOKIE_SAMESITE = 'None' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CORS_ALLOW_CREDENTIALS = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] And this is how I'm making the request in Nuxt.js: <template> <div> <h1>User Profile</h1> <form @submit.prevent="getUserInfo"> <button type="submit">UserInfo</button> </form> </div> </template> <script> import axios from 'axios'; export default { methods: { async getUserInfo() { try { const response = await axios.get('https://localhost:8000/api/userinfo/', { }, { withCredentials: true }); console.log(response.data); } catch (error) { console.error(error); } }, }, … -
AJAX is only getting data from last form in loop (Django)
I have a for loop that creates a number of forms on the page. I want to be able to submit these forms to another page without refresh using AJAX, however no matter which form I submit it only ever shows the value for the very last form. HTML code {% for post in post_list %} <form class = "f_form" id="f_form" name = "myForm" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="add">Submit</button> </form> {% endfor %} Jquery <script type="text/javascript"> $(document).ready(function(){ $(document).on('click','.add',function (event) { event.preventDefault(); var element = $(this); $.ajax({ url: '{% url "webscraper-favorited" %}', method: 'post', data:element.parent('.f_form').serialize(), success: function(data){ $('#message').html(data); } }); return false; }); }); </script> views.py def favorited(request): if request.method == 'POST': favorited = request.POST.get('favorited') favorites.append(favorited) print(favorited) context = { 'favorites' : favorites, } return render(request, 'webscraper/favorited.html', context) Right now the script is outside of the for loop but I previously tried putting it in the for loop as well. Instead of binding the script to the submit button I also tried binding it to the form id. That yielded the same result from my attempts. -
InconsistentMigrationHistory
I unfortunately deleted contenttypes app from django_migrations in psql(pgadmin4) database. From then when i'm trying to run py manage.py makemigrations it returns " raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration auth.0001_initial is applied before its dependency contenttypes.0001_initial on database 'default'. " My entire project was collapsed. Any solution please.......... As these migrations are automatically created by django i cant eeven understand where to modify the code. -
RTCPeerConnection Issue: Uncaught DOMException - Failed to execute 'setRemoteDescription' on 'RTCPeerConnection Django
I am encountering an issue with my WebRTC implementation in Django using Django Channels. The error I am facing is: "Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable" After some research, I found a possible explanation for this error on Stack Overflow. It seems to be related to the fact that when a third user joins, it sends an offer to the two previously connected users, resulting in two answers. As a single RTCPeerConnection can only establish one peer-to-peer connection, attempting to setRemoteDescription on the second answer fails. The suggested solution is to instantiate a new RTCPeerConnection for every remote peer. However, I'm unsure how to implement this in my existing code. Below is the relevant portion of my consumers.py and JavaScript code. consumers.py and JavaScript code import json from typing import Text from django.contrib.auth import authenticate from Program.models import ChatRoom, Message from channels.generic.websocket import AsyncWebsocketConsumer from .service import add_remove_online_user, updateLocationList, add_remove_room_user from asgiref.sync import sync_to_async from channels.db import database_sync_to_async class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.authenticate_user() await self.channel_layer.group_send( self.room_group_name, { 'type' : … -
How to rreturn a nested serialized data in Django
I created a Registration view in my Django app, but when I tried testing it, I wasn't getting the expected result. I'm trying to test my view with the data below, but I wasn't getting the expected result: { "email": "faruqmohammad@gmail.com", "first_name": "Faruq", "last_name": "Mohahmmad", "phone_number": "08137021976", "password": "#FaruqMohammad1234", "confirm_password": "#FaruqMohammad1234", "vehicle_registration_number": "ABJ145", "min_capacity": 20, "max_capacity": 50, "fragile_item_allowed": true, "charge_per_mile": 1000 } And the response I get is { "data": { "user": { "email": "mohammedfaruq@gmail.com", "first_name": "Mohammed", "last_name": "Faruq", "phone_number": "08137021976" }, "is_available": true, "vehicle_type": "TWO_WHEELER", "vehicle_registration_number": "", "min_capacity": null, "max_capacity": null, "fragile_item_allowed": true, "ratings": null, "charge_per_mile": null }, "message": "Rider registration successful" } {"vehicle_registration_number": "", "min_capacity": null, "max_capacity": null, "fragile_item_allowed": true, "ratings": null, "charge_per_mile": null} These values are set to the default value from the model even when I provided them And below is my model, serializer and views Model: class Rider(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, related_name="rider_profile" ) vehicle_type = models.CharField(max_length=50, default="TWO_WHEELER") vehicle_registration_number = models.CharField(max_length=20, unique=True) is_available = models.BooleanField(default=True) min_capacity = models.PositiveIntegerField(null=True, blank=True) max_capacity = models.PositiveIntegerField(null=True, blank=True) fragile_item_allowed = models.BooleanField(default=True) charge_per_mile = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) current_latitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) current_longitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) ratings = models.DecimalField(max_digits=3, decimal_places=2, …