Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending a zip file from hug framework to Django
Background: I am working on a microservice architecture, which has a Django app as a middle communicator. The services are written in hug. Problem: I am uploading a zip file in hug and trying to send it via a post request to Django application, unfortunately the file that I am receiving in hug function is byte string. and post is not able to send it mentioning following error. File "/usr/local/lib/python3.8/cgi.py", line 577, in __bool__ | raise TypeError("Cannot be converted to bool.") my hug function looks like this. def bulkUploadUserPhotos(request, file): apiURL = DJANGO_APP_URL # file is coming from a request. # error coming in below line apiResponse = requests.post( apiURL, files = file ) if apiResponse: return apiResponse.json() else: return { 'msg': 'Failed' } when I try to print file I receive following byte like data. \x8e\t\x8enH9\xa5\xa9\xfe\xa4\x8a\xf2\xeb\'\xb3g\xf7-B\xdd\x03\xbb\xab\x04\xf9\xa9\xfa\r\x0e\x88)){Pc\x94\'\xd2\xb9\xfc^Do\x83$^\x9d/2\xf4\xe7\xeb\xa3\xe1\xfd\xcd\x97\xdbF\x01\xa9=\xd6\xee\xacR\'L^W\xea\xc9\x9a\x82\xd5\xdc%\xd2\r\xeb\xf6\xb3\x93\xee\xf9\x1aJ"\x18\x17R\xe8j\xd9\xbfO\xec|\xe7L\x83V\xff\xc0\xd9\xd9\x19\xf8\xba\x84\xaa%\xf3)\\\t\x93R\x7f\x15\x95R\xa8\x9f\xb5mX<v\x19_\xa6\xeb\xdd\xa7\xbb6\r\x93D\x00\x1c\xd5\n\\\xd0`\xa3 u\xfc\xf53\x1c\x1cZ\xbb\x18\xd0\x1c~\xfc#\xf3\x81\xa5"\x90\xaaIG\x9e\xf4\xa6h\xbf\x96\xe13\xf3\x80e\x94\x9fU*\xc23vXa\xa3\xcb\x89\xa8}\xf4,\xb8Ld\xf8\x91\x1b\x8b\x82:\xa7X$2\xf9\xf2\xf7I\x9f\xb67\xab\x8b>\xe3$\xa1\x08\xb1\x14\xc3\x84\x9c\xcc=^\x8e\xbc\xf5m\x88Pn\xda\xc0\xd2\xc3&)\xabT\x07+\xf8\xf9\x12\x8d\xf0\xa4\xdf>g5R\xce\x89fD\x9d\x80\x11\x99G\xd1\xa9X\xfb\'yX\x04\xb7\x8b\x91\xcc\x99+/\xe7uZ\xff\xd8, -
Getting unique value on the base of Role
I have model name Movie which have many-to-many Relation with Actor Table. Actor Table is further many-to-many relation with Celebrity-Role. My question is i need only unique values on the base of roles Like Actors who's role is Director they show in Movie Table field with Director and only directors should be there and so on. i share my models please have a look. class CelebrityRole(models.Model): CELEBRITY_CHOICES = ( ('Actor', 'Actor'), ('Producer', 'Producer'), ('Writer', 'Writer'), ('Director', 'Director'), ) role = models.CharField(max_length=8, choices=CELEBRITY_CHOICES) def __str__(self): return self.role class Actor(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) name = models.CharField(max_length=200) rank = models.CharField(max_length=5, default=0) gender = models.CharField(max_length=6, choices=GENDER) avatar = models.ImageField(upload_to='CelebrityGallery/', blank=True) description = models.TextField(blank=True) birth_place = models.CharField(max_length=200, blank=True) dob = models.DateField(auto_now=False, auto_now_add=False) height = models.CharField(max_length=20) is_married = models.BooleanField(default=False) movies = models.ManyToManyField( 'movies.Movie', related_name='movies', blank=True) celebrity_role = models.ManyToManyField(CelebrityRole) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here is my Movie Table class Movie(models.Model): title = models.CharField(max_length=200) year = models.CharField(max_length=25, blank=True) description = models.TextField(blank=True) released = models.CharField(max_length=25) runtime = models.CharField(max_length=25) language = models.CharField(max_length=255) country = models.CharField(max_length=100) metascore = models.CharField(max_length=5, blank=True) imdb_id = models.CharField(max_length=10, blank=False, unique=True, default='tt3032400') imdb_rating = models.CharField(max_length=5, blank=True) imdb_votes = models.CharField(max_length=100, blank=True) budget = models.CharField(max_length=25) box_office = models.CharField(max_length=25, … -
Can I get a code for getting id using javascript and ajax
I am new to development and dont have much idea about this please help me, I am unable to get the code for taking id of the absent student using javascript please help me with it. This is my html code where the list of students is displayed, all student by default are present and I if i mark some student as absent all other students should be saved as present and other marked as absent which were selected HTML code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table"> <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {% for student in students %} {% if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year %} <tr> <td style="color:white;"><input type="hidden" name="student_name" value="{{student.id}}" >{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> … -
I want a free alternative. What can I use, is there?
I can't use Rds in my django database I want a free alternative what can I use And is there a way to use Rds without an AWS account -
How to customize/filter django admin panel forms data?
I created models as below; Team model stores different team names, Tournament model is used to create a tournament and add teams into it and finally Game model where I select a tournament, add two teams and create a game. My problem is in Admin panel, while creating a game after selecting a tournament I have to select two teams, in the choice list I am getting all the available teams in the Teams database, instead of just the teams participating in the tournament. class Team(models.Model): name = models.CharField(max_length=30) # Ind, Pak, Aus, Sri, Eng class Tournament(models.Model): name = models.CharField(max_length=50) # Asia Cup: teams = models.ManyToManyField(Team) # Ind, Pak, Sri class Game(models.Model): name = models.CharField(max_length=50) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) # Asia Cup teams = models.ManyToManyField(Team) # Expected: Ind, Pak, Sri My Admin panel customization: class TeamInline(admin.TabularInline): model = Game.teams.through class Game(admin.ModelAdmin): fields = ['name'] inlines = [TeamInline] -
Django CMS - How to add background image in cms
I have been using placeholder to change images and text in html template like this {% block newsimage %} {% placeholder "newsimage" %} {% endblock newsimage %} But in one particular html file the background image have been called from class using css for example- html <div class="container"> In css .container { background: url(../images/sample.jpg); background-size: cover; background-repeat: no-repeat; height: 468px; } So That I cant able to add placeholder for this image how can i add background image for this template in django cms? -
Vs code could not fint models values in django
My models.py: class Service(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) name = models.CharField(max_length=255) price = models.CharField(max_length=255, null=True, blank=True) And my views.py: service = Service.objects.get(id=pk) When I want to show which values have in Service object, Vs code doesnt prompt list of values. For instance, When I tpye id=pk, na, it must prompt value name of models Which extension Have to I install? -
Updating or saving a form field using cleaned_data in Django not working
It is simple, but I don't know why it is not working! I just want to set my TOTAL field from the form with the PRE-TOTAL value. It is updating my FORM_DATA (instance using cleaned_data), but not saving! It is still coming with the default value!!! Would someone tell me why? Here go the codes: MODELS.PY from django.db import models from django.utils import timezone class av_pomades(models.Model): cod_prod = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) price = models.FloatField(default=0) pic = models.ImageField(default='default.jpg', blank=True) def __str__(self): return self.name pomades_to_chose = ( ('Suavecito - water based','Suavecito - water based'), ('Reuzel Blue - water based','Reuzel Blue - water based'), ('Layrite - water based','Layrite - water based'), ('Suavecito - oil based','Suavecito - oil based'), ('Reuzel Pink - Oil Based','Reuzel Pink - Oil Based'), ('Layrite - oil based','Layrite - oil based') ) class order_form(models.Model): pomade = models.CharField(max_length=100, choices=pomades_to_chose) amount = models.PositiveIntegerField() ord_date = models.DateField(default=timezone.now) total = models.FloatField(default=0) def __str__(self): return self.pomade FORMS.PY from dataclasses import fields from tabnanny import verbose from django import forms from . import models class order_forms(forms.ModelForm): class Meta: # model that the fields will come from model = models.order_form # chosing the fields to be displayed fields = ['pomade', 'amount', 'total'] VIEWS.PY from django.shortcuts import … -
"Django-filter" Is it possible to use FilterClass(FilterSet) MultipleChoiceFilter within ViewSet methods? Django 1.11, Python 2.7
I have my class ClassFilter(FilterSet) with some of the Filters fx. MultipleChoiceFilter, ModelMultipleChoiceFilter etc. in it: class ClassFilter(FilterSet): something_severity = MultipleChoiceFilter(choices=Something.SEVERITY_CHOICES, method='something_severity_filter', widget=CSVWidget) def something_severity_filter(self, queryset, name, severities): if severities: queryset = queryset.filter(something_state=Something.STATE_SOMETHING) ... return queryset class Meta: model = Something fields = [] It works perfect when it comes to filtering endpoints. It is assigned to the class like: class ClassViewSet(mixins....., DefaultApiViewSet): filter_class = ClassFilter by having filter_class = ClassFilter. Everything works just fine but now I am in in doubts if I may use the ClassFilter MultipleChoiceFilter within ClassViewSet methods. This means by executing POST method in ClassViewSet, I want to get the MultipleChoiceFilter from FilterClass to filter on my method by getting it as SomethingFilter.get_filters() method @action(detail=False, methods=['post']) def something_update(self, req): ... all_filters = SomethingFilter.get_filters() for serializer_filter in serializer_filters: for filter in all_filters: if(serializer_filter == filter): f = all_filters[filter] Now the f is a filter which I require so that is MultipleChoiceFilter. But when I try to filter with that filter it throws an error. f.filter(queryset, [('LOW')]) #filter the queryset with the filter based on LOW choice Throws: assertionError: Filter 'something_severity' must have a parent FilterSet to find '.something_severity_filter()' In documentation for django-filter it is exactly line: … -
Django custom foreign key representation
If i have two models class Parent(models.Model): attribute_1 = .... attribute_2 = .... class Child(models.Model): parent = models.ForeignKey(Parent) Django by default will do lazy fetching to parent as it will hit the database when i try to access attribute_1 or attribute_2, so how can I make it fetch them by default for this specific use case -
Django templates not picking static files
Following is the my static folder structure: ProjectABC - App1 - App2 - App3 - ProjectABC - resources - static - imgs - css - templates This is how the project structure looks like. This is how the static configuration in settings.py looks like: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) This is how the base.html looks like: <!doctype html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=1, initial- scale=1, user-scalable=0"> <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"> <link rel="stylesheet" href="https://fonts.googleapis.com/css? family=Open+Sans:400,600,800"> <title>{{SITE_NAME}}</title> <link rel='shortcut icon' href= "{% static 'img/favicon.png' %}"/> <link href="{{STATIC_URL}}css/application.css" media="screen" rel="stylesheet" type="text/css" /> <link href="{{STATIC_URL}}css/style.css" media="screen" rel="stylesheet" type="text/css" /> <script src="{{STATIC_URL}}js/application.js" type="text/javascript"></script> {% block extracss %} {% endblock %} </head> <body> <div class="container"> <h1>Hello</h1> </div> </body> </html> All the static files are being loaded as seen in terminal, but in browser its just loading bare html without any css or img: Please lemme know if i am missing something. Thnk You! -
Problem in deploying Django website on Cyber Panel
I have deployed the Django website on openlite server and cyberpanel. According to the documentation of the cyberpanel, there is no requirement to run the server manually. The default page of cyberpanel will be removed automatically once the Django website will be there. But in my case, that default page is still there. As this is not working, I tried it by executing the following command: python manage.py runserver example.com:8000 After this, the website is working only on port 8000 i.e. "https://example.com:8000", but not on "https://example.com". I have tried configuring all the settings in settings.py like setting the allowed host to ["*"] and also configuring the configurations of vhost in cyberpanel but still it is not working. Can anyone help please ? -
Not able to get current logged in user in django model
I am trying to get current logged in user through my model so that I can only see the current user in my order page dropdown: I have gone through a lot of documents which state that it is not that easy or feasible to get current logged in user in model. I have tried other method like getting AUTH_USER_MODEL but it is returning admin level users as well so not solving the problem. I am also sending the current logged in user from my views file but dont know how to access it inside form class, able to access it in init but dont know how it can be accessed in class. models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model from django.http import HttpResponse,HttpRequest class Customer(models.Model): name = models.CharField(max_length=200,null=True) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) #customer = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) date_ordered = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=20,default= 'PENDING') def __str__(self): return str(self.customer.id) forms.py : class createorderform(ModelForm): def __init__(self,*args,**kwargs): self._instance=kwargs.pop('instance',None) super().__init__(*args,**kwargs) #def __init__(self,instance): # self.user = instance # super().__init__(instance) class Meta: model=Order fields="__all__" exclude=['status'] Views.py def … -
Set the value of a field in a model as the value of a field in another model in django
I have a two model field one which is the user model and one which is the landlord model. I want the first_name and last_name of the user model to be saved also in the landlord model. This is my model view pass class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") objects = UserManager() class Landlord(models.Model): user = models.OneToOneField(User, null= True, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(unique = True , null=True) bio = models.TextField(null=True) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") USERNAME_FIELD = 'email' REQUIRED_FIELDS= [] objects = User() def __str__(self): return str(self.user)``` -
How to run Django new project in the same VS code folder which already has a project that is running on every runserver Port?
I created two projects baseproject and web_project using django in vs code folder: smcode5 with virtual environment. I used web_project first to create an app and run on server port 8000. Now I want to use baseproject for an app, but only web_project runs. Any suggestions? -
populating foreign key in django
I'm creating a page that lets only admin add some assets. Each asset has a type. I have used a dropdown to select the asset_type. The selected value of asset_type gets passed into views.py but I can't get it written into the newly created asset object. Here is my models.py class assetType(models.Model): title = models.CharField(max_length=150) @property def get_type(self): return asset.objects.filter(asset_type=self.id) def __str__(self): return f"{self.title}" class Meta: verbose_name_plural = 'Asset Types' class asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False) asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True) asset_name = models.CharField(max_length=30, null=True) #unique=True location = models.CharField(max_length=30, null=True) brand = models.CharField(max_length=30, null=True) purchase_year = models.PositiveIntegerField(blank=True, null=True) isActive = models.BooleanField(default=True, null=True) currentOwner = models.ForeignKey(User, default='', null=True, on_delete=models.CASCADE) Here is createAssetView from views.py @user_passes_test(lambda u: u.is_superuser) def createAssetView(request): assetTypeList = assetType.objects.all() # use assetType.title assettype = request.POST.get('asset-type') assetname = request.POST.get('asset-name') locationn = request.POST.get('location') brandd = request.POST.get('brand') purchaseyear = request.POST.get('purchase-year') isActivve = request.POST.get('is-active','') == 'on' cuser=request.user context={ "cuser":request.user, "asset_type_list":assetTypeList, "asset_type":assettype, "asset_name":assetname, "location":locationn, "brand":brandd, "purchase_year":purchaseyear, "isActive":isActivve, 'iterator':range(2014,2050) } if request.method == 'POST': new_asset = asset() new_asset.asset_type_title=request.POST.get('asset-type') new_asset.asset_name=assetname new_asset.location=locationn new_asset.brand=brandd new_asset.purchase_year=purchaseyear new_asset.isActive=True if isActivve else False new_asset.currentOwner=cuser print(assettype) # PRINT assettype new_asset.save() return redirect('createAssets') return render(request, 'assets/createAsset.html', context) The PRINT assettype statement prints selected asset type from the form, so the … -
IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id
I'm trying to implement a comment section in my blog that looks as follows: I don't have a user or post name input because it should take as input the request user and the post ID of the post where it's making the comment. My Comment model: class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) approved_comment = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): max_len = 75 if len(self.body) > max_len: string = self.body[:max_len] + "..." else: string = self.body return string Comment form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) exclude = ['user', 'post', ] View function: def get_post_details(request, post_id): unique_post = Post.objects.get(id=post_id) all_comments = Comment.objects.filter(post=unique_post) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=True) new_comment.post = unique_post new_comment.user = request.user new_comment.save() return get_post_details(request, post_id) else: comment_form = CommentForm() context_dict = { 'post': unique_post, 'comments': all_comments, 'new_comment': new_comment, 'comment_form': comment_form } return render(request, 'blog/post_details.html', context=context_dict) I'm not sure what's missing, but when I try to add a comment I get the below error: IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id I've searched all over stackoverflow and the issue … -
Does django supports frontend pagination?
In brief sight, to use django's Paginator class, we need to paginate from backend. But most of web pages are doing pagination at frontend. Is it possible doing frontend pagination with django's Paginator? Or should I just give it up and use datatables with giving all data to client? -
How to convert web URL data to JSON format
I am mobile application developer. I want to try to get web URL data in JSON format. I have try to build image aggregator application. https://yandex.com/images/search?rpt=imageview&url=https%3A%2F%2Favatars.mds.yandex.net%2Fget-images-cbir%2F1973508%2FEArWpseFrv-9jTLCuEUwTw5291%2Forig&cbir_id=1973508%2FEArWpseFrv-9jTLCuEUwTw5291 I am trying this URL data in JSON format like our REST API response. Is it possible to convert JSON data of this URL. I have also knowledge of Django framework. If it is not possible from front end using android studio then please share me possibility of Django. Thank you -
How to use Modal Foreign key
comment in a situation where my modal looks like this i want to display comments without having to go to different page class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_name = models.CharField(max_length=150) desription = models.CharField(max_length=200) image = models.ImageField(upload_to="images/uploads") like = models.ManyToManyField(User, related_name="liked", blank=True, default=None) like_count = models.BigIntegerField(default=0) date_added = models.DateField(auto_now_add=True, blank=True) # @property # def like_count(self): # return self.like.count() def __str__(self): return self.desription class Meta: db_table = "Posts" ordering = ["date_added"] class Comments(models.Model): post = models.ForeignKey(Posts, on_delete=models.CASCADE) comment = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) date_added = models.DateField(auto_now=True, blank=True) class Meta: db_table = "Comments" ordering = ['date_added'] and in the index use {{post.comment}} ??? -
Anchor tag is changing the background color of other tags when click in Bootstrap 5
Whenever i try to click a anchor tag it always change the background of others tags for a split second even though i didn't click them, where do i get things wrong? Code Here: <nav class="navbar navbar-expand-lg navbar-light bg-warning"> <div class="container-fluid px-5"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="/home/">Home</a> </li> <li class="nav-item me-auto"> <a class="nav-link" href="/rooms/">Rooms</a> </li> </ul> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item me-auto"> <a class="nav-link" href="#">Login</a> </li> <li class="nav-item me-auto"> <a class="nav-link" href="#">Sign-in</a> </li> </ul> </div> </div> -
how to host Django using ngrok
I am trying to publish Django local host using ngrok. But I am getting an error. Can anyone resolve it? error is ERROR: unknown shorthand flag: 'o' in -ost-header-localhost:8000 -
Django Cms - How to add customise menu in djangocms
Hi Im new to cms I was implementing djangocms in my project I have already have my html files im added placholders in that for making that content editable for example: {% block content %} {% placeholder "content" %} {% endblock content %} I have added placeholder for all the places i needed when i come to menu i used placeholder it only changes in the current html page i need to change in all the page which have same header and footer I Have tried {% show_menu 0 100 100 100 %} But it comes default cms menus i need menu with my default style. I have also tried {% include "header.html" %} But the placeholder only coming the plugin i need to add link again and again in every page. Is there any solution for while im adding plugin in header.html it will display on all the pages which have the same header ? -
Django doesn't raise form error on client side if form isn't valid
So I have the following model and modelform which are handled by a view. Now if a user enters a number > 99.99 on the number input the form validation fails due to the specified parameters of field monthly_amount which is fine. However, there is no error displayed on the frontend. class Benefit(models.Model): company = models.ForeignKey('company.Company', on_delete=models.CASCADE) monthly_amount = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) ... def __str__(self): return f'ompany {self.company.name}' class BenefitForm(ModelForm): class Meta: model = Benefit exclude = ('company', ) ... monthly_amount = forms.DecimalField(label='Monthly $ equivalent', widget=forms.NumberInput(attrs={'class': benefit_tailwind_class})) And this is y view handling the form def render_dashboard_benefits(request): # Get a qs of available Benefits the company of the authenticated user offers current_user = request.user qs_benefits = Benefit.objects.filter(company__userprofile=current_user).order_by('-created_at') ctx = { 'page': 'Benefits', 'qs_benefits': qs_benefits, } # Create a blank form instance on GET requests and add it to the context if request.method == 'GET': form = BenefitForm() ctx['form'] = form else: # Create clean form form = BenefitForm() ctx['form'] = form # Create new Benefit instance on POST request new_benefit = BenefitForm(request.POST) if new_benefit.is_valid(): # If the instance is valid create it but dont save it yet new_benefit_instance = new_benefit.save(commit=False) # Get the related company instance and assign it … -
django channels Disconnects after Handshake on deployment
i'm new to using websocket and i'm trying to use channels for a simple chat. everything works perfectly on local development but in production, when i deployed the project it doesn't work and disconnects after handshaking i don't know where the problem is and what to do consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): print("connected", event) await self.accept() Type = self.get_user_type() if Type == "Pationt": id = self.scope["session"]["User_id"] user = UserInfo.objects.first() # user = await self.get_pationt_object(id) else: id = self.scope["session"]["Provider_id"] user = Providers.objects.first() # user = await self.get_doctor_object(id) chat_room = f"user_chatroom_{user.id}" self.chat_room = chat_room await self.channel_layer.group_add(chat_room, self.channel_name) async def websocket_receive(self, event): print("receive", event) received_data = json.loads(event["text"]) msg = received_data.get("message") sent_by_id = received_data.get("sent_by") send_to_id = received_data.get("send_to") thread_id = received_data.get("thread_id") if not msg: print("Error:: empty message") return False Type = self.get_user_type() if Type == "Pationt": sent_by_user = await self.get_pationt_object(sent_by_id) send_to_user = await self.get_doctor_object(send_to_id) else: sent_by_user = await self.get_doctor_object(sent_by_id) send_to_user = await self.get_pationt_object(send_to_id) thread_obj = await self.get_thread(thread_id) if not sent_by_user: print("Error:: sent by user is incorrect") if not send_to_user: print("Error:: send to user is incorrect") if not thread_obj: print("Error:: Thread id is incorrect") mess = await self.create_chat_message(thread_obj, msg) print(mess) other_user_chat_room = f"user_chatroom_{send_to_id}" response = {"message": msg, "sent_by": sent_by_user.id, "thread_id": thread_id} # await self.send({"type": …