Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
backend.quote_name not working, suggest somthing to make this work
` def dump_model(model): from django.db import connection, backend opts = model._meta cursor = connection.cursor() fields, default = get_model_stru(model) cursor.execute('select %s from %s' % (','.join(map(backend.quote_name, fields)), backend.quote_name(opts.db_table))) return call_cursor(opts.db_table, fields, cursor) ` Django version I am using is 1.6.7,I tried connection.ops.quote_name, str(), also tried defining quote_name nothing seems to working -
Django Form, how to get further model info for ModelChoiceField
I have 3 models that are related to eachother. A showing has the 'film' and 'screen' foreignkeys that link to Film and Screen. I'm trying to setup a webpage so that you can view information on a showing that is already setup, and edit it from dropdowns of what films and screens are available. The problem I have at the moment is that instead of showing the screen numbers, and film titles that can be selected from, my dropdowns are showing 'Screen Object (4)' or 'Film Object (2)'. How do I get that next level of information to show from each object? My models are: class Film(models.Model): ageRatings =[ ("U", "U"), ("PG", "PG"), ("12", "12"), ("15", "15"), ("18", "18"), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) length = models.DurationField() rating = models.CharField(max_length=3, choices=ageRatings, default="U") genre = models.CharField(max_length=50) poster_url = models.CharField(max_length=255, default='') class Screen(models.Model): id = models.AutoField(primary_key=True) cinema = models.ForeignKey(Cinema, on_delete=models.CASCADE, related_name='screens') screen_number = models.PositiveSmallIntegerField() seating_capacity = models.PositiveIntegerField() class Showing(models.Model): id = models.AutoField(primary_key=True) film = models.ForeignKey(Film, on_delete=models.CASCADE, related_name='showings') screen = models.ForeignKey(Screen, on_delete=models.CASCADE, related_name='showings') start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) available_seats = models.IntegerField() adult_price = models.FloatField() student_price = models.FloatField() child_price = models.FloatField() def save(self, *args, **kwargs): self.end_time = self.start_time + self.film.length super().save(*args, … -
django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id
I have created a custom model on django to create users and superuser, and now when i try to create a superuser, i get the following error django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) user = self.model( email=email, name=name ) # creates a new model that the manager is representing user.set_password(password) user.save(self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(self._db) return user # is_superuser is automatically created by PermissionsMixin class UserProfile(AbstractBaseUser, PermissionsMixin): """Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] def get_full_name(self): """Retrieve full name of user""" return self.name def get_short_name(self): """Retrieve short name of user""" return self.name def __str__(self): """Return string representation of our user""" return self.email I added the model in the settings.py … -
Django: python manage.py runserver exits with ‘Performing system checks, what is the possible issue?
I am working on a django project and have been using python manage.py runserver to spin up my development local server, but it just started exiting at Performing system checks. This is the first time i am encountering such issue, have any one experienced this issue before, please how do i go about it? C:\Users\Destiny Franks\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj> This is how everything looks, it does not show any error message or issue, just breaks off and return to the cmd -
Check if a code exists in Django Database
I'am trying to check if a value exists in one of my database fields so this is my models.py class Student(models.Model): username = models.CharField(max_length=200, null=True, blank=True, verbose_name='نام کاربری') code = models.CharField(max_length=10, null=True, validators=[MinLengthValidator(10)], blank=True, verbose_name='کد ملی') def __str__(self) -> str: super(Student, self).__str__() return self.username class Meta: verbose_name = 'دانش آموز' verbose_name_plural = 'دانش آموزان' I can create a model in django's panel but the thing that I want, is Checking if a property of this class exists this is my views.py class LoginView(View): def get(self: Self, request: HttpRequest) -> HttpResponse: login_form: LoginForm = LoginForm() return render( request=request, template_name='index.html', context={ 'login_form': login_form, } ) def post(self: Self, request: HttpRequest) -> Union[HttpResponseRedirect, HttpResponsePermanentRedirect, None]: login_form: LoginForm = LoginForm(request.POST or None) if (login_form.is_valid()): username = login_form.cleaned_data.get('username') code = login_form.cleaned_data.get('code') # I want to check if " code " is in database # if it exists, login # else show an error I want to check if the code variable value, exists in my database and if it exists, login else show an error I expect my code check the value existance but I don't know how to do that -
Using ForeignKey key Django to reference the 'id' from another table
I want to use the user_id as a foreign key in CPA table here is my model ---models.py---- and on the Django admin admin page It show all of the user data. **Please note that the person detail on the image have been generated using Faker. I have try using this user_id = models.ForeignKey(User,to_field='id', on_delete=models.CASCADE, default=1) I want it to show just the id number which is 1 as follow expected value How can I do that?? Thank you for your reply -
Django's bulk_create doubts
I'm adding this function to my Django app, but I have a couple of questions I need to know and which I couldn't find in Google. Does it insert all records in the order the list is given? Or can they be suffle? Can I know which id corresponds to the index in the list of the items to give? In case an error happened will it prompt which one failed, and will continue inserting the others, or will it stop inserting the rest of elements? -
Updated data don't seem in DRF api response
The updated data doesn't seem in api response. When I add or update some data in admin panel it doesn't affect to api response. To fix it i must write docker-compose restart. How can i fix this problem I supposed that this problem comes from caches issue. Therefore i add cache configuration in settings like this: `CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } }` But it doesn't fix problem -
how to add Comment form inside a post detailed
Is there any way I can add a comment form inside a post's details? I have a view that shows a model object, and I want to allow users to comment on that view. I have tried to use this method, but using that method, a user should leave a post's details and add their comment somewhere else rather than doing it inside a post's details? I have try to do that using the method below, but it gives me an error every time I clicked on submit button: TypeError at /video-play/so-da-shakuwa/ Field 'id' expected a number but got <Video: videos/DJ_AB_-_Masoyiya_Official_Video_9UfStsn.mp4>. views: def play_video(request, slug): play = get_object_or_404(Video, slug=slug) if request.method == 'POST': comments = request.POST['comments'] new_comment = Comment.objects.create( comments=comments, post_id=play ) new_comment.user = request.user new_comment.save() return redirect('Videos') context = { 'play':play } return render(request, 'video/play_video.html', context) template: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col-md-9"> <form action="" method="post"> {% csrf_token %} <div class="input-group"> <textarea name="comments" id="comment" cols="10" class="form-control" placeholder="write your comment"></textarea> <button class="btn btn-primary" type="submit">submit</button> </div> </form> </div> </div> </div> models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) class Comment(models.Model): user … -
Wrong Routing Django
I have a Django project with this layout in baseApp views.py def Home(request): rooms = Room.objects.all() context = {'rooms':rooms} return render(request,'base/home.html',context) def room(request,pk): room = Room.objects.get(id=pk) context = {'room':room} return render(request,'base/room.html',context) def createRoom(request): context= {} return render(request,'base/room_form.html',context) in baseApp urls.py urlpatterns = [ path('', views.Home, name="home page"), path('<pk>/', views.room, name="room"), path('create-room/',views.createRoom, name="create-room"), ] in the base/temp/home.html <h2> <a href="{% url 'create-room' %}">Create Room</a></h2> it supposed to go to to this url : 172.0.0.1:8000/create-room/ " to room_form.html" but it goes to : 172.0.0.1:8000/room/create-room with error Field 'id' expected a number but got 'create-room' I am Expecting it supposed to go to to this url : 172.0.0.1:8000/create-room/ showing room-form.html -
Creating a fully functional website that can be used [closed]
I need help, can someone please help me in finishing creating a website, it is a project I am supposed to be done with by Wednesday, I need help making the links active and functional where after clicking a website it directs you to a webpage with information also, the buttons to be made functional The website should be responsive and active and can be used the website currently looks like this: https://afia.azurewebsites.net/ourhospital/ the github repo link is: https://github.com/abayomiabiodun/AFIA-MBELE.git PLEASE HELP THANKS SOMEONE TO KINDLY HELP IN FINISHING THE WEBSITE -
Django query __in filter on subquery joined over multiple fields without foreignkey
Short: This is the SQL I try to achieve in django: with start_dates as ( select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id ) select * from my_table m inner join start_dates sd on m.person_id = sd.person_id and m.date_current >= sd.start_date ; Long: There is a table which I need to access twice. The table constists of activities of people. Each people has multiple activities so multiple rows in this table. 1) First access is to find for a set of given filters (like the name of the acitivity and the age of the person) which persons activities fit the filters and per person what is its oldest acitivity fitting the filters. I call that oldest-date "start_date". On SQL this could look like: select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id With this query I found a sub-set of people with their oldest filtered-activity (so there may be also older activities which do not fit the filters above) Sample A sample would be to find all people ever did taking drugs plus the date when it happened first. 2) Second access is to get for every person found all its … -
login with LinkedIn: Django REST and React.js
I've got problems with authentication with LinkedIn. In my React app, I created LoginButton component following documentation for react-linkedin-login-oauth2. import { useLinkedIn } from 'react-linkedin-login-oauth2'; import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png'; function Login() { const { linkedInLogin } = useLinkedIn({ clientId: '78j5bjwgkxxxxx', redirectUri: 'http://127.0.0.1:8000/dj-rest-auth/linkedin/', onSuccess: (data) => { console.log(data) }, onError: (e) => { console.log(e) } }); return ( <img onClick={linkedInLogin} src={linkedin} /> ); } export default Login That button is kinda working. As far as I'm understanding, 'redirect_URI' should point backend view, it redirects me to http://127.0.0.1:8000/dj-rest-auth/linkedin/ with code and state. But backend doesn't log me in automatically and manually (I'm trying to paste "code" form URL to "code" in form below. Then I'm getting that: My backend should work (I did everything following documentation for dj-rest-auth and allauth) from allauth.socialaccount.providers.linkedin_oauth2.views import LinkedInOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class LinkedinLogin(SocialLoginView): adapter_class = LinkedInOAuth2Adapter client_class = OAuth2Client callback_url = 'http://127.0.0.1:8000/dj-rest-auth/linkedin/' from django.urls import path from . import views urlpatterns = [ path('accounts/', include('allauth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/linkedin/', views.LinkedinLogin.as_view(), name='linkedin_login'), ] Next issue is, after login with button from frontend, I'm getting "user closed the popup" error, I'm not closing or unfocusing anything, in other worlds onError is running, … -
How to deal with Django Cascade deleted objects in django-simple-history?
I have a problem with django-simple-history when I use cascade deletion on objects. I have several tables in my database that inherit from other tables, so I’ve set the deletion to cascade. The problem is that when I want to query Historical Objects generated by django-simple-history, I do have the one in the parent table, but for objects in the children table, that were automatically deleted by Django, I this error : MyApp.models.parentTable_object.DoesNotExist: parentTable_object matching query does not exist. If I understand the problem, django-simple-history tried to create a Historical object for my deleted object but failed because it needed the parent object it inherited and that no longer exists at this point. I can’t do without cascading so I hope it’s possible because django-simple-history has met all my expectations so far. Thanks you for your help My environment: OS: Windows 10 Browser: Firefox Django Simple History Version: 3.1.1 Django Version: 4.0.3 Database Version: django's integrated SqLite3 -
AttributeError: type object 'object' has no attribute 'id'
I am trying to add permissions to my Django Rest Framework Project, but i get an error: AttributeError: type object 'object' has no attribute 'id' My permissions.py file looks like this: from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): """Allow users to edit their own profile""" def has_object_permission(self, request, view, obj): """Check user is trying to edit their own profile""" if request.method in permissions.SAFE_METHODS: return True return object.id == request.user.id My views.py class for the UserProfile looks like this: class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = ( TokenAuthentication, ) permission_classes = ( permissions.UpdateOwnProfile, ) My serializers.py file: class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user profile object""" class Meta: model = models.UserProfile fields = ("id", "email", "name", "password") extra_kwargs = { "password": { "write_only": True, "style": { "input_type": "password" }, } } def create(self, validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data["email"], name=validated_data["name"], password=validated_data["password"], ) return user def update(self, instance, validated_data): """Handle updating user account""" if "password" in validated_data: password = validated_data.pop("password") instance.set_password(password) return super().update(instance, validated_data) The traceback of the error: Traceback (most recent call last): File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 145, in _get_response response = … -
Choice field validation DRF
Hi all I have my model and its serializer, what I discovered when testing is that serializer is saved no matter what I have in my choice field but in Django admin choice field is empty when the data is wrong and when the data is right I can see the correct option so, -> wrong choice data -> saved regardless -> nothing in django admin -> correct choice data -> saved -> correct value in django admin How can I return validation error if I detect that user posted incorrect data? what I was trying out is topic = serializers.ChoiceField(choices=School.topic) and I don't think that iterating over each tuple and searching for a string is correct or efficient code class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.all() serializer_class = SchoolSerializer def create(self, request): serializer = SchoolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class School(models.Model): SUBJECT = ( ('Math', 'Mathematic'), ('Eng', 'English'), ('Cesolved', 'Chemistry'), ) name = models.CharField(blank=False, max_length=50) subject = models.CharField(choices=SUBJECT, max_length=15, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(f'{self.name} is {self.subject}') class SchoolSerializer(serializers.ModelSerializer): subject = serializers.ChoiceField(choices=School.SUBJECT) def validate(self, data): name = data["name"] if (5 > len(name)): raise serializers.ValidationError({"IError": "Invalid name"}) return data class Meta: … -
Can i use django.db.transaction.atomic with ThreadPoolExecutor?
I have a large set of Projects to validate and update with transaction in 1 perform. If 1 project failed it need to rollback all projects. but when i use ThreadPoolExecutor it got stuck with no log ERROR or WARNING even with max_workers=1. from concurrent.futures import ThreadPoolExecutor, wait @transaction.atomic def update_projects() projects = Project.objects.filter(...) items = [(project, auth) for project in projects] with ThreadPoolExecutor(max_workers=MAX_WORKER) as executor: futures = [executor.submit(validate_and_update, *item) for item in items] wait(futures) def validate_and_update(project, auth): # get other data and validate with project. project.save() i tried multiprocessing instead of threading but it got other error like: "no results to fetch" "pop from empty list" pool = multiprocessing.Pool(processes=2) for item in items: pool.apply_async(validate_and_update, *item) # close the pool pool.close() # wait for all tasks to complete pool.join() -
Why is Source Control (VScode) asking to commit every single file on my computer to git?
I am trying to create project using Python and Django, using a virtual environment. This is how I set up the project in terminal: cd MyProject python3 -m venv env source env/bin/activate pip install django django-admin startproject (projectname) When I go to open the file in VSCode, source control scans and prompts to commit every single file on my computer (including files in the trash) to Git, to the point where it says "Too many changes were detected. Only the first 10000 changes will be shown below". Why is this happening? I tried right clicking and doing 'discard changes' but it ended up deleting files. -
issue when using django(daphne) and scrapy together
Im having issues getting my scrapy spider to work with django when using daphne. i noticed that when i use the normal wsgi server ie. without adding daphne to the list of installed apps, everything works fine as expected. but with daphne, my spider gets stuck after initial requests and never gets to parse. i have made a minimalistic reproduction of the issue , and would be very greatful with anyone can explain why this issue occurs and how to go about it resolving it. thanks PS: this is just a reproduction of the issue, as for why i need daphne, my project uses django channels project structue daphne_scrapy/ ├── daphne_scrapy │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── spiders.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 └── manage.py settings.py (these were the only changes made to the settings.py file, added daphne and asgi_app) INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] WSGI_APPLICATION = 'daphne_scrapy.wsgi.application' ASGI_APPLICATION = 'daphne_scrapy.asgi.application' spider.py note: i need to do the django setup because my spider needs to made use of django models in the real project im working on. import scrapy from scrapy.crawler import CrawlerProcess … -
Docker python: can't open file 'manage.py': [Errno 2] No such file or directory
I have two questions at once (Main)I'm trying to deploy a Django project on Docker and I get a python error: can't open file '/backend/manage.py': [Errno 2] No such file or directory Can I use env_file instead of environment for Postgres ? Project structure films -backend -config -__init__.py -asgi.py -settings.py -urls.py -wsgi.py -manage.py -venv -.env -docker-compose.yml -Dockerfile -requirements.txt enter image description here Dockerfile FROM python:3.10 COPY requirements.txt /temp/requirements.txt WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN pip install -r /temp/requirements.txt COPY . . docker-compose.yml version: '3.7' services: web: build: . container_name: films command: > sh -c "python manage.py migrate && python manage.py runserver" ports: - "8000:8000" depends_on: - db env_file: - .env db: image: postgres container_name: db_film environment: - POSTGRES_DB=films - POSTGRES_USER=username - POSTGRES_PASSWORD=password -
Getting an error No module named 'learning_logs' when running application in Heroku
I am working on the Django tutorial from Python Crash Course and unable to get the Learning Log application to run from Heroku.I have tried all the possibilities but still not being able to get it to run. Below is the log data : 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 688, in _load_unlocked 2023-04-23T23:52:40.244383+00:00 app[web.1]: File "", line 883, in exec_module 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "", line 241, in _call_with_frames_removed 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/learning_log/learning_log/wsgi.py", line 18, in 2023-04-23T23:52:40.244384+00:00 app[web.1]: application = get_wsgi_application() 2023-04-23T23:52:40.244384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-04-23T23:52:40.244384+00:00 app[web.1]: django.setup(set_prefix=False) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/init.py", line 24, in setup 2023-04-23T23:52:40.244385+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-04-23T23:52:40.244385+00:00 app[web.1]: app_config = AppConfig.create(entry) 2023-04-23T23:52:40.244385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-04-23T23:52:40.244386+00:00 app[web.1]: import_module(entry) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2023-04-23T23:52:40.244386+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1050, in _gcd_import 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1027, in _find_and_load 2023-04-23T23:52:40.244386+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2023-04-23T23:52:40.244387+00:00 app[web.1]: ModuleNotFoundError: No module named 'learning_logs' 2023-04-23T23:52:40.244482+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [7] [INFO] Worker exiting (pid: 7) 2023-04-23T23:52:40.339083+00:00 app[web.1]: [2023-04-23 23:52:40 +0000] [8] [ERROR] Exception in worker process 2023-04-23T23:52:40.339084+00:00 app[web.1]: Traceback (most recent call last): … -
Django daphne: Apps aren't loaded yet
When i try to run daphne -p 8001 messanger.asgi:application I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If i run server without daphne, I get this error: Listen failure: Couldn't listen on 127.0.0.1:8000: [Errno 48] Address already in use. This is my settings .py: INSTALLED_APPS = [ "channels", "chat", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django_extensions', ] ASGI_APPLICATION = "messanger.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URL", "redis_url")], }, }, } This is my asgi.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "messanger.settings") django_asgi_app = get_asgi_application() django.setup() application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(chat.routing.websocket_urlpatterns) ) ), }) This is my consumer.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name # Join room group channel_layer = get_channel_layer() async_to_sync(channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] author_id = text_data_json["a"] chat_id = text_data_json["chat"] message_create = Message(content=message, author_id=author_id, chat_id=chat_id) message_create.save() print("message:", message, "author_id:", author_id, "chat_id:", chat_id) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( self.room_group_name, { "type": "chat_message", "message": message, "author_id": author_id, "chat_id": chat_id } ) def chat_message(self, event): message = event["message"] author_id = event["author_id"] author_username = User.objects.get(id=author_id).username chat_id = event["chat_id"] self.send(text_data=json.dumps({ "type": "chat", … -
How do I compare the values gotten from html checkbox to id of same values in database?
I am fairly new to Django and I use the 4.2 version. This is my problem. I am building a blog website, I was trying to add multiple values(tags) for each blog post, from the HTML template checkbox input to my database, which is PostgreSQL. In that database, I already have pre-stored values of items in a Tags table. This table has a ManyToMany relationship with the main Blogpost class. But I am having problems with this particular process. I am trying to add tags for each blogpost created, from the tags already set in the Tags table. The idea is that a user selects the tags they want to include in their blogpost and in the manytomany table, the ids of the tags and the blogpost are set, when the blogpost is saved. I understand that I am to get the id of the values I am trying to add from my database where they exist and include them in the blogpost but I don't exactly know how to do this. This is what my code looks like: models.py class BlogPost(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key='True', editable=False) post_title = models.CharField(max_length=300, blank=True, null=True, verbose_name='Title of blog post') post_image = models.ImageField(upload_to='posts/%Y/%m/%d', … -
comment remonter ce problème : Erreur d'intégrité Échec de la contrainte UNIQUE : account_user.username
j'ai crée mon view de login quand je me connecte il m'affiche cette erreur voila view coresspand -
django Warning 302 in post from UpdateView
"Hello, what I need is to add a record in one model (Historico) and update the status of a record in another model (Factura) in the same form. However, I am getting a 302 error in the console. [23/Apr/2023 18:02:40] "POST /facturas/actualizar/1 HTTP/1.1" 302 0 This is my form: class FormActualizarFactura(forms.ModelForm): comentario = forms.CharField(widget=forms.Textarea) class Meta: model = Factura fields = ('estado', 'etapa', 'email', 'comentario') This is my view: class ActualizarFactura(UpdateView): model = Factura form_class = FormActualizarFactura template_name = 'facturas/fac_actualizar.html' success_url = reverse_lazy('facturas:listaFacturas') def post(self, request, *args, **kwargs): try: if super().post(request, *args, **kwargs): historico = Historico() historico.factura = isinstance(self.object, Factura) and self.object or None historico.estado = self.object.estado historico.user = request.user historico.comentario = request.POST.get('comentario') historico.save() else: # Se produjo un error al actualizar la factura messages.error(request, f'Error al actualizar la factura: {self.object.NFactura}') except Exception as e: # Se produjo un error general messages.error(request, f'Error general: {e}') return redirect('facturas:listaFacturas') Can you help me or should I implement another method to have two separate forms (but validated in a single HTML form) and each one perform its function in a TemplateView?" Update the status of a record in one model and add it to the Historico table, all from the same form.