Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hello you can explain to me how to make a one to one communication
hello you can explain to me how to make a one to one communication system example of facebook with chat in friend or linkedin -
calling a function on button click in Django
I have multiple buttons on an HTML page. When a user clicks them, I want to call respective functions and manipulate the database. I don't know if Django-forms are the right thing to use here. If yes, should I use different forms for different buttons? -
How to get the value (not the key) of a TypedChoiceField in django form?
I have a django form with some TypedChoiceFields like this one : Q1 = forms.TypedChoiceField(coerce=choice_parser, choices = Q1_CHOICES, label=Q1_TITLE, initial='', widget=forms.Select(), required=True) Here is my Q1_CHOICES : Q1_CHOICES = ( ("W", "Woman"), ("M", "Man") ) My problem is in my view when I call this form when I want to get the answer of the user I only succeeded to get the keys (W or M) but never the values "Man" or "Woman". I used form.cleaned_data["Q1"] to get the answers. I know I could differiantiate them with "W" and "M" but for the other questions it is a big deal Thanks for your help -
RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'
Trying to call app.add_chat_members from Pyrogram in a Django view but can't seem to instantiate the client. Steps to Reproduce views.py ... from pyrogram import Client def add_users_to_chat(chat_id, user_ids, forward_limit = 0): user_bot = Client("session_name", api_key=API_KEY, api_hash=API_HASH) with user_bot: return user_bot.add_chat_members(chat_id, user_ids, forward_limit) def add_user_to_chat_view(request): ... add_users_to_chat(request.kwargs.get('chat_id'),request.user.telegram_id) I am running django in asgi with uvicorn uvicorn config.asgi:application --host 127.0.0.1 --reload. I have tried using async: async def add_users_to_chat(chat_id, user_ids, forward_limit = 0): user_bot = Client("session_name") async with user_bot: return await user_bot.add_chat_members(chat_id, user_ids, forward_limit) I have also tried async_to_sync from asgiref.sync import async_to_sync @async_to_sync async def add_users_to_chat(chat_id, user_ids, forward_limit = 0): user_bot = Client("session_name") async with user_bot: return await user_bot.add_chat_members(chat_id, user_ids, forward_limit) Traceback File "/utils/telegram.py", line 6, in <module> from pyrogram import Client File "/.local/lib/python3.8/site-packages/pyrogram/__init__.py", line 41, in <module> from .client import Client File "/.local/lib/python3.8/site-packages/pyrogram/client.py", line 44, in <module> from pyrogram.methods import Methods File "/.local/lib/python3.8/site-packages/pyrogram/methods/__init__.py", line 25, in <module> from .messages import Messages File "/.local/lib/python3.8/site-packages/pyrogram/methods/messages/__init__.py", line 23, in <module> from .edit_inline_media import EditInlineMedia File "/.local/lib/python3.8/site-packages/pyrogram/methods/messages/edit_inline_media.py", line 25, in <module> from .inline_session import get_session File "/.local/lib/python3.8/site-packages/pyrogram/methods/messages/inline_session.py", line 27, in <module> lock = Lock() File "/usr/lib/python3.8/asyncio/locks.py", line 164, in __init__ self._loop = events.get_event_loop() File "/usr/lib/python3.8/asyncio/events.py", line 639, in get_event_loop raise RuntimeError('There is no … -
Message not showing when returning 204 status code
Inside my custom DeleteView view I have delete method and I want to just display message in some case. The code: messages.success(request, "hi") return HttpResponse(status=204) The problem is that it does not display the message until I reload, or move to other screen. I want to keep the use in the same screen and just display the message so I return 204. How to make it work? -
Truncate reverse in Django
I just want to truncate reverse chars in Djanog. For example I have this value Image/path_image.jpg then, the output that I want is path_image.jpg. The first 6 chars should not be included in displaying the characters. Currently I've been using {{ img_photos.photos |truncatechars:9}} but It includes Image. Is there any documentation or idea to do this? Thanks in advance. -
Problems with get_gueryset method in Django
I have a problem with filtering a queryset that after filtering should be paginated, I am using get_queryset to filter the queryset of objects but on the page nothing is displayed. I have a blog page where I have all the post in a list, and are paginated, on the page I have the most common tags and whenever I click on a tag it redirects the user on the page with posts that have that tag and I want them to be displayed in a list and to be paginated like in the initial page but it's not working. my view: class TaggedPostListView(ListView): model = Post template_name = 'blog/blog.html' context_object_name = 'posts' paginate_by = 2 def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) tags = Post.tags.most_common()[:8] context['banner_page_title'] = 'Blog' context['page_location'] = 'home / blog' context['tags'] = tags return render(request, self.template_name, context) def get_context_data(self, **kwargs): context = {} return context def get_queryset(self): tag = get_object_or_404(Tag, slug=self.kwargs.get('slug')) return Post.objects.filter(tags=tag).order_by('-published_date') model: class Post(models.Model): class PostCategory(models.TextChoices): FAMILY = 'FAMILY', _('Family') BUSSINESS = 'BUSSINESS', _('Bussiness') MWRKETING = 'MARKETING', _('Marketing') SPENDINGS = 'SPENDINGS', _('Spendings') author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=200, unique=True) content = models.TextField(_('Content')) category = models.CharField(_('Category'), max_length=9, choices=PostCategory.choices, default=PostCategory.BUSSINESS) slug = models.SlugField(_('Slug'), … -
'TreeQuerySet' object has no attribute 'name'
I have a Problem in Converting the' TreeQuerySet' object to the QuerySet object This is the error I am getting While serializing using DRF Got AttributeError when attempting to get a value for field name on serializer SubCategoriesSerializer. The serializer field might be named incorrectly and not match any attribute or key on the TreeQuerySet instance. Original exception text was: 'TreeQuerySet' object has no attribute 'name'. Serializer class SubCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'slug', 'views', 'title', 'description', 'avatar', 'color' ) Api Views category = Category.objects.get(pk=1) categories = category.get_children() categories_serializer = SubCategorySerializer(categories, context={'request': request}) -
How can you connect Fetch API to output the data of the Django API?
I'm trying to build an email scrapper with Django and Python, I want the data to be outputted in the same page (meaning that when someone enters a URL, the emails found would be printed in the same page). I've build an script to do this. Particularly, a Javascript script which is this one: function submitURL() { const url = document.querySelector("#InputSearch").value; const data = { url }; fetch('http://127.0.0.1:8000/api/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); } For now, when i run this code nothing happens. But I want it to detect the URL that is being inputted and output the emails scrapped in the same page. Do I need to create an API and if so? What would be the values in that API? -
How To Add Certain Amount To a User Balance immediately a post is Added Succesfully
I want User to be able to Earn from my website immediately they add a post on the website but am finding it difficult to add that feauture to my apps. I want an amount to be added to my website immediately a post is submitted. Please take a good look at my code* The Below code is for my post models.py. class Post(models.Model): title = models.CharField(max_length=160, help_text='Maximum 160 Title characters.') summary = models.TextField(max_length=400, help_text='Maximum text of 400 characters can be inserteed here alone' ) subtitle = models.CharField(max_length=250, blank=True) introduction = models.TextField(max_length=500, blank=True, user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)) content = RichTextUploadingField(blank=True, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) This is a short code for my balance.py class Balance(models.Model): user = models.ForeignKey(User) date = models.DateTimeField(default=timezone.now) balance = models.IntegerField(default = 0) Question Summary I have a blog post where every users on the website is elligible to Post News and Information on the website and every user have a balance. I Now want $2 to be added to this default balance of every Aunthenticated Users immediately a post is beeing added succesfully by a registered user. That is if an aunthenticated user on my website add a post then an … -
How to pass data from template to django side
I just started to code Python Django. I just wanted to make basic login project. I tried to pass login variables from html side to views.py Here is my html code: <form action="/index" method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input class="form-control" id="username" type="email"/> </div> <div class="form-group"> <div class="d-flex justify-content-between"> <label for="password">Password</label><a class="fs--1">Forgot Password?</a> </div> <input class="form-control" id="password" type="password" /> </div> <div class="custom-control custom-checkbox"> <input class="custom-control-input" type="checkbox" id="card-checkbox" checked="checked" /> <label class="custom-control-label" for="card-checkbox">Remember me</label> </div> <div class="form-group"> <button class="btn btn-primary btn-block mt-3" type="submit" id= "login" name="submit">Log in</button> </div> </form> My urls.py: urlpatterns = [ path('', views.loginPage, name="login"), path('index', views.home, name="index") ] My forms.py from django import forms class LoginForm(forms.Form): username = forms.EmailField(label="Username"), password = forms.CharField(label="Password") And my views.py def home(request): context = {} if request.method == 'POST': form = LoginForm(request.POST) print('form:', form) if form.is_valid(): print('niceee') else: return render(request, 'index.html', context) else: form = LoginForm() I can't see variables into views.py. How can i fix this? -
Django QuerySet lazy evaluation different in python debugger compared to normal execution
I'm working on implementing a paging solution for running post-processing on a model that has grown very large in the database. The general approach I'm taking for this is the following: set up the base QuerySet definition evaluate the total row count using .count() (i.e. not returning all of the data yet) use the QuerySet slicing syntax to fetch the data in chunks with a bounded size The pseudo code looks something like the following: 1 : base_queryset = MyBigModel.objects.filter(...).values(...).exclude(...).annotate(...).order_by(...) 2 : 3 : count = base_queryset.count() 4 : 5 : chunks = (count // pagesize) + 1 6 : for i in list(range(chunks)): 7 : # grab slice of queryset 8 : chunk_qs = base_queryset[(i * pagesize):(i * pagesize) + pagesize] 9 : print(chunk_qs.query) # examine rendered SQL 10: print(chunk_qs.explain()) # examine query plan When I run the above code in normal mode it behaves as expected. The QuerySet slicing syntax on line 8 returns another QuerySet object and I'm able to inspect the SQL query and query plan on lines 9-10. Note that my expectation is even at this point, the query has not been fully executed. The lazy evaluation should hold off until I perform an operation … -
Django - Image not saving from form
I am getting an error setting up this Django web app. I receive a 505 error message whenever I hit the submit button. The image is supposed to be saved in the root directory, but I can't seem to figure out the problem. Below is the code for the web app urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url from CancerClassifier import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url('^$', views.index, name = 'homepage'), url('predictImage', views.predictImage, name='predictImage'), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) views.py: from django.shortcuts import render from django.core.files.storage import FileSystemStorage def index(request): context = {'a' : 1} return render(request, 'index.html', context) def predictImage(request): print(request) print(request.POST.dict()) fileObj = request.FILES['filePath'] fs = FileSystemStorage() fs.save(fileObj.name, fileObj) context = {'a' : 1} return render(request, 'index.html', context) index.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Skin Lesion Classifier</title> </head> <body> <h1>Upload new File</h1> <form class="imageUpload" action="predictImage" method="post"> {% csrf_token %} <input type="file" name="filePath"> <input type="submit" value="Submit"> <br> <h3>Prediction: {{prediction}}</h3> </form> </body> </html> This is the error message i received in the terminal: [16/Jan/2021 17:13:14] "GET / HTTP/1.1" 200 493 <WSGIRequest: POST '/predictImage'> {'csrfmiddlewaretoken': 'UPYALDxVQ8SJR8DDy55h14PnaaWElXBwcYnlms6hhpV9qgbtdy1hW6UnU1Y8TVpk', 'filePath': 'image-asset.jpeg'} Internal Server Error: … -
Error: Command '['H:\\Django Practice\\My_Blog_project\\env\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']
Error: Command '['H:\Django Practice\My_Blog_project\env\Scripts\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. -
Add extra context to admin index page
In my admin.py of my admin dashboard app I added this following code: class MyAdminSite(admin.AdminSite): def index(self, request, extra_context=None): if extra_context is None: extra_context = {} extra_context['foo'] = 'bar' return super(MyAdminSite, self).index(request, extra_context) I try to display the context in the index.html (Line 15) but it doesn't work. Did I miss any step required? Thanks {% extends "admin/base_site.html" %} {% load i18n static %} {% block breadcrumbs %}{% endblock %} {% block content %} <div class="content"> <div class="row"> <div class="col-12"> <div class="card card-chart"> <div class="card-header"> <div class="row"> <div class="col-sm-6 {{ direction.panel }}"> <h5 class="card-category">{% trans "Total Shipments" %}</h5> <h2 class="card-title">{% trans "Performance" %}{{ foo }}</h2> </div> ... {% endblock %} -
How to share files through websocket in django?
I'm building a chat application in django using django channels. But can't able to find enough tutorial regarding the file sharing through websockets. Can anybody help to figure it out? -
Html files do not work in Python from Django
I have a problem with the html file in Python Django. This is my code: {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> {% endblock content %} And this is the result: Any idea? -
Pass url href in Django
The problem is, how can I pass data from html to my views, based on selected row button in my html. As you can see the trigger to pass data is through Submit button which I've been using href and get the id. The problem is there's no arguments not found in my url.It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Html {% for folder in folder_list %} <a href="{% url 'view_gallery' folder.id %}" class="btn btn-outline-teal" >Submit</a> {% endfor %} Url.py urlpatterns = [ path('scanned_docs/',views.scanned_docs, name='scanned_docs'), path('view_gallery/<str:pk>/',views.view_gallery, name='view_gallery') ] views.py def view_gallery(request,pk): if request.method == 'POST': image = gallery_photos.objects.filter(gallery_info_id = pk) data = {'photos':image} return render(request, 'view_gallery.html', data) @login_required(login_url='log_permission') def scanned_docs(request, reason=""): #I think there's no problem here in this function folder = folder_info.objects.all() data = {'folder_list':folder} return render(request, 'scanned.html',data) -
I am trying to fix the ordering only on 1 category but its still displaying from the first post
I am displaying only posts from category with id=1 but in template and i did the order_by but still on template its showing from the first post not from the latest class LajmetListView(ListView): model = Lajmet model = Kategori template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit') context['trilajmet'] = Kategori.objects.get(pk=1) return context {% for lajmet in trilajmet.lajmet_set.all %} {% if forloop.counter < 5 %} <div class="single_iteam"> <a href="pages/single_page.html"> <img src="media/{{lajmet.fotografit}}" alt=""></a> <div class="slider_article"> <h2><a class="slider_tittle" href="pages/single_page.html">{{lajmet.titulli}}</a></h2> <p>{{lajmet.detajet}}</p> <p>{{lajmet.data_e_postimit}}</p> </div> </div> {% endif %} {% endfor %} -
Exit status 1 error while installing mod_wsgi
I am getting following error while installing mod_wsgi using pip3. I downloaded it once mistakenly before installing Apache, then it threw error for Apache's unavailability and didn't install. Then I installed Apache using command brew install apache2 and then did pip3 install mod_wsgi --no-cache-dir so that it don't take up the cached image, but it didn't work and got following error. Any help is much appreciated. Thanks! Collecting mod_wsgi Downloading mod_wsgi-4.7.1.tar.gz (498 kB) |████████████████████████████████| 498 kB 4.6 MB/s ERROR: Command errored out with exit status 1: command: /usr/local/opt/python@3.9/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/0f/3wwtkx4d6m94zpmq0r5rw5c80000gn/T/pip-install-lygp82k1/mod-wsgi_ef198f9a817445a7b3cf53dd590fbdb2/setup.py'"'"'; __file__='"'"'/private/var/folders/0f/3wwtkx4d6m94zpmq0r5rw5c80000gn/T/pip-install-lygp82k1/mod-wsgi_ef198f9a817445a7b3cf53dd590fbdb2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/0f/3wwtkx4d6m94zpmq0r5rw5c80000gn/T/pip-pip-egg-info-2q3u8hgc cwd: /private/var/folders/0f/3wwtkx4d6m94zpmq0r5rw5c80000gn/T/pip-install-lygp82k1/mod-wsgi_ef198f9a817445a7b3cf53dd590fbdb2/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/0f/3wwtkx4d6m94zpmq0r5rw5c80000gn/T/pip-install-lygp82k1/mod-wsgi_ef198f9a817445a7b3cf53dd590fbdb2/setup.py", line 490, in <module> target_version = tuple(map(int, target.split('.'))) AttributeError: 'int' object has no attribute 'split' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
s3 aws user authentication in django
Hi I'm using Arvan cloud (arvancloud.com/en) cloud storage in my porject (very similar to S3 AWS). and aslo I'm using django-storages and boto3 libraries. my project is a online learning platform (like udemy). and I have courses and lessons. so I should authenticate the users who want to download or see the contents (video or document) if he/she bought the course it is possible to see or download the contents. my question is how can i authenticate users? (So that they can not illegally access the content) How about query string expiration? (I tried to reduce the expiration time but it did not work!) these are my codes: # this is models.py for course app. User = get_user_model() class Category(models.Model): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(null=True, blank=True, unique=True) sub_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub_categories') def __str__(self): return f'{self.name}' def save(self, *arg, **kwargs): self.slug = slugify(self.name) return super().save(*arg, **kwargs) class Course(models.Model): teachers = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses') name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank=True, unique=True) cover = models.ImageField(upload_to='files/course_covers/', storage=CourseMediaStorage()) description = models.TextField(max_length=512) requirements = models.TextField(max_length=120) price = models.DecimalField(max_digits=5, decimal_places=2) is_free = models.BooleanField(default=False) def __str__(self): return self.name def save(self, *args, **kwargs): if self.is_free: self.price = Decimal('0') self.slug = slugify(self.name) return super().save(*args, **kwargs) … -
Add 1 to a database value when button is pressed using Django
I have a django model that looks like this: class Character(models.Model): character_Name = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) level = models.PositiveSmallIntegerField(validators=[MaxValueValidator(20), MinValueValidator(1)], default=1) def __str__(self): return self.character_Name with an html file(main.html) that looks like this: <!DOCTYPE html> <html lang="en"> <body> <h1>{{ characters.character_Name }}</h1> <h4>Level: {{ characters.level }}</h4> <button onclick="increase_level()"> + 1 </button> </body> a function in views.py that looks like this: def main(request): if request.user.is_authenticated: characters = Character.objects.filter(user=request.user).order_by('character_Name').first return render(request, 'main.html', {'characters': characters}) else: return redirect('account creation') and its path from urls.py: path('main', views.main, name='main'), How can I implement the press of the button updating the page and the database by leveling up by 1? -
error 404 (Not Found) when trying to get local JSON file with AJAX method on django project
I'm trying to access my database from a JS file. In order to do so I serialized all my models objects into local JSON files and now I'm trying to read this files with the AJAX method (wich I've never tried before), but it's failing to find them. My directories look something like this: /RecipeSite (...) /reading /writing (...) /static/writing/ /css /scss /js forms.js /json test.json (...) In my writing/js/forms.js i have this code: (...) $.ajax({ type: "GET", dataType: "json", url: "/test.json", success: function(data) { console.log(data); } }); (...) but when i run it, the console shows GET http://127.0.0.1:8000/test.json 404 (Not Found) -
Overriding the create method of Django Rest Framework Serialization
I am creating a Django backend where I am using Django Rest Framework for building REST API. I have nested serialization, and when I try to serialize the data I have to override the create function of the ModelSerializers. I'm a bit scared that this is going to cause a problem or a loophole in the backend's security as I am not using the default validation when creating an object. SO IS IT NORMAL TO DO SO? # THIS IS MY MODELS.PY from django.db import models from django.contrib.auth.models import User class UnivStudent(models.Model): """ A class based model for storing the records of a university student Note: A OneToOne relation is established for each student with User model. """ user = models.OneToOneField(User) subject_major = models.CharField(name="subject_major", max_length=60) # THIS IS MY SERIALIZERS.PY from rest_framework import serializers, status from models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') class StudentSerializer(serializers.ModelSerializer): """ A student serializer to return the student details """ user = UserSerializer(required=True) class Meta: model = UnivStudent fields = ('user', 'subject_major',) def create(self, validated_data): """ Overriding the default create method of the Model serializer. :param validated_data: data containing all the details of student :return: returns … -
how to deploy android app on server and additional convert django to apk
I am very new to android application development; I want to know how to deploy an app and how much it cost to deploy as an additional question, I am fairly good at Django so I want to ask can I convert the Django web application into apk file and how; just share an example link