Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django checkbox do not return nothing
I mading a project and i need to get checkbox values in sequence, but django do not return anything when that checkbox are unchecked. how can i do that return False instead of nothing? forms.py class myFormExemple(forms.Form): checkbox = forms.BooleanField(required=False) views.py def MyViewExemple(request): if request.method == 'POST': print(request.POST.getlist('checkbox')) context = { 'form': myFormExemple } return render(request, "cadastro/myHTMLTemplate.html", context) and myHTMLTemplate.html: <form method="post" id='form'> {% csrf_token %} {{form.checkbox}} <button type="submit">save</button> </form> -
About django operation templates display screen
About django operation templates display screen I use django to write duplicate content into the base_generic.html page (including navbar sidebar footer), but because base_generic.html is one page and polls_list.html is another page content, I hope they can be combined, but My current situation is that the base_generic.html page covers the polls_list.html page, and the polls_list.html page disappears directly, unless it is hidden {% extends "base_generic.html" %} , My polls_list.html page will come out. Can someone help me answer this question? I don't know where I am not familiar, and I missed the process of learning. Please help, thank you. views.py def polls_list(request): context = { 'title': 'test index', 'user': request.user, } return render(request, 'polls/polls_list.html', context) polls_list.html {% extends "base_generic.html" %} {% block head %} <title>list profile</title> {% endblock %} {% block content %} <div class="container-fluid background-color: red;"> <div class="row"> <p>{{ user }}</p> </div> <div class="row"> <h1>Author List</h1> {% if author_list %} <ul> {% for author in author_list %} <li> <a href="{{ author.get_absolute_url }}"> {{ author }} ({{ author.date_of_birth }} - {% if author.date_of_death %}{{ author.date_of_death }}{% endif %}) </a> </li> {% endfor %} </ul> {% else %} <p>There are no authors available.</p> {% endif %} </div> {# /* row #} … -
Sending email to a specific user using Django
How can I send an email from the superuser to a specific user (which I want to select from a dropdown list) using Django? -
A part of Passed context not rendering in template django
A part of context doesn't render in my template. I have function based view as def index(request): context = { 'blogs': BlogPost.objects.all(), } context['likes'] = 1 return render(request, 'index.html', context) inside template.html {% for post in blogs %} {{post.id}} {# this renders perfectly #} {% endfor %} {{ likes }} {# this part doesn't render #} what could be the error? I am unable to figure it out. -
How to output multiple options during Django shopping mall implementation
I am a student who is learning Janggo. I'm asking you a question because I have a question while processing shopping mall options. The data for the ongoing project are as follows. Cardigan has two options, Size and Color, and I want to use Select in the template to import the Value of Size and Value of Color separately. I want to know if this is possible. For example, I would like to write: I wonder if it's possible, and if possible, I'd appreciate it if you could let me know how it can be implemented. -
Get schema and options in Django Rest Framework
In a particular API that is used to manage production data for the visual effects and animation industry, there is a call in the python API to get the available fields for an entity (a model basically). I am looking at trying to get the same things from my Rest API to dynamically add new or remove attributes to a react frontend with the correct field types. Does something like this already exist in DRF or will I need to create a custom view to get this data from the meta on the model? An example response may be something like... {model: { field1: { type: "charField", choices: ["A", "B", "C"], default: "A", required: True }, field2: { type: "boolField", default: True, required: False } } Thanks! The Example API I mentioned: https://developer.shotgridsoftware.com/python-api/reference.html#shotgun_api3.shotgun.Shotgun.schema_field_read -
Django - Finding Subtotal
I am trying to create a page that displays a users events and there total hours and mileage. I can get the tables to display for each user but I cannot figure out how to sum up the hours and mileage for each. I have the following Model. class VolunteerRecord(models.Model): eventname = models.CharField(max_length=50, blank=False, default='') category = models.CharField(max_length=100, blank=False) hours = models.FloatField(blank=False) date = models.DateField(help_text=_('Enter the date of the event')) mileage = models.FloatField(blank=False, null=True, default=0.0) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) The following queryset in views.py records = VolunteerRecord.objects.filter(date__range=(first_day,last_day)).order_by('owner_id__username', 'date') records_list = list(records.values('id','owner_id__username', 'category', 'eventname', 'date', 'hours', 'mileage')) and the following in my html template {% regroup records_list by owner_id__username as byMember %} {% for owner_id__username in byMember %} <div class="content"> <h1>{{ owner_id__username.grouper }}</h1> <table class="table" border="1" style="width: 100%;white-space:nowrap;"> <tr> <th style="text-align:left">Category</th> <th style="text-align:left">Event Name</th> <th style="text-align:left">Date</th> <th style="text-align:right">Hours</th> <th style="text-align:right">Mileage</th> </tr> {% for record in owner_id__username.list %} <tr> <td>{{ record.category }}</td> <td>{{ record.eventname }}</td> <td>{{ record.date }}</td> <td style="text-align:right">{{ record.hours }}</td> <td style="text-align:right">{{ record.mileage }}</td> </tr> {% endfor %} <tr> <td colspan="3">&nbsp;</td> <td id="total_hours">[WHERE TOTAL HOURS PER USER GOES]</td> <td id="total_mileage">[WHERE TOTAL MILEAGE PER USER GOES]</td> </tr> </table> </div> <p>&nbsp;</p> {% endfor %} I am trying to solve for … -
Django: How to render a list horizontally on the index route
I'm building a Django application and ran into a problem rendering a list of categories horizontally on the index route. Here is my code: models.py class Category(models.Model): class Meta: verbose_name_plural = 'categories' name = models.CharField(max_length=255) def __str__(self): return self.name views.py def categories(request): return render(request, 'test_app/index.html', { 'categories': Category.objects.order_by('name').all() }) def category(request, category_id): category = get_object_or_404(Category, pk=category_id) listings = Listing.objects.filter(category=category).order_by('-timestamp').all() return render(request, 'test_app/index.html', { 'title': category.name, 'listings': listings }) index.html {% extends "layout.html" %} {% block body %} <div class="container-fluid"> <div class="card-columns mx-auto col-10"> {% for listing in listings %} <div class="mx-auto card h-100 mb-3" style="max-width: 480px"> <a href="{% url 'listing' listing.id %}"> <img class="card-img-top" src="{{ listing.image.url }}" alt="{{ listing.title }}"> </a> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <class="card-text"><small class="text-muted">Posted in {{ listing.category }}</small> </div> </div> {% endfor %} </div> </div> {% endblock %} urls.py urlpatterns = [ path('', views.index, name='index'), path('categories', views.categories, name='categories'), path('categories/<int:category_id>', views.category, name='category'), path('listings/<int:listing_id>', views.listing, name='listing'), path('purchase/<int:listing_id>', views.purchase, name='purchase'), ] layout.html <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}My Site{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'categories' %}">Categories</a> </li> <ul> {% for category in categories %} <li> <a href="{% url 'category' … -
How Do I continue working on a deployed Django project without deleting the database data?
I have deployed my django application on heroku. My application on heroku runs a command that adds data to my mySQL database on AWS daily. Now I want to continue working on the django app, and I want to test new code, but that will create new data which I do not want to be stored on the live database, instead I would like to use SQLlite for production. How would I switch back to the MySQL database that has all the real data once I am ready to deploy the new version of my django app, without deleting all the data on the live database? I know I can save the data in the current database using these commands and load it into SQLlite from MySQl: python manage.py dumpdata > datadump.json python manage.py migrate --run-syncdb python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() python manage.py loaddata datadump.json But I'm not sure how I am meant to migrate back to the MySQL database without erasing the live MySQL Database's data when I redeploy. Any help would be much appreciated. -
why thumbnail are not displayed in img tag using the values() method in views?
I have a model with 10 fields. But in the template I just want to return four fields('slug', 'code', 'area', 'thumbnail') . To do this, I used the Values() in View. But the thumbnail is not displayed in img tag of template and the src of the photo is empty. views.py: def home(request): allVilla = Villa.objects.filter(status='p').values('slug', 'code', 'area', 'thumbnail')[:8] context = { 'allvilla': allVilla, 'allproduct': allproduct, } return render(request, "wooden/home.html", context) home.html (template): <div id="slider_villa_home" class="owl-carousel owl-theme box_slider_villa dir_left"> {% for v in allvilla %} <div class="item position-relative box_item wow flipInY"> <div class="position-absolute bg"></div> <img class="img_item" src="{{ v.thumbnail.url }}" alt="{{ v.code }}"> <p class="position-absolute p_item"> <b>{{ v.code }}</b> <br> <b>{{ v.area }}</b> </p> <a class="position-absolute link_item" href="{% url 'wooden:singlevilla' v.slug %}"> </a> </div> {% endfor %} </div> pls help -
DRF Serializer How do I place serialize my data and display
I have following Serializer I am facing problem with Json with serializing. I have user named daniel james and he have multiple subject like maths science I am providing nested serializer to fill all subject but based on subject users name also repeats below is more specific qsn class ListResultSerializer(ResultSerializer): user = serializers.CharField() semester = serializers.CharField() subject = serializers.SerializerMethodField() class Meta(ResultSerializer.Meta): fields = ( 'user', 'semester', 'subject', ) def get_subject(self, instance): return SubjectSerializer(instance).data And In my views.py I have done like this. class ListResultView(rest_generics.ListAPIView, UserMixin): serializer_class = serializers.ListResultSerializer permission_classes = (AllowAny,) def get_object(self): return self.get_user() def get_queryset(self): return usecases.ListResultUseCase( user=self.get_user() ).execute() I use usecases.py to filter the data here is further code class ListResultUseCase: def __init__(self, user: User): self._user = user def execute(self): self._factory() return self._result def _factory(self): self._result = Result.objects.filter(user=self._user) Now this is the Json I am getting right now from above code. [ { "user": "daniel james", "semester": "first", "subject": { "gpa": "a+", "subject": "maths" } }, { "user": "daniel james", "semester": "first", "subject": { "gpa": "A", "subject": "data structures" } } ] I want my json to be in this format [ { "user": "daniel james", "semester": "first", "subject": [ { "gpa": "a+", "subject": "maths" }, { …