Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it a good idea to run django management command as windows service?
Following this answer you can register a python script as a windows service with NSSM. But are there any obvious downsides on registering a django management command as windows service this way? nssm.exe install ProjectService nssm.exe set ProjectService Application "c:\path\to\env\Sricpts\python.exe" nssm.exe set ProjectService AppParameters "c:\path\to\django_project\manage.py command" The command would parse the contents of some files as they are being created. -
How to stop page refresh on each task addition in my Django To-do app?
I am quite new to the web development world and have just built a Todo app using Django and hosted the app on Heroku. I have used Django ModelForm for adding tasks to my TaskModel. Now my problem is that each time I add a task, the whole page refreshes as the added task goes to the postgres database used by Heroku. It is not a very good user experience, as it is refreshing the page on each task addition and also it is taking time for reloading the page. What should I do to stop page refresh but still add the task to the database? Note: I have used authentication in my todo app so that the tasks can be accessed from any device, so I don't think storing my task merely in the browser cache will work. But I am open to any suggestions. -
python django variables from views.py to html show the code intead of the value
I'm trying to print my products from sqlite the problem is that the result in the browser is the code itself and not the value. views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'dict': products}) index.html: <ul> {% for prod in dict %} <li>{{ prod.name }}</li> {% endfor %} </ul> The result in the browser is: {% for prod in dict %} {{ prod.name }} {% endfor %} -
SOCKETS IN DJANGO
I've build an app in Django that sends socket messages to a external Desktop app. It works perfectly in local sending messages to a custom Ip and port address using the python library Websockets. Here's my code: import asyncio import websockets async def getstatus(ip,port): uri = f"ws://{ip}:{port}/" async with websockets.connect(uri) as websocket: await websocket.send(str(json.dumps({"Action":"status"}))) return await websocket.recv() Now i deployed it into a HEROKU server and sockets doesn't work. I also use django Channels wirh Redis and Daphne Anyone knows the best way to do this??? Thanks a lot :) -
Converting a function decorator to a Class Mixin django
I tried to convert a cutoms decorator from a function to a Class Mixin because I use CVB and I wanted to inherit from this Mixin to check for users status for some pages. I have this decorator which check whether the user is authenticated or not, if the user is authenticated and tries to access a page that has this decorator it will be redirected to the dashboard if is not then il will have the access to acces the page. I wrote this class as a class version of the decorator and if the user is logged in then it works ok but if it it's not and tries to acces that page it give me this error: ImproperlyConfigured at /auth/login/ UserLoginView is missing the permission_required attribute. Define UserLoginView.permission_required, or override UserLoginView.get_permission_required(). this is the decorator: def is_authenticated(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('dashboard') else: return view_func(request, *args, **kwargs) return wrapper_func class version: class IsAuthenticatedMixin(PermissionRequiredMixin): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('dashboard') return super().dispatch(request, *args, **kwargs) the views which inherits this mixin class IndexFormView(IsAuthenticatedMixin, CreateView): permission_required = 'view' template_name = 'home/index.html' form_class = NewsletterForm def post(self, request, *args, **kwargs): email = request.POST['email'] if Newsletter.objects.filter(email=email).exists(): … -
The included URLconf 'appName.urls' does not appear to have any patterns in it
Checking the documentation doesn't show any potential cause for the error. I have a django project with a number of apps (dir layout: ) settings.py (cryptoboard): ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = "cryptousers.CryptoUser" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', 'rest_framework', 'frontend', 'knox', 'cryptousers', 'cryptocurrency', ] ... ROOT_URLCONF = 'cryptoboard.urls' urls.py (cryptoboard): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('frontend.urls')), path('', include('leads.urls')), path('', include('cryptousers.urls')), path('', include('cryptocurrency.urls')) # <== WORKS IF COMMENTED OUT ] urls.py (cryptocurrency): import sys from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ path('get_currency_latest/', views.get_latest_currency, name='get_currency_latest'), # this used to work # url(r'^get_currency_on_date/(?P<date_day>\d{4}-\d{2}-\d{2})/$', # views.get_currency_on_date, name='get_currency_on_date'), # # Sample: # # http://127.0.0.1:8000/get_currency_between_dates/2020-11-24/2020-11-25 # url(r'^get_currency_between_dates/(?P<date_start_day>\d{4}-\d{2}-\d{2})/(?P<date_end_day>\d{4}-\d{2}-\d{2})$', # views.get_currency_between_dates, name='get_currency_between_dates') re_path(r'^get_currency_on_date/(?P<date_day>\d{4}-\d{2}-\d{2})/$', views.get_currency_on_date, name='get_currency_on_date'), re_path(r'^get_currency_between_dates/(?P<date_start_day>\d{4}-\d{2}-\d{2})/(?P<date_end_day>\d{4}-\d{2}-\d{2})$', views.get_currency_between_dates, name='get_currency_between_dates') ] The same error is thrown regardless whether the urls.py above is as it is or empty. views.py (cryptocurrency) from django.shortcuts import render import json from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.utils import timezone from django.utils.datetime_safe import datetime … -
Django form field using jQuery
I want to pass the screen size of the client to the django view.py. Right now I am trying to pass it through a form from jQuery, but I keep getting 'None'. What am I doing wrong? Or is there any other way I could get the screen size? My js: <script type="text/javascript"> document.getElementById('{{ form.width.id_for_label }}').value = screen.width; document.getElementById('{{ form.height.id_for_label }}').value = screen.height; </script> HTML: <form id="myform" method="POST"> {% csrf_token %} {{ form.myfield }} <div class='width'> {{ form.width }} </div> <div class='height'> {{ form.height }} </div> <input id="submit" type="submit" style="display: none"/> </form> form.py class MymodelForm(forms.ModelForm): class Meta: model = Mymodel fields = ['myfield', 'width', 'height',] widgets = { 'width': forms.HiddenInput, 'height': forms.HiddenInput } -
How to make my webapp only accessible only on a private network/place
I'm building a webapp, actually it's ready to deploy but I need it to be restricted. like I want that I'm the only one and my client have access to that web application. That my client can't access it on other networks or IP address. only in his home/office. I already set CORS on my webapp but I don't know what IP to set. Is there a specific IP address to set on my CORS? because afaik, ISP IP addresses changes from time to time. How can I do it? thanks! -
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? -
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 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: …