Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache 24 Error: Forbidden You don't have permission to access this resource
I am running Django on an Apache24 server which is running but when i search for the localhost i get an error: Forbidden You don't have permission to access this resource.. When i check the logs i see this error: The given path is misformatted or contained invalid characters: AH00036: access to / failed (filesystem path 'C:/Apache24/\xe2\x80\x9cC:') Here are the relevant files: httpd.conf Define SRVROOT “c:/Apache24” ServerName localhost Include conf/extra/httpd-vhosts.conf LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" httpd-vhosts.conf <VirtualHost *:80> ServerName localhost ServerAlias localhost WSGIScriptAlias / “C:/Users/Administrator/Desktop/myapp/myapp/wsgi_windows.py” <Directory C:/Users/Administrator/Desktop/myapp/myapp/> <Files wsgi_windows.py> Require all granted </Files> </Directory> </VirtualHost> -
Get the value of a specific variable in a html template with django
I am trying to get the value which is stored in a variable as : html <p class="title" name="no">Guarde : {{no}}</p> ... <form action="nextep" method="get"> <button class="btright" name="btnext" action="nextep"> <i class="fas fa-chevron-circle-right"></i> </form> views.py def nextep(request): n = {{ no }} #I would like to get it from the initial value stored (which is 1) return render(request, "episode.html", {'no': n+1}) How could I do that please? I tried different version with request.get['no'] too, but nothing worked, if someone has an idea, thanks for you help -
How can I share a variable between multiple functions of a class in Django?
I want the page load to initialize "self.var" and then share this output with functions 'shared1' and "shared2" within the "main" class. I want to avoid declaring self.var each time I call "shared1" or "shared2". I also do not want to use request.sessions because this requires additional overhead when serializing self.var this is my views.py: class main: def __init__(self): self.var = ['test'] def pageload(request): context = {"nothing": "nothing"} return render(request, "index.html", context) def shared1(self, request): s1 = self.var s1alt = s1.append('test1') context = {"var": s1alt} return JsonResponse(context) def shared2(self, request): s2 = self.var s2alt = s2.append('test2') context = {"var": s2alt} return JsonResponse(context) this is my urls.py: path('home/',views.main().pageload,name="categories"), path('ajaxgets1/',views.main.shared1,name="ajaxgets1"), path('ajaxgets2/',views.main.shared2,name="ajaxgets2"), -
Is there a more efficient way to edit a django many to many field?
Is there a way to edit many to many fields in django that involves removing objects efficiently? lets say you have these models: class PerksAndBenefits(models.Model): name = models.CharField() class Company(object): perks_and_benefits = models.ManyToManyField(PerksAndBenefits) and your user sends in a list from the frontend to update their model: data=['name 1', 'name 2', 'name 3'] But the model has company.perks_and_benefits.all() = Queryset('name 1', 'name 3') is there a way to do this that doesnt involve clearing the company and then bulk creating through the relation model? -
ValidationError: [u'ManagementForm data is missing or has been tampered with.'] when trying to submit a form?
I have already tried the other posted solution to add the management file to the template. The only other answer online is about prefixes which we do not believe is the problem. Any ideas? -
How to run python codes (not in views) periodically in Django Framework?
I am using Django Framework to write a middleware. Basically, every week, it calls an external API to receive a xml file, does some data processing and sends the results to RabbitMQ. I am new to Django Framework. I wrote some python files to achieve the logic, but these files did not execute when running the server. I am wondering how to run these codes periodically which are not inside views. Thank you. -
How to retrieve https api endpoints from an opensource Pylons project: Reddit, specifically?
Reddit was opensource until a while ago, and here's their repo: https://github.com/reddit-archive/reddit I was wondering if it was possible to backtrack all https endpoints they use: for login, for sign-up, for posts, for comments, for follow, etc. Can we backtrack it? It will also be helpful if someone who has already figured this out shares their findings. Thank you. -
Explanation of Django error_messages{}?
With this explanation of implementing a custom user model in django there is the inclusion of error_messages{...} dictionary. Where does 'unique' come from? Where can I find a comprehensive list of the possible options? I have looked at the documentation for built-in field classes here and I have looked in the appropriate fields.py file on github which says EmailField inherits from CharField, which in turn inherits from base Field class. None of these mention 'unique' as a possible key in the dictionary so I'm really confused as to why you can define it. -
How to use a serializer with foreign keys for Django rest api?
I have two django models with a many-to-one relationship (one venue can have many events). I want to produce a page which has all the attributes from each event, and the information about its venue from the venue model. Here is my models.py file: class Venue(models.Model): venueID = models.AutoField(primary_key=True) venueName = models.CharField(max_length=40) venueImage = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.venueName class Event(models.Model): venueID = models.ForeignKey( Venue, related_name='events', on_delete=models.CASCADE) venueName = models.CharField(max_length=40) eventID = models.AutoField(primary_key=True) artistName = models.CharField(max_length=100) eventName = models.CharField(max_length=100) def __str__(self): return self.eventName Here is my serializers.py file class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = "__all__" class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = "__all__" class VenueForGivenEventSerializer(serializers.ModelSerializer): events = EventSerializer(many=True) class Meta: model = Venue fields = '__all__' My urls.py file: (I'm pretty sure that this is not the issue) from django.urls import path from django.urls.conf import include from .views import EventViewSet from .views import VenueViewSet from .views import VenueForGivenEventViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('events', EventViewSet) router.register('venues', VenueViewSet) router.register('fullevents', VenueForGivenEventViewSet) urlpatterns = [ path('', include(router.urls)) ] At the moment, when accessing /fullevents, I currently get an error saying: int() argument must be a string, a bytes-like object or a number, not 'Venue' … -
Django celery not using default queue
I'm using Django 3.2 and Celery with the following configuration celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quiz.settings') celery_app = Celery('quiz') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() @celery_app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and the following settings.py import os from kombu import Queue CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_DEFAULT_QUEUE = 'tb-account-task-queue' if os.environ.get('CELERY_BROKER_URL', None): CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_QUEUES = [ Queue(CELERY_TASK_DEFAULT_QUEUE) ] CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 60, 'polling_interval': 60, 'region': os.environ.get('AWS_DEFAULT_REGION', None) } When the task is created, it creates a new queue in SQS with celery instead of using tb-account-task-queue task as defined as the default queue. -
How to maintain Django celery progress for a queue having multiple workers
I have 2-3 tasks which run with 2 workers and as each record is processed i increment the counter and convert it into a percentage and store it in redis against a process_id, which was generated for the queue, but the issue is sometimes worker 2 will complete faster than worker 1 even-though worker 1 was issued the task first and this causes the percentage to drop which will ultimately prevent the final value from not reaching 100%, is there any solution to this? -
Why is the Django form not rendering in a class-based view?
Background: I've been working on the 'mini blog' challenge in Mozilla's tutorial. Got 'author' (user), 'post' working. Added 'comment'. With bits of code from this (among others), I managed to use a function-based view to get 'CommentForm' work on the 'post-detail' page. But trying to convert the function-based view to a class-based view stumped me. Because the various errors I encountered all relate to some key fundamental concepts, like explicit/implicit 'request', passing 'context', I've been working at it, hoping to understand Django better. But I'm getting nowhere. The problem is the form, 'CommentForm', doesn't render in the template. At one point, it rendered, but 'submit' the form led to not allowed error. I figured it related to 'GET' vs 'POST'. At this point, I'm not sure where the issue is--views? template? Appreciate some pointers. Here's my code: models.py class Post(models.Model): post = models.TextField(max_length=1000) post_title = models.CharField(max_length=100) description = models.TextField(max_length=500) post_created_at = models.DateTimeField(auto_now_add=True) post_updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) @property def num_comments(self): return Comment.objects.filter(post_connected=self).count() def __str__(self): return f'{self.author or ""} – {self.post_title[:40]}' def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) def get_absolute_url(self): return "/blog/{}/".format(self.pk) class Meta: ordering = ['-post_created_at'] class Comment(models.Model): comment_title = models.CharField(max_length=100) comment = models.TextField(max_length=1000) comment_created_at = models.DateTimeField(auto_now_add=True) comment_updated_at = … -
Django: How to fill several empty cells in a table
I'm currently just learning Django and I'm doing electronic grade book. I have tried lots of things, but nothing helped. I need the teacher to see the table with the current tasks, given to a certain class. Two of the columns of this table, relevant to my problem, are the following: "tasks" and "marks", each mark is related to a certain task. Thus, I have the One-to-many relation between classes Mark and Task (models/views/urls attached by the link): https://www.codepile.net/pile/anxGqm7W In my template I have written forloop, so that each mark corresponds to a certain task: https://www.codepile.net/pile/KRBbvmRG Now in my column "Marks" I see all marks, related to their tasks. However, not all tasks are rated. So some cells of "Marks" column are empty (" " when I look at the code of the page in my browser). I need to somehow fill them with the "Add mark" link to the admin page, so that the teacher could add mark. So I need to have some cells in this colums, filled with marks (already done and working) and some should not be empty, but should have links to redirect to another page. Here comes the problem. I cannot find any solution … -
No cookies being stored when hosting Django Site on AWS EC2
I'm trying to host my django site on an AWS EC2 instance using apache. I'm currently using http only and accessing via the EC2's IP address, but eventually plan to enable ssl with a custom domain. I've managed to get the site up and running using the apache conf file below, but when I access it, my browser does not seem to be storing any cookies, which is interfering with the site's functioning. I am also unable to authenticate users. I have previously hosted on Heroku without encountering these errors. I don't believe this is apache related, because I also see the same issue when disabling apache, running 'python manage.py runserver 0.0.0.0:8000' and accessing the site with {{ip address}}:8000. Apache conf file <VirtualHost *:80> ServerAdmin email@email.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django-app/django-app/staticfiles <Directory /home/ubuntu/django-app/django-app/staticfiles> Require all granted </Directory> <Directory /home/ubuntu/django-app/django-app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIPassAuthorization On WSGIDaemonProcess django_site python-home=/home/ubuntu/django-app/venv python-path=/home/ubuntu/django-app/django-app WSGIProcessGroup django_site WSGIScriptAlias / /home/ubuntu/django-app/django-app/django_app/wsgi.py </VirtualHost> settings.py This file is lengthy, so I'll just post a summary of some of the values I've set that I believe are relevant based on prior research. ALLOWED_HOSTS = ['{{EC2 IP Address}}'] SESSION_COOKIE_AGE = 604799 SESSION_COOKIES_SECURY = … -
How to view data in django from react front-end
I want to be able to view data that comes from my react front-end and want to use the print function to display the results in python @api_view(["POST"]) def testfunc(request): return JsonResponse(request,safe=False) thanks in advances -
Django Rest Framework Help figuring out bottleneck for response times. I've tried multiple things with no success
I am having 4-5 second response times with 1000 blog posts in the PostgreSQL database. I've used cProfile as shown here by my guy Haki Benita and my serializers are serializing 1000 objects in the 0.003 second zone. I have a lot going on like pagination and to_representation as you will see so I was hoping someone can help me see something that I am not. My question is, how do I improve my response times while still returning all the different data points that I've defined? Please have a look and be gentle please :) models: import uuid from datetime import timedelta from django.conf import settings from django.db.models import Manager, Model, DateTimeField, TextField, CharField, EmailField, IntegerField, \ BooleanField, ForeignKey, ManyToManyField, OneToOneField, SlugField, CASCADE, SET_NULL from django.core.exceptions import ValidationError from django.utils import timezone from django.template.defaultfilters import slugify from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex from django.contrib.auth import get_user_model User = get_user_model() from blog_api.users.model_validators import validate_min_3_characters, validate_no_special_chars from blog_api.posts.validators import validate_min_8_words from blog_api.posts.managers import PostManager, TagManager class BaseModel(Model): '''Base model to subclass.''' created_at = DateTimeField(editable=False, null=True) updated_at = DateTimeField(editable=False, null=True) class Meta: abstract = True def save(self, *args, **kwargs): if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() return super(BaseModel, … -
Doesn't Django's "request" only work when explicitly called?
That was my assumption. But there are examples like this one where: class PostDetailView(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.object is None: return HttpResponseRedirect(reverse('blog')) count_visits = None unique_views = set() if self.request.user.is_authenticated: post_views = PostView.objects.filter(post=self.object) count_visits = post_views.count() for post_view in post_views: unique_views.add(post_view.ip) I tried to make use of the above code, but I got an error name 'request' is not defined. My code (below) is messed up, but I'd like to understand how I can make an explicit request so that a form on a class-based view can work (that's for another post): class PostDetailView(generic.DetailView): model = Post context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.object is None: return HttpResponseRedirect(reverse('/')) if self.request.user.is_authenticated: comment_form = CommentForm(request.POST) comment_form.save() -
how to fetch ad logged in user from django web app service?
I have a django web app hosted on azure. I don't see X-MS-CLIENT-PRINCIPAL-NAME and X-MS-CLIENT-PRINCIPAL-ID in the headers for fetching logged in user. How to fetch mysite/.auth/me response? I am getting "you do not have permission to view this directory or page" from views.py. -
How to use multiple infinite-scroll in a page in django
I have recently done Infinite Scroll With Django pagination & using Waypoints on a card on HTML, On the same page I have another card & I want to implement the same on the 2nd card , The elements of the second card are coming on click of an element of 1st card , example click on 1st element of card1 , list of related elements on card2 to appears.But the infinite scroll on card2 is not working , it is working on card1 only.here is my code html <div class="card-body infinite-container" data-height="500"> <ul class="list-group" id="pid"> {% for each in products %} <li class="list-group-item p-2 list-group-item-action pointer clickbottom infinite-item"> <div class="row" id="{{element.id}}"> <div class="col col-lg-8 col-md-8 col-sm-8"><span style="color:orange" class="classTitle" id="{{each.id}}">{{each.name}}</span></div> </div> </li> {% endfor %} </ul> </div> {% if products.has_next %} <a class="infinite-more-link" href="?page={{ products.next_page_number }}"></a> # Here it is working {% endif %} <div class="card-body infinite-container" data-height="400"> <ul class="list-group" id="pid"> {% for each in quality %} <li class="list-group-item p-2 list-group-item-action pointer clickbottom infinite-item"> <div class="row" id="{{each.id}}"> <div class="col col-lg-8 col-md-8 col-sm-8"><span style="color:orange" class="classTitle" id="{{each.id}}">{{each.name}}</span></div> </div> </li> {% endfor %} </ul> </div> {% if quality.has_next %} <a class="infinite-more-link" href="?page={{ quality.next_page_number }}"></a> # Here Not working <script> var infinite = new … -
jquery button click not working , using django templates for rendering
I have multiple buttons on the same page with same id so basically rendering in a for loop with same id . I set a click event handler in jquery but it fires for only the first button. Can you suggest? -
Django Heroku - Site matching query does not exist
First of all, i have read a lot of posts with similar object, but no one brought me the solution, so i wanna try to ask the question my self. I have a Django application that is hosted using heroku with no problems. My problem is when i try to access the admin page or sign in using google then i get the following error 'Exception Value: Site matching query does not exist' And this error only shows when i am trying on the deployed / live version of my application. When i am on the local version i have no problems when accessing admin page or google login. Here is my code in settings: from pathlib import Path import os import django_heroku from django.utils.translation import gettext_lazy as _ # 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/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o!=!fb90hv@&d)55p&ru4%hoyz6s(5y8zv0u+mi+^rvfdontg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] DEFAULT_AUTO_FIELD='django.db.models.AutoField' # Application definition INSTALLED_APPS = [ 'django_countries', 'bootstrap_modal_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'django.contrib.sites', 'social_django', … -
Javascript multiple countdown timers on the same page using dates from django models
this is my first ever post so please let me know if I need to clarify anything thanks. I don't have any Javascript experience and I'm trying to write a countdown timer that runs through a django model's data and displays a countdown timer based on each individual object date in my database. My django models work correctly and loops correctly etc. I place the below script within my django models for loop but the script only pulls the first objects target date and then populates the countdown timer(correctly) for my first django model object's targetdate but it uses the date of only this first model. My guess is that I need to put the targetdate (the folowing piece of code) : let targetdate = new Date({{ datemodel.dateinmodel|date:"U" }} * 1000); also in some sort of for loop within javascript itself. I've tried to do this but I really still struggle a lot with javascript at the moment so I don't have any idea. Do I need to put the target date also in some sort of loop within my javascript script to be able to make it loop through the rest of the object dates in my django model? … -
How can I fix it when I've messed up the path of an import?
I have a directory that looks like this: I am working in a urls.py file with the path mysite/mysite/urls.py, and I want to import the views.py file from the 'register' folder (with the path /mysite/register/views.py). I tried importing it with this line: from register import views as v But I get an error saying that there's no module like that because Python is importing from a register.py file instead of a register-folder. I have tried fixing it by giving the direct path to the right folder, like they showed in this solution, with # some_file.py import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '/path/to/application/app/folder') import file But I still import the .py-file instead of from the folder. I have tried changing the default path of the whole project, but that only caused more errors. I have had this problem before, because I name classes and functions the same as some built-in function I didn't know about, but this time I cant seem to figure it out. How can I fix this? -
SQLite, Django, in operator and django.db.utils.OperationalError: database is locked
I am using Django w/ SQLite and in my queries I use the whatever__in=whatever_list i.e. in operator. I am getting the django.db.utils.OperationalError: database is locked error and from what I read, decreasing concurrency is a possible solution to the error. My question is: replacing the in operator by a for loop, retrieving objects one by one does decrease concurrency or not? In other words, does in operator introduce/involve concurrency or is it syntactic sugar of a for loop? Thanks. -
consommation api créé en Symfony
bonjour a tous , j'ai crée une application web (Symfony) et je souhaite obtenir les informations de l'utilisateur sur mon appli mobile(flutter) , Jai crée l 'api en Symfony via api platform, après conversion de l'api en Dart( json To Dart) quand je fais Get aucun résultat mais quand je remplace mon lien api par un autre lien d' api en ligne pour tester tous passe sans problème , s'il vous plais Jai besoin de votre aide.