Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Add $2 To a User Account Balance Immediately A Post is Viewed on a Django Blog
I want Users on my website to be able to Earn from my website immediately they View a post on my blog 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 been viewed on clicked on and i have an IP function because i want the action to be once(the amount should be added once). Please take a good look at my models.py for the post 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,) content = RichTextUploadingField(blank=True, null=True) This is balance.py class Balance(models.Model): user = models.ForeignKey(User) date = models.DateTimeField(default=timezone.now) balance = models.IntegerField(default = 0) In my models.py i also have a code for my view #this is used in ordering view count in django views class PostView(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE) date = models.DateTimeField(auto_now=False, auto_now_add=True) ip = models.GenericIPAddressField(null=False, blank=False) class Meta: ordering = ['-date'] This is the property that counts my views @property def view_count(self): return PostView.objects.filter(post=self).count() Question Summary I Now want $2 to be added to this default … -
Why is this not JSON?
"{"ops": [{"insert": "Ajax story content."}]}" I am trying to send json from a django view to my template and play with it with JS. Why can I not parse this? When I run JSON.parse() I am given an error that says VM817:1 Uncaught SyntaxError: Unexpected token in JSON at position 40 at JSON.parse () at :1:6 I've run it through JSONLint and it gives me an error Error: Parse error on line 1: "{"ops ": [{"insert ": Expecting 'EOF', '}', ':', ',', ']', got 'undefined' To me, it looks like valid JSON. What's up? -
Why my model's __str__ method return a Queryset only when testing?
I have a simple model that have a __str__ method that returns a string as expected, but when testing the __str__ method it returns a Queryset and the test fails. Why this happens? I am already calling the method using str() instead of __str__() as this other post suggested class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username In the shell it returns the username from the corresponding User object as a string, as expected: author = Author.objects.get(pk=1) str(author) 'edumats' But when testing the __str__ method of the model, the test fails, as the method returns a Queryset: The test: def test_author_methods(self): author1 = Author.objects.filter(user__username='Test User') self.assertEqual(str(author1), 'Test User') The error from the test: FAIL: test_author_methods (posts.test_models.PostTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/edumats/Projects/blog/blog/posts/test_models.py", line 37, in test_author_methods self.assertEqual(str(author1), 'Test User') AssertionError: '<QuerySet [<Author: Test User>]>' != 'Test User' - <QuerySet [<Author: Test User>]> + Test User -
Django ORM - Can I create a new object with a foreign key using a different column other than ID?
I checked around a fair bit and could not find any examples of what I am looking for so i am not sure if it is possible at all. I have a model with a foreign key. I want to create a new object in that model but i don't have the ID but I do have the field "username" value. I should also add that this is a foreign key relationship to another foreign key WeekdayAssignment Model example: class WeekdayAssignment(models.Model): start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) triage = models.ForeignKey(TeamMember, on_delete=models.PROTECT, related_name="triagers") ... TeamMember Model Example: class TeamMember(models.Model): member = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='Member Name') ... User Model Example: class User(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50) What I would like to do is create a new object using the members username from the Foreign key's not the ID like this: WeekdayAssignment.objects.create(start_date='2021-01-13', end_date='2021-01-20', triage__member__username='jac') However, if i do this i get the error WeekdayAssignment() got an unexpected keyword argument 'triage__member__username' and same thing if i drop __username If drop the __member__username from the field like this: WeekdayAssignment.objects.create(start_date='2021-01-13', end_date='2021-01-20', triage='jac') i get ValueError: Cannot assign "'jac'": "WeekdayAssignment.triage" must be a "TeamMember" instance. which is totally expected as … -
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) …