Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement Like feature similar to Instagram with Django using ajax?
hi I have been making a social media site with a like feature similar to Instagram where user does not need to view the individual post to like it but can like that post directly from the main page , how can i do that ? my main template: {% load static %} {% if user.is_authenticated %} {% if obj %} <h1 style="background:skyblue;text-align:center;">Posts</h1> {% for obj in obj %} <div style="background:lightgrey;border-radius:5px;margin-bottom:20px;padding:1rem;"> <form method="get"> <input hidden value="{{obj.id}}" name="liked_post_id"> </form> <p>{{obj.user}}</p> <p>{{obj.name}}</p> <img height="250px" width="100%" src="{{ obj.image.url }}" alt="Image "> <p>{{obj.desription}}</p> <!-- {% include "like_page.html" %}--> <button id="btn_1" name="btn_1" type="submit" value="{{ obj.id }}">like </button> <span id="like_count">{{obj.like_count}}</span> <h4>add a comment</h4> {% include "comments.html" %} </div> {% endfor %} {% else %} <h1 style="background:skyblue;text-align:center;">No Posts available</h1> {% endif %} {% endif %} my urls : from django.urls import path from .views import index, show, LikeView, addComment\ # , likeviewNumber urlpatterns = [ path("", index, name="home"), path("show", show, name="show"), path("like/", LikeView, name="post_like"), path("comment/",addComment, name="comment" ), # path('like_num',likeviewNumber ) ] the ajax I used: <script src="{% static 'jquery-3.6.0.js' %}" type="text/javascript"></script> <script> $(document).on('click','#btn_1',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "post_like" %}', data:{ postid:$('post_id').val(), // idher mene abhi name=Post_id use kia ha <like_page.html> k ander /warna yahan par buton … -
how to sum model in Django rest Api
I am new to Django rest Api devlopment I want to sum rent_amount, bijli_bill, other_amount and get value as Total amount, i dont know to add them pls help I want value like this { "id": 1, "rent_date": "23-08-2022", "rentmonth": "June", "rent_amount": 500.0, "bijli_bill": 200.0, "other_amount": 100.0, "other_commnet": "test", "total_amount": 800.0, } This the model file from sqlite3 import Date from django.db import models from django import forms from django.contrib.auth.models import User class rent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # id=models.IntegerField(primary_key=True) rent_date = models.DateField(auto_now_add=True) rentmonth = models.CharField(max_length=30) rent_amount = models.FloatField() bijli_bill = models.FloatField() other_amount = models.FloatField(blank=True) other_commnet = models.CharField(blank=True, max_length=200) This is my serializer from rest_framework import serializers from .models import rent from django.contrib.auth.models import User from django.db.models import Sum class rentSerializer(serializers.ModelSerializer): rent_date = serializers.DateField(format="%d-%m-%Y", read_only=True) rentmonth = serializers.CharField() rent_amount = serializers.FloatField() bijli_bill = serializers.FloatField() other_amount = serializers.FloatField() other_commnet = serializers.CharField(max_length=200) class Meta: model = rent fields = ('__all__') This is view file class rentViews(APIView): def get(self, request, id=None): if id: item = rent.objects.get(id=id) serializer = rentSerializer(item) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) items = rent.objects.all() serializer = rentSerializer(items, many=True) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) -
Django can't add new item to another database on admin site
I'm using two databases to create an app and everything looks fine, I can change, delete the existing item but can't add new item to other database table on the admin site. The data should be stored in dbcost.tbItemDetail instead of userauth.tbItemDetail. Does anyone know how to correct this? Thanks Here is the code: code on admin.py: from unicodedata import name from django.contrib import admin from .models import * #Create MultiDBModelAdmin to expose multiple databases for admin site class MultiDBModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): # Tell Django to save objects to the other database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the other database obj.delete(using=self.using) def get_queryset(self, request): # Tell Django to look for objects on the other database. return super().get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the other database. return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the other database. return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs) # Register your other database here: class tb_companyinfo(MultiDBModelAdmin): using = 'dbcost' #select database name list_display = ('name','emailaddress',) #add different fields into admin … -
SQLAlchemy ORM group_by and join
I have a query query = session.query(portfolioAnalysis_portfoliomain,portfolioAnalysis_stocklist, stock_companymaster, stock_industrymaster,func.count(stock_industrymaster.c.INDUSTRY).label('count_ind'))\ .filter(portfolioAnalysis_portfoliomain.c.user_id==user_dt.id)\ .join(portfolioAnalysis_stocklist, portfolioAnalysis_stocklist.c.portfolio_id==portfolioAnalysis_portfoliomain.c.id)\ .join(stock_companymaster, stock_companymaster.c.FINCODE==portfolioAnalysis_stocklist.c.stock_id)\ .join(stock_industrymaster, stock_industrymaster.c.IND_CODE==stock_companymaster.c.IND_CODE)\ .group_by(portfolioAnalysis_stocklist.c.id)\ .all() I wnat the data as ('Refinary', 2) ('Banking', 3) but I am getting the data as ('Refinary', 1) ('Refinary', 1) ('Banking', 1) ('Banking', 1) ('Banking', 1) I tried the below query but it throws error. query = session.query(portfolioAnalysis_portfoliomain,portfolioAnalysis_stocklist, stock_companymaster, stock_industrymaster,func.count(portfolioAnalysis_stocklist.c.id).label('count_ind'))\ .filter(portfolioAnalysis_portfoliomain.c.user_id==user_dt.id)\ .join(portfolioAnalysis_stocklist, portfolioAnalysis_stocklist.c.portfolio_id==portfolioAnalysis_portfoliomain.c.id)\ .join(stock_companymaster, stock_companymaster.c.FINCODE==portfolioAnalysis_stocklist.c.stock_id)\ .join(stock_industrymaster, stock_industrymaster.c.IND_CODE==stock_companymaster.c.IND_CODE)\ .group_by(stock_industrymaster.c.INDUSTRY)\ .all() -
Retrieving ID atribute from URL
In my django project i have a url: https://example.com/nice_page#123 This url will lead user to particular post on my page, this is an example how it works on stackoverflow: What is the "N+1 selects problem" in ORM (Object-Relational Mapping)? (it is a link to particular answer, and your browser will move you right to this answer.) My goal is to get this #123 id from url. I can't do it with django's META data by request.META it doesn't show this #123 id, it only returns me https://example.com/nice_page How can i get this #123 id? I would prefer making it with django, but javascript is also acceptable. -
Loading css from static files in django not working
this is what the file explorer looks like this is the html file userController/templates/users/dashboard.html {% extends 'base.html' %} {% load static %} <html> <head> /* loadint the css */ <link rel="stylesheet" href="{% static 'css/dashboard.css' %}"> demowebsite/settings.py # STATIC_DIR=os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'userController/static/') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') the css file is not getting loaded, i cant tell where my problem is -
Django - how to add items to ManyToMany field from Queryset
What I am trying to achieve is to get the title that the user inserted in the form and save it in all components that are currently in the cart. This piece of code contains the items that are currently in the cart: get_components = user.cart_component.all() It gives me a queryset like this: <QuerySet [<ProductComponents: component 1>, <ProductComponents: component 2>, <ProductComponents: component 3>]> I am also able to get the title from the form by using get('title'). What I am struggling with is how can I add all components from get_component to the newly created template. I am getting the following error: Field 'id' expected a number but got 'test template'. my post method in TemplateView: def post(self, *args, **kwargs): ce_template_form = SaveAsTemplateForm(data=self.request.POST) if ce_template_form.is_valid(): template_title = ce_template_form.cleaned_data.get('title') user = self.request.user get_components = user.cart_component.all() for component in get_components: component.template.add(template_title) # how can I pass id here? ce_template_form.save() return redirect('cart') models.py class UserTemplate(models.Model): title = models.CharField(max_length=200) class CostCalculator(models.Model): [...] template = models.ManyToManyField(UserTemplate, related_name='user_template', blank=True, default='-') -
crontab django Erorr
hello everyone im trying to start simple crontab-django job scheduled as i will show you in the code below My os is Ubuntu 20.04 this is the myapp/cron.py file as mentioned in the documentation cron.py from .models import Cats def my_scheduled_job(): Cats.objects.create(text='Testt') and this is the settings i used frm the documentation CRONJOBS = [ ('*/1 * * * *', 'coins.cron.my_scheduled_job') ] INSTALLED_APPS = ( 'django_crontab', ... ) i keep getting this error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/crontab.py", line 126, in run_job job = self.__get_job_by_hash(job_hash) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/crontab.py", line 171, in __get_job_by_hash raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! even i tried to add python manage.py crontab add again and show and it appears python manage.py … -
How to solve sender mail and receiver same issues in Django?
I want, when a user will submit the contact form then I'll get a mail from the user mail. Everything is okay here, but the issue is I get the mail from my own mail when a user submits the form. Mean, sender mail and receiver mail is the same. That's why I can't see from which mail the mail cam Where is the problem?😢. Help me to resolve the issues. views.py: def ContactME(request): if request.method == "POST": MessageSenderName = request.POST.get('name') SenderMessage = request.POST.get('message') SenderEmail = request.POST.get('email') Contact.objects.create( Name = MessageSenderName, Email = SenderEmail, Message = SenderMessage, ) send_mail( '(Portfolio)' + MessageSenderName, SenderMessage, SenderEmail, ['mossaddak15-2413@diu.edu.bd'], ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'demo@gmail.com' EMAIL_HOST_PASSWORD = 'vkqhtdnqhzfrcuhs' EMAIL_USE_TLS = True -
Django & mongoDB integration failing
i'm trying to connect my django project with MongoDB by using djongo. every time i run the python manage.py migrate, the migration runs but it throws an error after this Applying App.0007_alter_order_customer_alter_orderitem_customer_and_more...Not implemented alter command for SQL ALTER TABLE "App_order" ALTER COLUMN "customer_id" TYPE int how to fix this??? i'm using two database in one cluster btw, hopefully that's not an issue #settings.py """ Django settings for amazon_clone project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-su&kse9ph!^@6x@r^vbb6396okv7u5mf#$cy()n(vl90y&kbe@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://amazon-clone69.herokuapp.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'App', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, … -
Get django date from subtracted timezone now
I am subtracting django's model datetimefield from timezone.now() and its resturning 17 days ,20:33:09.233443 as output , how to get date format? datetimefield = django_model.created_date date_i_want = timezone.now() - datetimefield print(date_i_want) output: 17 days, 20:33:09.233443 -
Call Celery Inspect from Django fails on every 2 requests with a "not enough values to unpack (expected 2, got 1)"
I am calling the following code from a django view (taken from https://docs.celeryq.dev/en/latest/userguide/workers.html#inspecting-workers): inspect_report = celery_app.control.inspect() tasks_active = inspect_report.active() It works correctly the first time but when I refresh the page i get a ValueError: not enough values to unpack (expected 2, got 1) Stacktrace: File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 458, in thread_handler raise exc_info[1] File "/venv_path/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/venv_path/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 423, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/home/benjamin/.pyenv/versions/3.9.6/lib/python3.9/asyncio/tasks.py", line 442, in wait_for return await fut File "/venv_path/python3.9/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 462, in thread_handler return func(*args, **kwargs) File "/venv_path/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/venv_path/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/benjamin/project/administration/views.py", line 357, in dashboard tasks_active = inspect_report.active() File "/venv_path/python3.9/site-packages/celery/app/control.py", line 149, in active return self._request('active', safe=safe) File "/venv_path/python3.9/site-packages/celery/app/control.py", line 106, in _request return self._prepare(self.app.control.broadcast( File "/venv_path/python3.9/site-packages/celery/app/control.py", line 741, in broadcast return self.mailbox(conn)._broadcast( File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 344, in _broadcast return self._collect(reply_ticket, limit=limit, File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 386, in _collect self.connection.drain_events(timeout=timeout) File "/venv_path/python3.9/site-packages/kombu/connection.py", line 317, in drain_events return self.transport.drain_events(self.connection, **kwargs) File "/venv_path/python3.9/site-packages/kombu/transport/virtual/base.py", line 969, in drain_events … -
Redis-RQ not executing jobs
I have a question but it turns out I have similar problems to other Github threads that haven't been resolved yet, might as well ask it here. I am running Django and is using redis-rq to execute background jobs. Unfortunately, it doesn't execute jobs from the default queue. I have already tried to rename it but no progress so far. Have you guys had this similar event before, and how did you resolve it? Thanks! -
Proper directory structure for app versioning (Django)
I am currently starting work on a existing Django Project, and I need to make changes to the existing APIs. However, I can't change the existing code since old apps and sites have been using it, which might take a lot of time to change the structure, and might break current dependencies for those. So, for now, as asked, I need to maintain separate directories to change/review the existing code and achieve a versioning-like structure for Django apps. What might be the best way/structure to achieve this? The current structure is simple as given by django-admin startproject project_dir |___project_name_dir |___settings.py ... |___app_1_dir |___ __init__.py |___ views.py, serializers.py ... |___app_2_dir ... So, I need to like create versioning type structure for app_1 here. What might be the best approach to do that? -
Django Rest Framework custom throttling classes not working
I am having issues with setting up custom throttling using the django-restframework for django. I made the following views.py class which contains a view with this custom throttle: from .custom_throttles import * @api_view(('GET',)) @throttle_classes([LowLevelThrottle]) def home_stats(request): token = request.data['token'] if token == os.environ['api_token']: content = { 'users' : len(Profile.objects.all()), 'posts' : len(Post.objects.all()), 'reactions' : len(PostReaction.objects.all()) } return Response(json.dumps(content), status=status.HTTP_200_OK) else: content = { 'error' : 'invalid token' } return Response(json.dumps(content), status=status.HTTP_401_UNAUTHORIZED) This custom throttle is imported from custom_throttles.py which looks as following: from rest_framework import throttling class LowLevelThrottle(throttling.AnonRateThrottle): scope = 'll' def allow_request(self, request, view): if request.method == "GET": return True return super().allow_request(request, view) And last but not least, this is how I have some settings in my settings.py file setup: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'django_project.custom_throttles.LowLevelThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'll': '1/second', } } I also have the following logs I can provide clearly showing how multiple requests were made within this 1 second time frame. [24/Aug/2022 07:43:14] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:23] "GET /homestats HTTP/1.1" 200 51 [24/Aug/2022 07:43:24] "GET /homestats … -
How to use Django with a legacy mysql 5.7 database (troubles with mysqlclient version)
I started a new Django project, but it supposed to be working with a legacy MySQL 5.7 database. For now, I have Django project, with specified database in settings.py and mysqlclient installed. First thing i tried was python manage.py inspectdb --database dbname but I git this error: MySQLdb.OperationalError: (1043, 'Bad handshake') I already realized that this is because I have mysqlconnector for version 8.0, and it's not compatible with mysql 5.7. I also found out that when installing mysqlconnector, its version depends on what i have in mysql_config. If I type mysql_config --version I get 8.0.30 And I cannot understand why, because if I run sudo dpkg-reconfigure mysql-apt-config It says that I have currently selected mysql-5.7. What actually is mysql_config and why it's configured to a different version? How can I switch it to 5.7 and have right version of mysqlclient installed? Or are there any other ways to make mysql 5.7 and my Django project work together? -
model creation in django
"here is the code i entered" class Projects(models.Model): title = models.CharField(max_length = 200) description = models.TextField(null = True, blank = True) demo_link = models.CharField(max_length = 2000, null = True, blank = True) source_link = models.CharField(max_Length = 2000, null = True, blank = True) created = models.DateTimeField(auto_now_add = True) id = models.UUIDField(default = uuid.uuid4, unique = True, primary_key = True, editable = False) code -
DRF - Request unique identifier [closed]
Is there any unique identifier like uuid in request object? from rest_framework.decorators import api_view from rest_framework.responses import Response @api_view(['GET]) def index_view(request): return Response() If there is not where to add it? Into request.META? -
How to Manage/Add Multiple User in Django Rest Framework
Scenario The are two roles in the system; LIBRARIAN and MEMBER As a User I can signup either as LIBRARIAN and MEMBER using username and password I can login using username/password and get JWT access token As a Librarian I can add, update, and remove Books from the system I can add, update, view, and remove Member from the system As a Member I can view, borrow, and return available Books Once a book is borrowed, its status will change to BORROWED Once a book is returned, its status will change to AVAILABLE I can delete my own account As i'm a newbie. Please help in how can I create the models of these. Thank you -
serializer.data and serializer.validated_data is blank when a serializer is initialized by dictionary
I am building an app using django and drf. While testing a serializer, I found the serializer could not save data to database because of null constraints. Below is the test code, serializer and model. location_serializer_data: LocationDict = { 'address': 'address', 'latitude': 11.1, 'longitude': 22.2, } @pytest.mark.django_db def test_deserializing(self): serializer = LocationSerializer(data=location_serializer_data) serializer.is_valid() new_location = serializer.save() # < where the test explodes Here is the error message django.db.utils.IntegrityError: NOT NULL constraint failed: locations_location.latitude I found that serializer.initial_data gets the data appropriately, but after serializer.is_valid(), two of serializer.data, serializer.validated_data become blank dict. I searched a bit but I found no clue of what was causing this. -
How to solve AttributeError of rest_framework_simplejwt/token_blacklist migration error?
After running python manage.py runserver I got a migration suggestion You have 9 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): token_blacklist. Run 'python manage.py migrate' to apply them. So I ran the migration command: python manage.py migrate Then I got this AttributeError. Part of the stack trace: File "{myproject_folder}/env/lib/python3.8/site-packages/rest_framework_simplejwt/token_blacklist/migrations/0003_auto_20171017_2007.py", line 11, in populate_jti_hex token.jti_hex = token.jti.hex AttributeError: 'str' object has no attribute 'hex'. System & Python Information: OS: Ubuntu 22.04.1 LTS x86_64 Kernel: 5.15.0-46-generic python: python3.8.10 I am using pyenv for multiple python installations and venv for the virtual environments. -
Difference between Django normal and Async views
async def index(request): return HttpResponse("Hello, async Django!") and def index(request): return HttpResponse("Hello, Django!") -
Django: typehinting backward / related_name / ForeignKey relationships
Let's say we have the following django models: class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo) And if I use this somewhere in some other class: bar = self.foo.bar Then mypy complains: Foo has no attribute "bar" How can I make mypy happy here? -
How can I update my {% for x in list %} table with setInterval() in Django?
[NOTE] I'm really new in web development. Please consider this I can make mistakes and I can ask stupid questions. Sorry about everything. Hello, I'm trying to make a student table with Django + Ajax. But there's a problem which I really can't understand how can I implement my ajax code for each row in the table. Now, I'm taking first index of every field in my ajax code. And ajax refresh this field in tables every second. But I want to update every cell and row in every second. Also I tried to add new cell with append(). It doesn't worked because of {% for students in object_list %} I didn't understand how to add a new append() row in {% for students in object_list %} In my html, this is the table body and ajax code. infoindex.html <table class="table table-light" id="studentstable"> <thead> <tr> <th scope ="col">Numara</th> <th scope ="col">Adı</th> <th scope ="col">Soyadı</th> <th scope ="col">Yaşı</th> <th scope ="col">Cinsiyet</th> </tr> <tbody id="tbodyid"> {% for students in object_list %} <tr> <td id="num">{{students.num}}</td> <td id="first_name">{{students.first_name}}</td> <td id="last_name">{{students.last_name}}</td> <td id="age">{{students.age}}</td> <td id="gender">{{students.gender}}</td> </tr> {% endfor %} </tbody> </table> <script> setInterval(function (){ $.ajax({ url : "http://127.0.0.1:8000/studentsapi", dataType: "json", success : function (data) { … -
Django send profile picture with django channels
I am doing a chat app and I want to show the profile picture of a user every time he sends something in the chat. Here is the code: Models.py class Chat(models.Model): room_name = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) username = models.CharField(max_length=200,blank=False,null=True,unique=True) profpic = models.ImageField(upload_to='profpics/',blank=True,null=True) Consumers.py # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import * from main.models import * class ChatConsumer(AsyncWebsocketConsumer): @sync_to_async def get_profile(self): return self.scope['user'].profile async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] room = text_data_json['room'] profile = await self.get_profile() profile_pic = profile.profpic profpic = json.dumps(str(profile_pic)) print(profpic) username = text_data_json['username'] await self.save_message(message, room,username) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username':username, 'profpic':profpic } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] profpic = event['profpic'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username':username, 'profpic':profpic })) chat.html .... chatS.onmessage = function(e){ const data …