Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to upload snapshot from webcam of client side to image field in Django?
welcome, I don't Know how to upload snapshot from webcam of client side to image field in Django I try to do some thing but I can't to do it . here is my code: models.py class Attendance_Model_IN(models.Model): First_Name= models.CharField(max_length=40) Last_Name= models.CharField(max_length=40) User_Name=models.CharField(max_length=40) Date_Time_IN=models.DateTimeField() Image= models.ImageField(blank=True,upload_to="chapters/%y/%m/%D/") class Attendance_Model_Out(models.Model): First_Name= models.CharField(max_length=40) Last_Name= models.CharField(max_length=40) User_Name=models.CharField(max_length=40) Date_Time_OUT=models.DateTimeField() Image= models.ImageField(blank=True,upload_to="chapters/%y/%m/%D/") html code <html> {% load staticfiles %} <head> <link rel="stylesheet" type="text/css" href="{% static 'app/content/main.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> </head> <body> <div class="booth"> <video id="video" width="400" height="300"></video> <a href="#" id="capture" class="booth-capture-button">Take Photo</a> <canvas id="canvas" width="400" height="300"></canvas> <img src="" alt="photo of you" id="photo"/> </div> <div id="signdiv" style="display:none;"> <form method="POST"> {% csrf_token %} <input type="submit" name="signin" value="Sign In" class="btn btn-default" /> <input type="submit" name="signout" value="Sign Out" /> </form> </div> <script src="{% static 'app/scripts/photo.js' %}"></script> </body> </html> JavaScript code (function() { var video = document.getElementById('video'), canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); photo = document.getElementById('photo'), vendorUrl = window.URL || window.webkitURL; navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; navigator.getMedia({ video: true, audio: false }, function(stream) { video.srcObject = stream; video.play(); }, function(error) { }); document.getElementById('capture').addEventListener('click', function () { context.drawImage(video, 0, 0, 400, 300); photo.setAttribute('src', … -
Django - Logout Redirect to Login Page
i am trying to redirect to login page after logout but some issues are coming. urls.py This is my actual logout routes and it works for me but it does not redirect me to login page path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), Changing logout.html -> login.html It destroys the session and logout the user but the problem is that when i click logout it redirects to login page but login input fields are not showing path('logout/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), And if i am using below path(route). It is not destroying session nor logout path('login/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), -
Django - Grabbing data from a sequence of forms and saving them at once
Using django, I want to grab data from multiple forms before saving it to database, the purpose is to force user to enter all the data required. How can I achieve this? Note: Currently I'm using html tabs for my sequence of forms. Thanks, Majid -
Function takes too much time to process in loop from database(3000 times)
I am calling a function in loop of 3000 time . I am calling that function and getting some dictionary from that function but it takes time . I am fetching data from database which gives me approximately 3000 rows and i am looping that rows and calling function in that loop which fetch data from database and returns dictionary but it takes time . Code: def test(request, uni_id): try: Obj = get_object_or_404(tabl_name, id=uni_id) except: Obj = None dict = {} if Obj:outlet_info dict['data1'] = Obj.id dict['data2'] = Obj.name dict['data3'] = Obj.eg dict['data4'] = Obj.access return dict cursor.execute('''SELECT cd.name, cd.no,ofk.demo_id FROM `main_table` as myo LEFT JOIN `table1` as emt ON emt.some_id = myo.some1_id LEFT JOIN `table2` as ofk ON ofk.id = myo.kit_id LEFT JOIN `table3` as cd ON cd.eg_id = myo.eg_id WHERE emt.type='test'''' result = dictfetchall(cursor) tmp_list, tmp_dict = [], {} for res in result: tmp_dict['name'] = res['name'] tmp_dict['no'] = res['no'] info = test(request,res['demo_id']) tmp_dict['data1'] = info['data1'] tmp_list.append(tmp_dict.copy()) Here I am getting demo_id from query and passing that to another query using function test to fetch data therefore it is taking too much time . Can anyone tell me how to improve the speed or include demo_id to main query … -
nginx index page coming instead of actual website in route 53 with ec2 instance
I have hosted my django website in aws ec2 instance with below ip and pointed to below domain 18.221.162.213 http://govtcarrier.in/ When i am going 18.221.162.213 in my browser it is coming my website but when i am going http://govtcarrier.in/ it is showing nginx welcome page. Please check the screenshots below -
Django models field import
As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(many2many). But how do I attach a particular question's choice selected by a particular user, to that same User? Will I have to change the built-in User model for that? In particular, the problem I faced was I tried creating a new model called 'Answers'. It can have either 'User' as the foreign key' OR 'Question' as the FK. But a particular answer belongs to BOTH - USER & QUESTION, i.e, it is the answer to a particular QUESTION marked by a particular USER. So that answer should have reference to BOTH the QUESTION (to which it is the answer/choice) and the USER (who marked that as her/his answer/choice to that particular QUESTION). I'm unable to figure out how to have the 'Answer' link BOTH to the … -
How to do group by on a different attribute and sum on a different attribute in Django?
models.py: class Student(models.Model): total_fees = models.PositiveIntegerField(blank=False) roll_number = models.PositiveIntegerField(blank=False) class StudentTransaction(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=False) amount = models.PositiveIntegerField(blank=False) timestamp = models.DateTimeField(auto_now_add=True, blank=True) admin.py: class StudentTransactionModelAdmin(admin.ModelAdmin): list_display = ['__str__', 'time', 'amount'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'student': x = StudentTransaction.objects.order_by().annotate(Sum('amount')).filter(amount__sum__lt=student__total_fees) kwargs["queryset"] = [i.student for i in x] return super().formfield_for_foreignkey(db_field, request, **kwargs) While doing annotate I want to get all transaction amounts summed up for every student in the function formfield_for_foreignkey. I want the actual Student objects, so this can't be done using values. To make it simpler, consider that there are 3 Student objects. One of them has made 2 transactions, another one has made 4 transactions, and the third one hasn't made any transactions. The sum of transaction amounts per student doesn't exceed the student's total_fees. The formfield_for_foreignkey should return all Student objects those who haven't paid their fees yet. The condition is: sum(<all transactions of each student>) is less than <total_fees of that student> Note: Some details are intentionally removed to keep the code as short as possible. If something is missing or will produce an error, do report it. -
How to add more fields in admin while creating AbstractUser
I m trying to create an AbstractUser but when using default UserAdmin form I don't get enough fields in admin. How to add more fields to UserAdmin -
How to perform multiple author search in google books api ? eg: q = author1 or author 2 or author3
I set up a system for based on google books api, I need to get books from a list of authors as user recommendations. is there any way to pass multiple author names in google books api ? I have tried with comma separated author list, but not working -
Queryset based on ForeignKeys in Django
While learning Django I am creating an example app in which I have two types of users; students and educators. Educators can create Study sections and students can choose which they would like to participate in (just a BooleanField yes or no). I would like to create a "view participants" page for each study so that the educators can see which students are participating in each section. To do this for each study section I need to query all of the student users who marked "yes" to participate in that study section. I am a bit stuck on how to use Django's QuerySet methods to do this. Here is my models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_educator = models.BooleanField(default=False) class Interest(models.Model): ... class Study(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='studies') name = models.CharField(max_length=255) interest = models.ForeignKey(Interest, on_delete=models.CASCADE, related_name='studies') def __str__(self): return self.name class Detail(models.Model): ... class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) interests = models.ManyToManyField(Interest, related_name='interested_students') def get_details(self, study): details = study.details.all().order_by('start_date') return details def __str__(self): return self.user.username class StudentAnswer(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='study_answers') study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='study_participate', null=True) participate = models.BooleanField('Correct answer', default=False) I would like to write a views.py function like this: @method_decorator([login_required, educator_required], name='dispatch') class StudyResultsView(DetailView): … -
Dockerfile ADD . is adding wrong directory
. |-- business_logic | .... | |-- docker-compose.yml |-- src | `-- backend | |-- Dockerfile | |-- manage.py | |-- requirements.txt | `-- webapp | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- utils.py I want Docker to copy ./src/backend/ to /code/ on the container and when I'm running this compose file: version: '3' services: db: image: postgres web: build: context: ./src/backend/ command: ls -l . volumes: - .:/code/ ports: - "8000:8000" depends_on: - db With the Dockerfile under backend: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ I would expect that the Dockerfile-position in the file tree or the context would be the relative path "." in the Dockerfile, but it seems as if "." points to the directory where docker-compose.yml lies. Because the output is following: web_1 | drwxr-xr-x 14 root root 448 Jan 2 01:51 business_logic web_1 | -rw-r--r-- 1 root root 207 Jan 2 03:10 docker-compose.yml web_1 | drwxr-xr-x 3 root root 96 Jan 2 02:34 src web_1 | -rw-r--r-- 1 root root 657 Jan 2 01:51 utils.py How to copy only everything below the backend-folder into code? -
How to override list_editable save?
class MenuPromoAdmin(admin.ModelAdmin): list_editable = ('position', 'sort_by', 'sort_number') list_display = ('id','product', 'category', 'label', 'sort_by', 'position', 'sort_number') raw_id_fields = ('product', 'category') list_filter = [] ordering = ('position','sort_number') fieldsets = [ "Position and Sorting", { 'classes': ('grp-collapse grp-open',), 'fields': ['position', 'sort_by', 'sort_number'] }), "Data", { 'classes': ('grp-collapse grp-open',), 'fields': ['url', 'label', 'title', 'css', 'product', 'category'] }), ] def save_model(self, request, obj, form, change): # do something super(MenuPromoAdmin, self).save_model(request, obj, form, change) admin.site.register(Menu_Promo, MenuPromoAdmin) I tried that, but it simply doesn't work for "mass save" -
Django - OneToOneField Not Populating in Admin
I’m trying to get the username of the current logged in user using OneToOneField to populate in the admin once the user submits a form. The username should go in the user column of admin.py. I’ve tried various methods and still no luck. I’m new to this and this is my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. Can someone please help? What am I missing? Thanks! Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['user']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from user_profile.models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): … -
Django - Variable is not getting send with POST request
Hey im using for my django project typescript to get a specific section from a text to my view but it somehow doesnt work and I dont really know why. Here is my template in which I want the "currentgap" sent to my view after clicking on the submit button. The getSelectionText() method just sets the id 'gap' to a specific string: <form action="editorgapcreate" id=create method="POST"> <script src="../static/textselector.js"></script> <div id="app" onmouseup="getSelectionText()"> This is a test section. </div> {% csrf_token %} <b>Your current selected gap:</b> <p id="currentgap"></p> <input type="hidden" name="gap" id="currentgap"> <button type="submit" name="create_gap">Create gap</button> </form> and here is my view in which I tried calling it: def editorstart(request): if request.method == 'POST': gap = request.POST['gap'] print(gap) return render(request, 'editor_start.html') else: return render(request, 'editor_start.html') The first time using currentgap in my template it displays it correctly but trying to send it to my view with a POST request doesnt work and the print is empty and I dont really know why. -
Protect pages by raising 404
I am learning Django, and I want to protect certain pages by raising 404 if request is not from certain login user. I already foreginkey topic to user. Here is the code to protect topic page. @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 I wonder are there better ways if I want to protect a lot of pages so I don't have to add the same code in every function? -
Django - Custom User Model Username Not Populating in Admin
I’m trying to get the username of the current logged in user that submits a form from the user_profile to populate in the Django admin. The custom user model is located in the users folder & I would like that username to populate under the username field in the Django admin for user_profile. I’ve tried various methods and still no luck. I’m new to this and it’s my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. What am I missing? Thanks! Code Below: user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import HomeForm from users.models import CustomUser from .models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): model = CustomUser list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'username'] list_filter = ['name', 'zip_code', 'created', 'updated', 'username'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.conf import settings class Listing (models.Model): username = models.CharField(max_length=100, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) … -
How to Access to Already Uploaded Docx Files in Django to search needed words?
I want to edit the needed uploaded file on webpage by searching and replacing the wanted words. How can I get the text of that doc file? I have a filefield in my models and I get the doc files in a list on my webpage,where I am able to delete the needed file or upload a new one. I try to edit the wanted uploaded doc file by creating a function in my views.py. I have tried to use docx module to open the uploaded file, and also have tried io.StringIO() but I did not manage to get the desired output. models.py class DocFile(models.Model): title = models.CharField(max_length=50) agreement = models.FileField(upload_to='') views.py def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) content = instance.agreement.open(mode='rb') variables = [] for line in content: match = re.findall(r"\{(.*?)\}", line.text) variables.append(match) return render(request, 'uploads/file_detail.html', { 'variables': variables }) or def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) # content = instance.agreement.open(mode='rb') content = instance.agreement(upload_id) with open(content, 'rb') as f: instance.agreement = File(f) source = io.StringIO(f) document = Document(source) variables = [] for paragraph in document.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in document.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) source.close() … -
Trying To access a document uploaded in website created by Django . Got errors
I have some have Package not found at '/media/documents/Agreement_sample.docx' when i am trying to change the file uploaded on django Website , though i am able to access and download it . How to access the file for changing it please Help? Github link https://github.com/Arabyan/N_pr/commits/master views.py def edit_files(request, file_id): exact_file = DocFile.objects.get(id=file_id) exact_file = exact_file.document.url print(1) exact_file = Document(exact_file) print(exact_file) # r line variables = [] for paragraph in exact_file.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in exact_file.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) print(variables) return render(request, 'edit_files.html', {'exact_file': exact_file}) edit_files.html {% block content %} <h1>Edit Document</h1> <a href="{{ exact_file }}" class="btn btn-primary btn-sm"> Download Pdf </a> <br/> <br/> <!--<button type="button">Open fields</button>--> {% endblock %} -
Django - Render is not working in my project
I am dealing with form like 1 week but couldn't solve my issue. Probably i overlook something that can be found easy by other eyes, but totally, i don't know what to do. I recognize problem by starting build form. I had to use render for form and it failed in every try. I am able to connect db and showing data in html pages but whenever i use render instead of render_to_response it is failing. And i had to use render for post request as i know. Not only for form, render is not working for all. Even for a simple: def home(request): context = {'foo': 'bar'} return render(request, 'main.html', context) models.py class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status forms.py from django import forms from MyApp.models import ModuleNames class ModuleForm(forms.ModelForm): moduleName = forms.CharField(label='Module Name', max_length=50) ModuleDesc = forms.CharField(max_length = 256) ModuleSort = forms.IntegerField() isActive = forms.BooleanField() ModuleType = forms.IntegerField() class Meta: model = ModuleNames fields =('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType') view.py from django.views.generic import TemplateView from django.shortcuts import render,render_to_response, redirect from … -
Rendering forms with django-semanticui-forms and confused with how choice fields work
I'm using the module django-semanticui-forms to render my forms in a nice format with SemanticUI. I'm confused about what they're doing with choice fields and how to use it in my own code. CHOICES_1 = ( (0, "Zero"), (1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), ) class Choice(models.Model): choices_1_1 = models.IntegerField(choices=CHOICES_1) When I render the form, I'm able to choose between the six options and when I output the choice on a html form like {{user.choices_1_1}}, I get an integer. This makes sense because the model has an IntegerField here. How do I get the value associated with this integer key though? Is there an easy way to print "Zero" instead of 0 without casing on each integer and rendering the string that way? Lmk if the question is confusing -
Calling function from typescript in html not working
Hey im using a django and wanted to use typescript for a specific function I need for my application. Here is my typescript file: testselector.ts: getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); console.log('a'); } else if (document.selection && document.selection.type != "Control") { console.log('b'); text = document.selection.createRange().text; } return text; } And here is my html where I want to call the function: {% extends "base_generic2.html" %} {% block content %} <script src="textselector.js"></script> <div id="app" onmouseup="getSelectionText()"> </div> {% endblock %} For some reason it doesnt find getSelectionText() and I dont really know why? -
django calculate duration between two timefield
I have two TimeField in a Django model that I want to calculate duration for in another databasefield, or function or class, or whatever best practice. I later want to use this information to show information sorted on 'prosjekt' and then 'aktivitet'. For example: Prosjekt1 aktivitet1 = 4 hours aktivitet2 = 2,5 hours aktivitet3 = 1 hour Prosjekt2 aktivitet1 = 5,5 hours aktivitet3 = 0,5 hours Prosjekt3 aktivitet3 = 8,5 hours etc. This is my models: from django.db import models from django.contrib.auth.models import User from prosjektregister.models import Prosjekt class Aktivitet(models.Model): aktivitet = models.CharField(max_length=100) def __str__(self): return self.aktivitet class Tid(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) prosjekt = models.ForeignKey(Prosjekt, on_delete=models.CASCADE) dato = models.DateField() tid_fra = models.TimeField() tid_til = models.TimeField() aktivitet = models.ForeignKey(Aktivitet, on_delete=models.SET_NULL, null=True) def publish(self): self.save() -
All accordions opening at once using Django
This is a really silly question, but I can't find the answer anywhere! I have a for loop & for each item, it creates an accordion as below. The problem is, the accordion always has the same ID, so when I toggle one to open, they all open. How can I systematically assign each a different value, so they open independently? <td colspan="5"> <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> <font color="black">Edit Task</font> </button> </h5> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <form action="/update/" name="form1", id="form1" method="post"> {% csrf_token %} <div class="form-group"> <select name="assignee" class="form-control" id="exampleFormControlSelect1"> <option>Select Assignee</option> <option>kikee</option> <option>kieran</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <select name="priority" class="form-control" id="exampleFormControlSelect1"> <option>Select Priority</option> <option>High</option> <option>Medium</option> <option>Low</option> </select> </div> <div class="form-group"> <input type="text" name="due" class="form-control" id="task" aria-describedby="emailHelp" placeholder="Due Date YYYYMMDD"> </div> <button type="submit" name="editbutton" value={{ todo.taskid }} class="btn btn-warning">Edit Task</button> </form> </div></div></div> </div> </td> -
Django Logged in User Not Populating in Admin
I’m trying to get the current username of the current logged in user that submits this form to populate in the Django admin. I would like the username to populate under the “username” field in the Django admin. I’ve tried various methods and still no luck. This is my first Django application I’m building so I’m not sure what I’m missing. Thanks! Code Below: user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import HomeForm from .models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'username'] list_filter = ['name', 'zip_code', 'created', 'updated', 'username'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.conf import settings class Listing (models.Model): username = models.CharField(max_length=100, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) user_profile/forms.py import os from django import forms from django.forms import ModelForm from django.forms import widgets from django.utils import six from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import filesizeformat from avatar.conf import … -
Websocket disconnect with Channels in Django
I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat. I show you my files. chat/consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) My template file room.html : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <input id="chat-message-submit" type="button" value="Send"/> </body> <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> </html> Root routing configuration : # mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added …