Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement CI/CD pipeline for Django application
I have a Django project and I want to implement CI/CD pipeline for the project but I really don't know how to go about it. Can someone guide me or refer a comprehensive article on that. Am using gitlab -
Why does my django template not recognize the url parameters I set in my views.py file?
I am building an event management app using Django. I have created a dynamic calendar, and I'm trying to add a link to next months calendar in my navigation. In my views.py file I added parameters like so: def home(request, year=datetime.now().year, month=datetime.now().strftime('%B')): <li class="nav-item"> <a class="nav-link" href="{% url 'home' '2021' 'November' %}">November</a> </li> When I add the two arguments, I get a template rendering error: Reverse for 'home' with arguments '('2021', 'November')' not found. 1 pattern(s) tried: ['$'] When I remove the two arguments and only leave 'home' the template error goes away, and I'm not sure why. Any help is appreciated! -
default value dont work in django inline formset
I'm trying to set default value for my django inline formset , but it only shows for the first form , the others are empty ! class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors') class BookingVisitor(models.Model): visitor = models.ForeignKey('vistors.Vistor',on_delete=models.PROTECT,related_name='visitor_booking') booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_bookingvisitors') reason = models.CharField(max_length=50,default='some text') but its doesnt work !? i also tried this in my view initial_data = {'reason':'some text'} VistorsInlineFormset(prefix='formset',initial=initial_data) but it raise this error : KeyError at /en/some/url 0 and this is my forms.py class BookingVisitorForm(forms.ModelForm): visitor = forms.ModelChoiceField( queryset=Vistor.objects.all().order_by('-pk'),empty_label='--------', ) class Meta: model = BookingVisitor fields = ['visitor','reason'] VistorsInlineFormset = inlineformset_factory(Booking,BookingVisitor,form=BookingVisitorForm,extra=1,can_delete=True) -
Django - Unable to get values from input field
I'm currently working on a Django project where I am trying to retrieve values from HTML input fields when a submit button is clicked. One is plane text and two are datetime fields. The view that is called runs when the button is clicked (I've hard coded values within my view function to test) but when I print the values of the input fields I'm trying to retrieve I get None for all three. The form I'm using in my html template looks like so: <form action="{% url 'get-billing'%}" method='GET'> {% csrf_token %} <button type="submit" value="click" class="btn btn-warning btn-sm fs-6">Submit</button> </form> views.py: def get_billing(request): url='placeholder for api url' secret='placeholder for api key' client = request.GET.get('client-name') start = request.GET.get('start-date') end = request.GET.get('end-date') print(client) print(start) print(end) response = requests.get(url, headers={ 'key': secret, 'start': '2021/10/01', 'end': '2021/10/02', }).json() # print(request) context = {'data':response} return render(request, 'billing/billing.html', context) urls.py: path('get_billing',views.get_billing, name='get-billing'), And this is what the 3 print statements return even though there are values in all 3. None None None Anyone know what I am doing wrong here? -
Django. Using a variable as a part of a variable name
I have a block of code that needs to be repeated over a hundred times with different input variables. The first 3 letters can change and the numbers can change. For example: BTCH1_13 maybe become BTCH1_18 or MESH1_13 I would need to use (var x)H1_(var y) and somehow be able to input them. I'm pretty sure there's a way to do this. Is there a term for this and how do I do it? </td> <td class="13"> {% if BTCH1_13.isBreak == '!' %}!{% endif %} {% if BTCH1_14.isPUpFractal == 'pUP' %}pUP{% endif %} {% if BTCH1_14.isPDnFractal == 'pDN' %}pDN{% endif %} {% if BTCH1_15.isUpFractal == 'UP' %}UP{% endif %} {% if BTCH1_15.isDnFractal == 'DN' %}DN{% endif %} {% if BTCH1_14.isPSG == 'PSG' %}PSG{% endif %} {% if BTCH1_15.isSG == 'SG' %}SG{% endif %} <br> {{BTCH1_13.maxRetracement|default_if_none:""}}|{{BTCH1_13.Current_RP|default_if_none:""}}|{{BTCH1_13.maxProjection|default_if_none:""}} </td> -
Django - how to use UpdateView modelform with custom field?
I would like to use a custom form field with an UpdateView. My code so far is: models.py class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) paper = models.BooleanField(default=False) pronouns = models.CharField(max_length=50, blank=True) def __str__(self): return self.username forms.py class CustomUserProfileForm(forms.ModelForm): pronouns = forms.CharField(label='Pronouns', required=True) class Meta: model = get_user_model() fields = ('first_name', 'last_name') def __init__(self, *args, **kwargs): _pronoun_list = ('he/him/his', 'she/her/hers', 'they/them/theirs') super(CustomUserProfileForm, self).__init__(*args, **kwargs) self.fields['pronouns'].widget = ListTextWidget( data_list=_pronoun_list, name='pronoun-list') This form references ListTextWidget although I don't think it directly relates to my issue: class ListTextWidget(forms.TextInput): def __init__(self, data_list, name, *args, **kwargs): super(ListTextWidget, self).__init__(*args, **kwargs) self._name = name self._list = data_list self.attrs.update({'list': 'list__%s' % self._name}) def render(self, name, value, attrs=None, renderer=None): text_html = super(ListTextWidget, self).render( name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + data_list) Views.py class CustomUserProfileview(UpdateView): model = CustomUser form_class = CustomUserProfileForm template_name = 'account/customuser_change_form.html' success_url = reverse_lazy('home') def form_valid(self, form): user = self.request.user pronouns = form.cleaned_data['pronouns'] user.pronouns = pronouns user.save() return super().form_valid(form) The form is displayed as I would expect, where I can change the first name, last name and choose pronouns from a list. If I print(user) and print(pronouns) I get … -
What's the difference between _set() and filter() using a Foreign Key in django?
Let's say I have a User and Order model. Order has a fk User. What's the difference between doing def getorders(request): user = request.user orders = user.order_set.all() and def getorders(request): user = request.user orders = Order.objects.filter(user=user) Both will return the same result, no ? So what's the benefits to use _set instead of filter ? -
How to get all related objects of all objects in a Queryset?
Unfortunately I cant find a straight-forward answer to this even though there are several related quesitions. Say we have: class Category(models.Model): name = models.CharField(max_length=50) class SubCategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category,on_delete=CASCADE, related_name='subcategories') I know I can get all the subcategories of a specific category by some_category.subcategories.all() But how do I get a queryset of all subcategories of all categories in a queryset? -
Django forms field
class Registration(forms.Form): Name=CharField() So, CharField input is showing in the browser but when I submit this field without filling any data it's doesn't show django error. And if I apply min_length and max_length both are not working What should I do -
Is there a way to force django to check for static files in the current app before checking other apps
I'm working with multiple apps and it helps to have the static files named the same way. Is there a way to force Django to search for static files based on the app I'm working in? For example. For a page in app3, It should check app3/static first for "style.css" before checking app1 even though app1 also has "style.css" -
How to use Multiple Inheritance in Django Rest Framework
I have two serializers which are identical except for their parent class. One inherits from DRF's serailizers.Serializer. The other inherets from a class called HalModelSerializer from a package called drf_hal_json. class BriefcaseSerializer(HalModelSerializer): contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) class SimpleBriefcaseSerializer(serializers.Serializer): contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) In my views.py I've overridden the get_serializer_class method to select one of these two serializers depending on the Accept header in the request. typing both classes out in full is bad for obvious reasons. Eg if I change one and forget to change the other. My attempt to fix this was to use multiple inheritance. This is the first time I've ever tried to use multiple inheritance. Attempt: class BriefcaseMixin: contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) class BriefcaseSerializer(HalModelSerializer, BriefcaseMixin): pass class SimpleBriefcaseSerializer(serializers.Serializer, BriefcaseMixin): pass This didn't work. GET Requests now error with django.core.exceptions.ImproperlyConfigured: Field name `username` is not valid for model `Briefcase`. Note I did have a custom create method as well for POSTs that used username. I've … -
Django Create post and send mail
after saving my variables in views.py that I have forwarded, can I send them as mail while saving the same fields? My mail sending codes are below but I didn't know how to do it. def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() except ValidationError as e: pass send_mail( 'test', 'testmessage', 'xx@xx.com', ['xx@xx.com'], fail_silently=False ) gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') -
How to pass value to Django Custom template tag's function
Got an error in my pet project: TemplateSyntaxError at /car/2/ 'get_car_info' did not receive value(s) for the argument(s): 'car_id' As I can see, function in custom template tags can not receive a value, but Django log shows that car_id variable is exists: Local vars Variable Value car_id 2 context {'spare_parts': <QuerySet [<Mileage: Рулевой наконечник Sasic 7674007>]>, 'title': 'Список запчастей для'} request <WSGIRequest: GET '/car/2/'> models.py class Car(models.Model): brand = models.CharField(max_length=40, db_index=True, verbose_name="Марка") model_name = models.CharField(max_length=60, db_index=True, verbose_name="Модель") model_variant = models.CharField(max_length=100, db_index=True, verbose_name="Модификация") age = models.SmallIntegerField(verbose_name="Год выпуска") views.py (commented code moved to custom template tags) def get_car_spare_parts(request, car_id): spare_parts = Mileage.objects.filter(car_id=car_id) # car = Car.objects.get(id=car_id) context = { 'spare_parts': spare_parts, 'title': 'Список запчастей для', # 'model_name': car.model_name, # 'brand': car.brand, # 'car_age': car.age, } return render(request, 'mileage/car.html', context) urls.py urlpatterns = [ path('car/<int:car_id>/', get_car_spare_parts, name='car_spare_parts'),] mileage_tags.py @register.simple_tag def get_car_info(car_id): car = get_object_or_404(Car, car_id=car_id) return car car.html {% extends 'base.html' %} {% load mileage_tags %} {% block head %} <title>{{ title }}</title> {% endblock %} {% block body %} <h1>{{ title }} {{ brand }} {{ model_name }} {{ car_age }} г./в.</h1> {% get_car_info %} <ol class="list-group list-group-numbered"> {% for item in spare_parts %} <li class="list-group-item"><a href="{% url 'spare_parts_mileages' item.car_id item.spare_part_id %}">{{ … -
convert timestamp to date in custom commands
i am creating custom commands in django. i have a problem with conversion timestamp to date by methods like fromtimestamp. i have such error: line 13, in handle timest_conv = datetime.fromtimestamp(timest) OSError: [Errno 22] Invalid argument this is my class with handle class Command(BaseCommand): def handle(self, *args , **options): r = requests.get('https://api.metals.live/v1/spot/silver').json() price = r[0]['price'] timest = r[0]['timestamp'] timest_conv = datetime.fromtimestamp(timest) print(price,timest, timest_conv ) return -
Django won't show models pictures in templates
images used to show but i think I have changed something that made it won't show this is my files if you could find the issue that made pictures don't show i would be glad this is my model.py : from django.db import models import uuid from django.contrib.auth.models import User from django.db.models.expressions import F from django import forms class Author(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) description = models.TextField(max_length=1000) id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) image = models.ImageField(null=True, blank=True, default='default_EtYECuR.jpg', upload_to='profilePics') email = models.EmailField(max_length=200, null=True, blank=False) password = models.CharField(max_length=50, null=True, blank=False) brief = models.CharField(max_length=100, null=True, blank=True) skills = models.ManyToManyField('Skill', blank=False) def __str__(self): return self.name class Skill(models.Model): name = models.CharField(max_length=100, blank=False, null=True) description = models.TextField(max_length=500) uuid = models.UUIDField(unique=True, primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.name and this is what I wrote for static files in settings.py: DEBUG = TRUE . . . . STATIC_URL = '/static/' MEDIA_URL = '/img/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') this is my function in views.py def profiles(request): profiles = [profile for profile in Author.objects.all()] return render(request, 'users/index.html', {'profiles': profiles}) and this is my template {% for profile in profiles %} <div class="column card"> <div class="dev"> <a … -
Module 'project_name' has no attribute 'celery'
I'm trying to set up a background task using celery and rabbitmq on django but I'm getting an error saying that my project has no attribute celery. I'm using PyCharm and installed celery through that. I'm new to celery but I've read a lot of articles similar to this issue (AttributeError: module 'module' has no attribute 'celery' this one seems the closest but not sure it's quite the same) Project structure: project_name ├──project_name | ├── settings.py ├──app_name1 | └──celery.py ├──app_name2 | └──tasks.py I run the following command: celery -A project_name worker -l info --pool=solo But I get the following error: Error: Invalid value for "-A" / "--app": Unable to load celery application. Module 'project_name' has no attribute 'celery' celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') app = Celery('project_name') app.config_from_object('django.config:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py file: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y -
Procfile for Heroku
So Heroku's explanation is useless if you don't already know what you're doing and I have no clue what should go in my Procfile. I tried: web: python appname.py because I found an example like that for python apps (I used Django so used the python build). Further searching didn't make things any clearer except for that I might need to use gunicorn instead of python. I found various posts suggesting various formats such as: web gunicorn web:gunicorn web: gunicorn I have no clue what should come after gunicorn, some posts have the programming language, some have an IP address, some have various other things. Some suggest running: heroku ps:scale web=1 but that results in an error: Scaling dynos... ! ! Couldn't find that process type (web). I just haven't got a clue and don't know where to turn; Heroku explains nothing. -
Django | admin account page group display
I created a custom admin page with a custom user account, but in the admin page when editing a user the group section is not showing properly admin.py: class AccountAdmin(UserAdmin): list_display = ('id' , 'email','username' , 'first_name' , 'last_name' , 'date_joined', 'is_admin' , 'is_staff') search_fields = ('email','username' , 'first_name' , 'last_name' ) readonly_fields = ('id','date_joined' , 'last_login') filter_horizontal = () list_filter = () fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name','last_name')}), ('Permissions', {'fields': ('is_active','is_staff', 'groups')}), ('Dates', {'fields': ('last_login', 'date_joined')}), ) admin.site.register(Account ,AccountAdmin) models.py class Account(AbstractBaseUser , PermissionsMixin): id = models.UUIDField(verbose_name="ID" , primary_key=True, default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(verbose_name="email",max_length=64,unique=True) username = models.CharField(max_length=32, unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) date_joined = models.DateTimeField(verbose_name="date joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login",auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name' , 'last_name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin view: -
Getting Search Query and Pagination at the same time in Django in request.GET
class HomeView(ListView)://views.py model=Movement template_name='home.html' paginate_by = 10 def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) mov_objs = Movement.objects.all() paginator = MyPaginator(mov_objs, self.paginate_by) page = self.request.GET.get('page', paginator.num_pages) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context['page_obj'] = page_obj ids=list(page_obj.object_list.values_list('id', flat=True)) sale_id = str(Sale.objects.filter(stored_ids=sorted(ids))).split('(')[1].split(')')[0] if self.request.method == 'GET': inv_no = self.request.GET.get('inv_no','0') context['inv_no']=inv_no else: inv_no = '0' sale_data=sale_id+','+inv_no context['sale_data']=sale_data return context def TallyExport(request,sale_data): t = loader.get_template('template.xml') [sale_id , inv_no] = [int(item) for item in sale_data.split(',')] mov_obj_ids = Sale.objects.filter(id=sale_id).values_list('stored_ids')[0][0] mov_obj = Movement.objects.filter(id__in=mov_obj_ids) response = HttpResponse(t.render({'mov_obj':mov_obj,'inv_no':inv_no}), content_type="application/xml") response['Content-Disposition'] = 'attachment; filename=file.xml' return response <center><h1>Title Page</h1></center> <h4> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page=1">&laquo; first</a> <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Sale {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.next_page_number }}">next</a> <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </h4> <form method="GET"> <input type="number" id="inv_no" name="inv_no" placeholder = "Invoice No"> <input type="submit" value="Save"> </form> {% if 'inv_no' in request.GET %} <a href="{% url 'tally' sale_data %}">Export To Tally</a> {% endif %} <ul> {% for post in … -
Best practice for designing models in Django project?
I am currently creating a hobby project using Django and am completely new to web dev. It's just a basic language tutoring application. Where a user can visit the website, click on which language they want to learn, and then select a tutor to learn from based on the language chosen. Currently, I was thinking of designing the database with the following tables - Languages, Tutors, Students - not sure if I should add any more? My main question is - if I create a languages app, can I just define all 3 models within that app and then use those same models in every other app I create? For example, I have a language app with the models - language, tutor and student If i create a booking system app, can I use those same models within that app? -
How to safely make Typescript work with a custom backend API
I am making use of API endpoint routes in my application. In these endpoints http requests about the data are processed by the backend with the help of a PRISMA ORM. However, i have to use something else for the frontend and started to write typescript types that resemble my backend types. This is very counterintuitive coming from programming languages like haskell or other typed languages. It seems the endpoint sits in the middle and is a source of all kinds of incompatibilities that might arise in the future. Because now I have 3 points of failure, the endpoint, the API and frontend typescript types (that are not even compiled and available at runtime.) Is there a more type-safe way to fix the endpoint-in-the-middle-problem? I've looked at several obscure fullstack projects such as Urweb and the less obscure Django but they lack an expressive templating language such as in Svelte or Vue. Are there other ways to make automatic type safe api endpoint code? -
Django get() got an unexpected keyword argument 'slug'
I need to use Korean in the url, but it doesn't work. views.py class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] I've tried slug:slug and url with re_path, but these methods says 'page not found' so I tried str:slug but it says get() got an unexpected keyword argument 'slug' This is slug data in my model. slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) 'allow_unicode' allows using Korean in the url. I can't find which code is wrong. Is there any problem with views.py or urls.py? -
Python Django Operational error, no such table
I'm trying to use a sqlite database from a different project in my django project. I've added the .db file to my project structure and added the following code (new database contains info about companies): In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'companies':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'companies/db/company_financials002.db' } } In companies/admin.py: from .models import Companies, RowData, StatementRows, Statements admin.site.register(Companies) admin.site.register(RowData) admin.site.register(StatementRows) admin.site.register(Statements) Next, I ran the manage.py makemigrations and migrate If I log into the admin panel, all tables are shown: admin panel However, if I try to access a table it hits me with an operational error/no such table: error message The autogenerated models says in the top comments: Remove managed = False lines if you wish to allow Django to create, modify, and delete the table so I did. I'm really at a loss as to how to acces my data now and I can't seem to find the solution anywhere on the internet. -
I get ModuleNotFoundError although i have the module in my django project
I am using Django 3.2.8 and also Django Rest Framework. Also using python 3.6.8. My directory structure is : iomobileproj >>iomobileapp ... apps.py ... >>iomobileproj ... settings.py ... In apps.py : from django.apps import AppConfig class IomobileappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'iomobileapp' In settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'iomobileapp.apps.iomobileappConfig' ] When i try to run the project i get below error : ModuleNotFoundError: No module named 'iomobileapp.apps.iomobileappConfig'; 'iomobileapp.apps' is not a package. But module is there. I am running similar project with same config in another project without error. -
self.scope['user'] always shows me the same user, Django Channels
I am a beginner in Django Channels and I try to make a chat app. I think everything works fine, but the problem is that the message is not send to both of users connected to the room. I think the problem is inside consumer.py in user = self.scope['user'] becuase if I print the user it shows me every time only the first user that wrote something. So if I have two users: user1 and user2 and if user2 write something as first, it user = self.scope['user'] will always give me the second user. I am using Redis by WSL2. an example console log if one of the user send something: receive {'type': 'websocket.receive', 'text': '{"message":"abc"}'} message {'type': 'chat_message', 'text': '{"message": "abc", "username": "test"}'} message {'type': 'chat_message', 'text': '{"message": "abc", "username": "test"}'} templates/thread.html {% extends "base.html" %} {% block content %} <h3>Thread for {% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</h3> <ul id='chat-items'> {% for chat in object.chatmessage_set.all %} <li>{{ chat.message }} via {{ chat.user }}</li> {% endfor %} </ul> <form id='form' method='POST'> {% csrf_token %} <input type='hidden' id='myUsername' value='{{ user.username }}'/> {{form.as_p }} <input type='submit' class='btn btn-primary'/> </form> {% endblock %} {% block …