Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Variable Number of ChoiceFields
I am making a form in Django where the user reads a paragraph, then is asked a variable number of questions about the paragraph (the content of the paragraphs and the number of questions per paragraph is is stored in Django models). For each question, I need to display a ChoiceField (the same one for each question). What is the best way to display the ChoiceFields and then read the data (i.e namespacing each separate question). I have already looked into FormSet which I do not think will work for my purposes. Any help is appreciated! -
Problem getting "first_name" and "last_name" from User model
I'm creating the Client model like this: from django.db import models from django.contrib.auth.models import User from platforms.models import Platform class Client(models.Model): """Model definition for Client.""" user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(("Compañía"), max_length=50) platforms = models.ManyToManyField(Platform, verbose_name=("Plataformas")) class Meta: """Meta definition for Client.""" verbose_name = 'Cliente' verbose_name_plural = 'Clientes' def __str__(self): """Representación de cliente.""" company = "Sin empresa" if self.company: company = self.company string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) return string But in this part, when I try to get the first_name and user_name I get an error: string = "{} {} ({})".format(self.user.first_name, self.user.last_name, company) This is the error: Instance of 'OneToOneField' has no 'first_name' member Why does this happen? "User" model should have first_name and last_name right? Thank you? -
Django filter my admin list for another field
In my django project i have this model: class as_clienti(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True ) id_ag = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ag_user",null=True, blank=True ) Codice = models.IntegerField() Nome = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.Nome well i would in my django admin when i open the as_clienti link to see the list containing data filtered for logged user but on column id_ag So in my admin.py i do: class as_clientiAdmin(FilterUserAdmin): def get_queryset(self, request): qs = super(as_clientiAdmin, self).get_queryset(request) return qs.filter(id_ag_id=request.user.id) but my django admin page remain blank with 0 rows returned message. Where am i wrong in my code? So many thanks in advance -
Using nested loop in django template
Hi i have a template where i used nested loop like fetching data from two table. html file <div class="content"> <ul class="dashboard-box-list"> {% for form in user.userselecttest_set.all %} <li> <div class="invoice-list-item"> <strong>{{ form.testselected }}</strong> <ul> {% for ut in user.usertest_set.all %} <li>{{ ut.totalprice }}</li> </ul> </div> </li> {% endfor %} {% endfor %} i have two table in models name "UserSelectTest" and "UserTest". So from "UserSelectTest" i retrieve items and "UserTest" thier price i am achieving in displaying the item but in price i get all values for example: Item Price A 120,70 B 120,70 but i want: Item Price A 120 B 70 I am getting confused in nested for loop hope i am making sense i know i am making some silly mistake , Please help. -
Django ASGI Deployment on Heroku
I want clear cut explanation of how should I deploy django 3.x and channels 2.x on heroku. my asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainProj.settings') django.setup() application = get_default_application() -
Overriding admin template works in local not in server
I have project like this structure /-myapp-templates-admin-myapp-myModel-change_list_result.html -change_list.html -base_site.html -base.html -myapp-index.html -base.html When I edit change_list_result.html the edited admin page works on python manager.py runserver. However not on server apache. I guess somehow change_list_result.html is not over-rided on apache server. Does anyone know the reason?? -
Javascript with Crispy Forms
I am using django-crispy-forms but would like to add some super simple JS to change the value of the submit button depending on if a checkbox is checked or not. Here's the generate HTML for the checkbox <div class="form-group"> <div id="div_id_draft" class="custom-control custom-checkbox"> <input type="checkbox" name="draft" class="checkboxinput custom-control-input" id="id_draft"> <label for="id_draft" class="custom-control-label"> Draft </label> </div> </div> <input type="submit" name="submit" value="Post" class="btn btn-primary" id="submit-id-submit"> Here is the JS I am trying to use: function draftbox() { var checkBox = document.getElementById('id_draft') var button = document.getElementById('submit-id-submit') if (checkBox.checked == true){ button.value = 'Save'; } else { button.value = 'Post'; } } Currently, when I click the checkbox, I get no changes in the submit button, but I would like for the "Post" in the submit button to change to "Save" when the checkbox is checked. -
mitmproxy 5.1.1 always crashed
I encountered mitmproxy crash issue with Windows 10 64-bit build 19041.207 Following are my crash logs Mitmproxy: 5.1.1 build pypi_0 from pypi Python: 3.7.6 from conda-forge OpenSSL: 1.1.1g build he774522_0 from conda-forge pyopenssl: 19.1.0 build py_1 from conda-forge cryptography: 2.9.2 build pypi_0 from pypi ================== D:\Dev\Anaconda3\envs\WXC_prj\python.exe D:/Dev/Anaconda3/envs/WXC_prj/src/main.py 2020-04-23 22:40:16.216 | INFO | web_server::32 - Gevent server mode 2020-04-23 22:40:19.039 | INFO | web_server::32 - Gevent server mode `Proxy server listening at http://*:8080 192.168.1.17:58307: clientconnect 192.168.1.17:58309: clientconnect 192.168.1.17:58307: Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\modes\http_proxy.py", line 9, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 285, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http1.py", line 83, in call layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 190, in call if not self._process_flow(flow): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 262, in _process_flow return self.handle_regular_connect(f) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\http.py", line 208, in handle_regular_connect layer() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 278, in call self._establish_tls_with_client_and_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 358, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\protocol\tls.py", line 448, in _establish_tls_with_server **args File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\connections.py", line 292, in establish_tls self.convert_to_tls(cert=client_cert, sni=sni, **kwargs) File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tcp.py", line 386, in convert_to_tls **sslctx_kwargs File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\net\tls.py", line 285, in create_client_context param = SSL._lib.SSL_CTX_get0_param(context._context) AttributeError: module 'lib' has no attribute 'SSL_CTX_get0_param' Traceback (most recent call last): File "D:\Dev\Anaconda3\envs\WXC_prj\lib\site-packages\mitmproxy\proxy\server.py", line 121, in handle root_layer() File … -
Django clean() function for form validation doesn't work
I created this simple form, but the function clean() doesn't work when I intentionally pass invalid data. here is the code: from django import forms SELECT_GENDER = ( ('M', 'Male'), ('F', 'Female'), ) SUBSCRIPTION = ( ('Pro', 'Professional'), ('Premium', 'Premium'), ('trial', '14 Days Trial') ) class FormsProject(forms.Form): fullname = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'placeholder': 'Basir Payenda'})) django = forms.BooleanField( widget=forms.CheckboxInput(), required=False) flask = forms.BooleanField( widget=forms.CheckboxInput(), required=False) gender = forms.ChoiceField( widget=forms.RadioSelect(), choices=SELECT_GENDER) comments = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control mb-2', 'rows': 4, }), help_text='Write here your message!') subscription_plan = forms.ChoiceField( choices=SUBSCRIPTION, widget=forms.Select(attrs={ 'class': 'form-control mb-3' })) def clean(self): super(FormsProject, self).clean() fullname = self.cleaned_data.get('fullname') if len(fullname) < 5: raise forms.ValidationError("ERRRRRRRRROR") return self.cleaned_data The form is rendered in template without any issue. The only thing is that it don't show validation error. Thanks -
UnboundLocalError: local variable 'listing' referenced before assignment
I have create model of comment in models.py with ForeignKey of Listing. while creating comment i get unexpected error i have posted so useful code to find error if request.method == 'POST': message = request.POST['message'] listing_id = request.POST['listing_id'] user_username = request.user.username listing = Listing.objects.all().filter(listing_id=listing.id) if listing: comment = Comment(message=message, user_username=user_username, listing_id=listing) comment.save() return redirect('listing', listing_id)``` and get this error as in picture[![error in browser][1]][1] [1]: https://i.stack.imgur.com/pdLPl.jpg -
django rest framework , Invalid json list
i am trying to add tags to my posts it works fine but whenever i make serializer class (to return json data ) it raise this error { "tags": [ "Invalid json list. A tag list submitted in string form must be valid json." ] } i have django-taggit and django-taggit-serializer package my models.py class Post(models.Model): title= models.CharField(max_length=50) description = models.TextField() location = models.PointField(srid=4326) tags = TaggableManager() my serializers.py class PostCreateSerializer(TaggitSerializer,GeoFeatureModelSerializer): tags = TagListSerializerField() class Meta: model = Post geo_field = 'location' fields = [ 'title','description','tags' ] my views.py class PostCreateApiView(CreateAPIView): queryset = Post.objects.all() serializer_class = PostCreateSerializer message = 'you have not account' permission_classes = [IsAuthenticated] def perform_create(self,serializer): serializer.save(user=self.request.user) i have seen some duplicated questions but wont worked in my case i use geo django with postgis database -
Django: problem with data format (string instead of JSON)
I have a new Django project with specific constraints for displaying data to be edited. I am not sure it is the best way to do the job. I want user: to be able to edit data directly in the html table add new lines in database (datas displayed at screen) Considering 2 forms : index form that display data of my model. When I click on "Modify settings" button user is redirected to edit form with the last 4 records send in the context (parameters) edit form display the last 4 records of my table with editable rows. When I click on "Modify settings" button I send data from html page with ajax query In my ajax view, I want to add data received in my model (4 new lines). But data below are not at JSON format but is a string??: datas [ { "ran_st1": "1", "ran_st2": "1", "bra_00A_act": "1", "bra_00A_lib": "Polyvitamines et oligo-éléments" }, { "ran_st1": "1", "ran_st2": "0", "bra_00A_act": "1", "bra_00A_lib": "Polyvitamines et oligo-éléments" }, { "ran_st1": "0", "ran_st2": "1", "bra_00A_act": "null", "bra_00A_lib": "null" }, { "ran_st1": "0", "ran_st2": "0", "bra_00A_act": "null", "bra_00A_lib": "null" } ] I don't understand how to convert as JSON? views.py @login_required … -
Django doesn't translate this form error : " Your username and password didn't match. Please try again."
I'm triying to translate my Django app to Spanish. I already set my settings.py like this: LANGUAGE_CODE = 'es' TIME_ZONE = 'America/Santiago' USE_I18N = True When I tried to login with invalid credentials I get this error message : "Your username and password didn't match. Please try again." which is in English. I already check django/django/contrib/auth/locale/es/LC_MESSAGES/django.po and I couldn't find this message translation and also couldn't find it i the english catalog (../en/LC_MESSAGES/django.po). Translation for other messages or tags seems to works. Anyone knows how to fix this? is this a bug or I'm doing something wrong? -
ModuleNotFoundError: No module named 'router'
Hi i am getting this error please help me. i am new on this field and i am getting this error. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'first', ] my views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from .serializers import MovieSerializer,RatingSerializers from .models import Movie,Rating # Create your views here. class MovieViewSet(ModelViewSet): queryset=Movie.objects.all() serializer_class=(MovieSerializer,) class RatingViewSet(ModelViewSet): queryset=Rating.objects.all() serializer_class=(RatingSerializers,) my main urls.py is """rest_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('my_apis',include('first.urls')), ] and serializers.py from rest_framework import serializers from .models import Movie,Rating class MovieSerializer(serializers.ModelSerializer): class Meta: model= Movie fields=['title','description'] class RatingSerializers(serializers.ModelSerializer): class meta: model=Rating fields='__all__' models.py is from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator,MaxValueValidator # Create … -
How to redirect logger django_structlog.middlewares.request to another file?
I use structlog with Django but I found my flat_line.log file difficult to read because every time an action is performed in the admin section there are several new entries like these: timestamp='2020-04-23T15:17:49.196600Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/myapp/market/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.325273Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='bf82598e-5a34-4bd0-a698-7556bf4733a4' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/myapp/market/'> timestamp='2020-04-23T15:17:49.465507Z' level='info' event='request_started' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' request=<WSGIRequest: GET '/admin/jsi18n/'> user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' timestamp='2020-04-23T15:17:49.468317Z' level='info' event='request_finished' logger='django_structlog.middlewares.request' request_id='9e7558a8-2d8f-4145-8569-9c6a74b0090b' user_id=1 ip='127.0.0.1' code=200 request=<WSGIRequest: GET '/admin/jsi18n/'> How can I redirect all entries from logger django_structlog.middlewares.request to another file so they don't flood the log files with a ton of undesired informations? This is how my configuration looks like: LOGGING = { "version": 1, "disable_existing_loggers": True, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer(key_order=['timestamp', 'level', 'event', 'logger']), }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "json.log", "formatter": "json_formatter", }, "flat_line_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "flat_line.log", "formatter": "key_value", }, }, "loggers": { '': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", } } … -
How to change header/page title of change list page in Django Admin
I'm working on Django.And I wanted to change the header in the change list page in the Django admin as marked with red color in the pic and my admin.py file looks like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So my question is how to change the header in the change list page as shown in the pic?? Thanks in advance!! -
Django: CSRF verification fails despite token is provided
In my template I have an "edit" button which toggles hidden row and sends an ajax call to the server in order to render an appropriate edit form there. When I try to submit a form I get 403 error due to CSRF token is missing or incorrect despite it is provided in form. Here is my HTML for table contents: {% for cleaning in cleaning_list %} <tr> <td id="td-name{{cleaning.id}}" class="text-md-center">{{ cleaning.name }}</td> <td id="td-difficulty{{cleaning.id}}" class="text-md-center">{{ cleaning.difficulty }}</td> <td id="td-frequency{{cleaning.id}}" class="text-md-center">{{ cleaning.frequency }}</td> <td class="text-md-center"> <button id="edit_btn{{cleaning.id}}" type="button" class="btn btn-warning btn-sm update-cleaning" name="show" value="{{cleaning.id}}">Edit</button> </td> </tr> <tr id='tr-{{cleaning.id}}' style="display: none"> {% include "cleaning_update.html" %} </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">There is no cleaning here yet :( Add some faster </td> </tr> {% endfor %} Here is a "cleaning_update" html: <form id="cleaning-save-update-form{{scleaning.id}}" method="post" action="{% url 'ajax_update_cleaning' %}"> {% csrf_token %} {% for field in form %} <td class="text-md-center"> {{field.label}}: {{ field }} </td> {% endfor %} <td class="text-md-center"><input id="{{scleaning.id}}" class="btn btn-primary save-updates-cleaning" type="submit" value="Change"></td> </form> Here is my js: $(function () { $(document).on('click', '.update-cleaning', function(event) { var target_id = $(this).attr('value') var btn_name = $(this).attr('name') $.ajax({ url: "{% url 'ajax_update_cleaning' %}", type: 'get', data: {'id': target_id}, dataType: 'json', beforeSend: … -
Django Locallibrary Project
I am working on locallibrary projects that mostly everybody did and need to add couple feature, but i could not get it. I need to add return book and take a book method/function for users. Inside myborrow list html I add this borrwed_user.html <a href="{% url 'book-return' bookinst.book.pk %}"> <button>Return it</button> </a> then add url path path('bookreturn/<int:pk>', views.bookreturn, name='book-return'), then add view def bookreturn(request, pk): model = BookInstance.objects.filter(id=pk) model.status = 'a' return render(request, 'catalog/bookinstance_list_borrowed_user.html') but it does not change status of book or drop the book from borrwer. I am missing something but i did not get it. Thank you for your help. -
AttributeError at /payment/ cards
I'm trying to develop an e-commerce website. For some reason, I'm receiving this error, although cards seems to be attributed correctly. My views.py: @login_required def PaymentView(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) except: the_id = None return redirect(reverse("myshop-home")) if request.method == "POST": try: user_stripe = request.user.userstripe.stripe_id customer = stripe.Customer.retrieve(user_stripe) except: customer = None pass if customer is not None: token = request.POST.get('stripeToken') card = customer.cards.create(card=token) charge = stripe.Charge.create( amount= 400, currency="usd", card= card, customer = customer, description = "Charge for %s" %(self.request.user.username) ) What actually is the problem here? -
how do i run a Script inside django?
enter image description here i created a folder containing the script text.py and init.py in app directory. i have already install Django-extentions, still am getting bugs C:\Users\Qasim\Desktop\translator>python manage.py runscript text No (valid) module for script 'text' found Try running with a higher verbosity level like: -v2 or -v3 C:\Users\Qasim\Desktop\translator>python manage.py runscript text -v2 Check for django.contrib.admin.scripts.text Check for django.contrib.auth.scripts.text Check for django.contrib.contenttypes.scripts.text Check for django.contrib.sessions.scripts.text Check for django.contrib.messages.scripts.text Check for django.contrib.staticfiles.scripts.text Check for news.scripts.text Check for rest_framework.scripts.text Check for django_extensions.scripts.text Check for scripts.text No (valid) module for script 'text' found -
Django allauth example [Errno 111] - Connection refused
I have the following error when login by FB in Django app which was uploaded to heroku: ConnectionRefusedError at /accounts/facebook/login/token/ [Errno 111] Connection refused Did I miss somethings? -
Forms has no attribute form
Hi guys im new to django so i tried to import forms from django and use it to make a section to send out articles and this is the code : from django import forms class SendArticleForm(forms.form): title = forms.CharField() body = forms.CharField(widget = forms.Textarea) published_at = forms.DateField() so after i tried to upload this code and run local server it gave me this error and i cant findout how this is happend. class SendArticleForm(forms.form): AttributeError: module 'django.forms' has no attribute 'form' -
I want to redirect to authenticate url after entering login credentials, but it is simply redirecting to same page that im in
a modal will be popped up after pressing login button, after entering details. I need it to be redirect to the following authenticate Django url. but it is showing the same site again <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter"> login </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Login</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="{% url "authenticate" %}"> <div class="modal-body"> <input type="text" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="username" class="form-control" placeholder="username"> <input type="password" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="password" class="form-control" placeholder="password"> </div> <div class="modal-footer"> <input style="margin: auto" type="submit" class="btn btn-danger" name=""> </div> </form> </div> </div> </div> </form></nav> -
Django models queries
I have 3 tables person(id, email,password,type), user_location(id,location,u_id) and reviews(id,review,from_id,to_id). The user_location(u_id) is the foreignkey to person(id). The review(from_id,to_id) is also foreignkey to person(id). So how can i filter out a person with type 'a' and location 'b' and the reviews he got with the reviewers name? -
How to change message design in the real time chat
I have real time chat in the project, where i have two types of users: students and teachers. I want to change design of teacher messages. I tried to change consumers.py and tried to work with template but it didn't work. I think that we can do that, if we'll work with consumers.py. Who knows how to implement that? models.py class CustomUser(AbstractUser,mixins.GuardianUserMixin): email = models.EmailField(_('email_address'), unique=True, name='email') username = models.CharField(_('username'), unique=True, max_length=128) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() consumers.py class Consumer(WebsocketConsumer): def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name self.name = self.scope['user'].username if self.scope['user'].is_anonymous: self.send({'close':True}) else: async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Joined Chat " } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.name+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) template <div class="ui form"> <div style="height:400px;width:100%;overflow-y:scroll" id="div_data"></div> <input type="text" name="message" id="message" placeholder="Message" style="padding:10px;width:100%; border-radius: 0px;"> <script> var roomName='{{ room_name }}'; var personname='{{ request.user.username }}'; var chatSocket=new WebSocket('ws://'+window.location.host+'/ws/chat/'+roomName+'/'); {% if request.user.is_anonymous %} window.location.pathname = '{% url 'users:login' %}' {% endif …