Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get foreign key attribute (or many to many attribute) of a model instance in Django in asynchronous queries?
In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In my case, I want to get university and courses of the model Student. models.py: from django.db import models class University(models.Model): name = models.CharField(max_length=64) class Course(models.Model): name = models.CharField(max_length=64) class Student(models.Model): name = models.CharField(max_length=64) university = models.ForeignKey(to=University, on_delete=models.CASCADE) courses = models.ManyToManyField(to=Course) when I use this code (in django 4.1): async for student in Student.objects.all(): print(student.university) print(student.courses) I get the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How can I fix this error? -
Will Django model instance always be populated when calling save()?
I have a model where I am overriding the save() function to add SearchVector's. I need to preprocess one of the instance's fields so I am overriding the save function: class Student(models.Model): first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") search_vector = SearchVectorField(null=True) def save(self, *args, **kwargs): sv = SearchVector(Value(self.first_name)) + SearchVector(Value(self.last_name)) if len(self.last_name) > 3: sv += SearchVector(Value(self.last_name[0:3])) self.search_vector = sv super().save(*args, **kwargs) Can I expect that all fields (first_name & last_name) of the instance are always populated inside the save() function? I noticed that the instance loading function from_db seems to suggest that model instances can be created with a partial set of fields. Does this mean that first_name could be None on the save() call? -
How to make an ajax function to execute only in in a certain case?
I have an ajax function that updates every second some value on page, I want to update it only when the script is working, because to not request a value that is the same. The script is updating this value, and ajax is refreshing it on website, but when script is not working, my ajax is requesting the value. How to make it work only when the script is working? var interval = 1000; function update() { $.ajax({ type: 'GET', url: 'http://localhost:8000/api/updating', headers : {'Authorization': "Token "+ token,}, data: $(this).serialize(), dataType: 'json', success: function (data) { $('#points_a').html(data)// first set the value }, complete: function (data) { // Schedule the next setTimeout(update, interval); } }); } setTimeout(update, interval); This is script in python view, Django: def task(userid, seconds_for_thirtydays=0): if(seconds_for_thirtydays < 2592000): p_a = Wallet.objects.filter(name__id=userid).values("points").first()['points'] add = p_a + 1 result = Wallet.objects.filter(name__id=userid).update(points=add) seconds_for_thirtydays = seconds_for_thirtydays + 1 time.sleep(1) task(userid) else: return The thing that I want to make is: When the value is not changing(the script is not working), then this ajax won't work and won't make requests, is it possible? -
Django/Wagtail Media Files not showing up in the admin portal on a fresh install
I am working on a site in dev that contains a media folder. When I do a fresh setup of the site (empty db) and do all the migrations and steps to get the site up and running I noticed in the admin portal none of the images and assets in the media folder dont show up even though they exist. I have to re-import an image and then it shows up in the admin portal as expected. I have looked all over and cannot find an answer. To put it simply why isnt the admin portal importing existing files in the media folder on a fresh setup? django==3.2 wagtail==3.0 base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' urls.py from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from wagtail.contrib.sitemaps.views import sitemap from search import views as search_views urlpatterns = [ ... ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If anyone has any idea? -
JS static files not working for Django Project
I am following this online countdown-tutorial https://www.youtube.com/watch?v=ZpujnQqcvAA to implement into my website. I feel I am missing something simple. base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- custom js--> {% block scripts %} {% endblock scripts %} <title>countdown to events</title> </head> <body> <div class="container mt-3"> {% block content %} {% endblock content %} </div> </body> </html> main.html {% extends 'base.html' %} {% block content %} {% for obj in object_list %} <div> <a href={{obj.get_absolute_url}}>{{obj.name}}</a> </div> {% endfor %} {% endblock %} countdown.html {% extends 'base.html' %} {% load static %} {% block scripts %} <script scr={% static 'main.js' %} defer></script> {% endblock scripts %} {% block content %} <div class ="row"> <div class = "col-5"> <div>{{object.names}} will take place:</div> </div> <div class = "col-7"> <div id="event-box">{{object.when|date:"M d, Y H:m:s"}}</div> </div> </div> <div>Time left:</div> <div id ="count-down-box" class="text-center mt-3 h1"> <div class ="spinner-border" role = "status"></div> </div> {% endblock content %} main.js console.log('hello world') const eventBox = document.getElementById('event-box') const countdownBox = … -
How can I reduce the marker making time of Mapbox js
I don't understand why this page takes minutes to render, it takes so long that I get a gunicorn timeout... Anyway I could fix it ? I try to generate a marker for every address passed with django, the current address list has around 300 addresses Each marker also has a popup do display informations about the user or the event associated with it // Create a marker for each address {% for address in addresses %} {% if address.user.count|add:address.time_filtered_events.count >= 2 %} var el=document.createElement("div"); el.className="marker"; el.style.backgroundImage = `url(https://ssb.wiki.gallery/images/3/30/SandbagHeadSSBM.png)`; el.style.width = `20px`; el.style.height = `20px`; el.style.backgroundSize = '100%'; new mapboxgl.Marker(el) .setPopup(new mapboxgl.Popup().setHTML(...) .setLngLat([{{address.longitude}}, {{address.latitude}}]) .addTo(map); {% else %} {% for user in address.user.all %} var el=document.createElement("div"); el.className="marker"; el.style.backgroundImage = `url({{user.main.image}})`; el.style.width = `20px`; el.style.height = `20px`; el.style.backgroundSize = '100%'; // Add markers to the map. new mapboxgl.Marker(el) .setPopup(new mapboxgl.Popup().setHTML(...) .setLngLat([{{address.longitude}}, {{address.latitude}}]) .addTo(map); {% endfor %} {% for event in address.time_filtered_events %} var el=document.createElement("div"); el.className="marker"; {% if event in address.current_events %} el.style.backgroundImage = `url(https://i.ibb.co/bX2yVm5/green-smash-ball.png)`; {% else %} el.style.backgroundImage = `url(https://ssb.wiki.gallery/images/7/7a/FightingWireFramesHeadSSBM.png)`; {% endif %} el.style.width = `15px`; el.style.height = `15px`; el.style.backgroundSize = '100%'; {% endfor %} {% for event in address.time_filtered_events %} var el=document.createElement("div"); el.className="marker"; {% if event in address.current_events %} el.style.backgroundImage … -
Python Authlib: ResourceProtecter decorator for class based views
I am trying to secure a Django-DRF based API using Auth0. The Authlib resource protector works fine using a function-based views however when I try to apply the ResourceProtector decorator from Authlib to a class-based view it keeps returning an error 'ViewSet' object has no attribute 'build_absolute_uri'. It appears the decorator function is using the self argument instead of the request argument to get the url when it is applied to a class-based view causing the error. Is there any other way to use Authlib resource protector decorator to a class-based view? Views.py from api.permissions import auth0_validator from authlib.integrations.django_oauth2 import ResourceProtector from django.http import JsonResponse require_oauth = ResourceProtector() validator = auth0_validator.Auth0JWTBearerTokenValidator( os.environ['AUTH0_DOMAIN'], os.environ['AUTH0_IDENTIFIER'] ) require_oauth.register_token_validator(validator) #Resource protector decorator works here @require_oauth() def index(request): return Response('Access granted') class Users(ModelViewSet): #Resource protector decorator does not work and invokes error below @require_oauth() def list(self, request): return Response('access granted') stack trace Internal Server Error: /v2/statistics Traceback (most recent call last): File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line 68, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in … -
How to automatically delete a Django Many-to-Many model entity once it no longer has any relations?
I have two models, Record and Tag. They have a Many-to-Many relationship. Tags also has a Many-to-Many relationship with a third model, Set. I'm using Django Rest Framework and the model serializer for Tag looks like this: class TagSerializer(serializers.ModelSerializer): usage_count = serializers.IntegerField( source="record_set.count", read_only=True) class Meta: model = Tag fields = ("name", "usage_count") What I want to achieve now is that once usage_count is 0, i.e. a Tag is no longer related to any Record, it is automatically deleted. The only reliable approach I could come up with is a cronjob that checks for Tags with such criteria and deletes them, as neither casecades nor any sort of delete "hooks" seem to do the trick. Is there a way to achieve this with an approach that is more elegant than a cronjob? -
How to use profile fields in comment form?
I to make my comment form login required and for that i had to use the fields in another models.py how can i use fields without foreignkey? models.py in blog app: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments', blank=True, null=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) class Meta: ordering = ('created',) def __str__(self): return f'نظر توسط {self.user} در {self.post}' models.py in account app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعهدهنده'), ('designer', 'طراح پروژه'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True) def __str__(self): return f'profile for user {self.user.username}' i want to use user full name and picture in comment template and with foreignkey I could not template: <div id="post_comments"> <h4>نظرات</h4> <div class="comment"> {% for comment in comments %} <div class="row"> <figure class="col-sm-2 col-md-2"> <img width="90" height="90" class="img-circle" src="{{ comment.user.photo }}" alt="عکس کاربر"> </figure> <div class="col-sm-10 col-md-10"> <div class="comment_name">{{ comment.user.user.get_full_name }}<a class="reply" href="#">&nbsp;</a> </div> <div class="comment_date"><i class="fa-time"></i>{{ comment.created }}</div> <div class="the_comment"> <p>{{ comment.body|linebreaks }}</p> </div> </div> </div> {% empty %} <h4>هیچ نظری وجود ندارد</h4> {% endfor %} </div> </div> is there any … -
How to reduce post method with two forms and two submit button?
I have two forms and two submbit buttons. Because I have a form submit for pdf and I have a submit for excel. So I distinguish in the views.py the forms like this: def post(self, request): filter_text = FilterText() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' content_excel= '' if request.POST.get('form_pdf') is not None: if submitted_form.is_valid() and request.POST: uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) if request.POST.get('form_excel') is not None: if submitted_form.is_valid() and request.POST: uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content_excel = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content_excel = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content_excel": content_excel }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) But as you can see this are almost identical code. Question: how can I reduce this? -
Assistance needed Django Rest Framework Serializer
I am new to the Django Rest Framework. I am attempting to get the navSidebarMaps object to serialize as follows: [ "navSidebarName": "mainSidebar", [ { "id": 1, "name": "item1", "order": 1, }, { "id": 2, "name": "item2", "order": 2, } ] ] What is the recommended approach for pulling the list of navSidebarItems through to the navSidebarMaps? The related_name argument seems to get me part way to the goal. However, I've missed something. Models: class navSidebars(models.Model): name = models.CharField(max_length=50, blank=False, null=False) description = models.CharField(max_length=150, blank=False, null=False) class navSidebarItems(models.Model): name = models.CharField(max_length=50, blank=False, null=False) description = models.CharField(max_length=150, blank=False, null=False) class navSidebarMaps(models.Model): fk_navsidebar = models.ForeignKey('core.navSidebars', related_name='sidebars', on_delete=models.CASCADE) fk_navsidebar_items = models.ForeignKey('core.navSidebarItems', related_name='sidebar_items', on_delete=models.CASCADE) order = models.IntegerField(default=0, blank=False, null=False) Serializers: class navSidebarSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebars fields = [ 'id', 'name', 'description', 'active', 'visible', 'enabled', 'can_delete', 'fk_navsidebar', 'created_by', 'created_when', 'modified_by', 'modified_when' ] class navSidebarItemsSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebarItems fields = [ 'id', 'name', 'description', 'position', 'active', 'visible', 'enabled', 'can_delete', 'created_by', 'created_when', 'modified_by', 'modified_when' ] class navSidebarMapsSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebarMaps fields = [ 'id', 'fk_navsidebar', 'fk_navsidebar_items', 'created_by', 'created_when', 'modified_by', 'modified_when' ] -
Django test to use Postgres extension without migration
I have an existing project that I want to start implementing test step. There are quite a few data migrations happened in the history and I don't want to spend the effort to make them run in test setup. So I have disabled 'migrations': DATABASES['default']['TEST'] = { 'MIGRATE': False, } However this Postgres DB makes use of some extensions class Meta: verbose_name = 'PriceBook Cache' verbose_name_plural = 'PriceBook Caches' indexes = [ GinIndex( name="pricebookcache_gin_trgm_idx", fields=['itemid', 'itemdescription', 'manufacturerpartnumber', 'vendor_id'], opclasses=['gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops'] ), ] Which resulted error when I run the test psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" I have had a look at here https://docs.djangoproject.com/en/4.1/ref/databases/#migration-operation-for-adding-extensions which specifically said done via migration but which I have disabled. An alternative is using template db but I don't really want to as this will be run automatically in gitlab using docker container and I don't want to maintain another fixture outside the project repo. So is there a way to initialise the database without running the migrations or is it possible to make it run completely different migration just for the test? -
The view main.views.view didn't return an HttpResponse object. It returned None instead
I have two forms on the same template. And that is why I check if one form has the name form_pdf: def post(self, request): extract_instance = ExtractingTextFromFile() filter_text = FilterText() extract_excel_instance = ExtractingTextFromExcel() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' if 'form_pdf' in request.method == 'POST': if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) and template: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning"> Upload! </button> </div> </form> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_excel" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning"> Upload! </button> </div> </form> But if I run this I get this error: The view main.views.view didn't return an HttpResponse object. It returned None instead. But I googled that error of course. And the suggestion is that you have to return render. But I have that. So how to tackle this error? -
Why does my Django form data not appear in the database?
I try to develop a simple input form to save a deposit for a fishing vessel. The vessel and the net are tables in the database. There is no error when the form is submitted but there is nothing happening in the background. I use a PostgreSQL database with PgAdmin for insights.I am a little bit stuck since it's my first time working with Django. I tried adding the dep_id field into the form but it did not change anything. forms.py models.py views.py Maybe I have any kind of dependency wrong or is it a problem with a key? -
send file to django rest with ajax
In my project, I use ajax to send form data to back-end(django rest framework). but when I see the request.data, the image field is empty. but other fields are ok. js(img is file input): $.ajax({ method: 'POST', url: '/step5/send/', contentType: 'application/json', data: JSON.stringify({"date": date, "hour": time, "price": price, "document": img, "id": {{user.id}} }), success: function (res) { console.log(res); }, error: function (err) { console.log(err); } }); view: @api_view(["POST"]) def step5_get_pay(request): date = request.data.get("date") hour = request.data.get("hour") price = request.data.get("price") document = request.data.get('document') id_ = request.data.get("id") user = User.objects.get(id=id_) Step5.objects.create(date=date, hour=hour, price=price, document=document, user=user) data = { "data": request.data, } return Response(data=data, status=200) and data: {date: '1401-11-14', hour: '10:10:10', price: '500', document: {…}, id: 1} Document is in request.data but I think It's must in request.FILES and in model that's save {} (empty) enter image description here enter image description here send a form with file input with ajax and django rest -
Django Set User as current user via admin
I need to set the 'project_created_by' value to the user who adds a new record to the Project model via the default django admin panel. Currently it shows up as a dropdown of all users. class Project(models.Model): project_name = models.CharField(max_length=25, unique=True, default="", blank=False) project_created_by = models.ForeignKey(User, unique=False, on_delete= models.CASCADE, blank=False) What is the simplest way to do this? -
How to clear a specific field upon changing the date in django?
I'm working on a website that has to do with user entering data to fields of a table. There is (input type=date) in top of the page. I want the user to enter values daily. but I want to save that data in the database according to that day and if the user change the date, I want to clear some fields for that day for a new fresh entry. I also don't know if there should be a datefield in model or not?? If so, would I have to populate the database with lots of dates? and if it reach the last date, I have to populate it again and so on?? How I go about doing this? I tried looking for a solution but couldn't find one that seems good. I found I could use crontab in django or scheduler but I don't think this is the optimum solution. -
Why is use-effect not working on React/django?
Hey guys! I am building a ToDo list web application with Django/React and now got into a minor problem I cannot seem to figure out. The problem is the note I am setting on my main page is not showing up when I click that current todo task. The terminal reads something like this "React Hook useEffect has a missing dependency: 'getNote'. Either include it or remove the dependency array." Can anyone pinpoint the error for me and tell me why its not working! Am I failing to see something? import React, {useState, useEffect} from 'react' import { useParams } from "react-router-dom" const NotePage = ({ history }) => { let [note, setNote] = useState(null) let { id } = useParams() useEffect(() => { getNote() }, [id]) let getNote = async () => { let response = await fetch(`/api/notes/${id}/`) let data = await response.json() setNote(data) } return ( <div className="note"> <textarea defaultValue={note?.id}></textarea> </div> ) } I recently upgraded from React v5 to v6 and learning how to use the new module. But this is a bit confusing. I did use it before and it worked perfectly but now for the application, it is throwing a error. -
Deploying Django Channels application to Heroku and setting Redis up
I've built a simple chat application in Django using Channels and Redis. Now I'm trying to deploy it to Heroku and I'm looking for some guidance on how to set up the Channel Layers using Redis. I've already deployed the application and tested it in the browser. I've managed to resolve my errors, and now the application is fully functional except for the messaging because I haven't set up a Redis server yet. I use Daphne as a web server if this provides any valuable information. I'm looking for an overview of all the steps I have to make to set up the Redis server, and how to configure the Channel Layers to work with it. I'd greatly appreciate any help on this, thank you in advance. -
Django has installed my system but not displayed version type
I have use Ubuntu 20.04.5 LTS. when i install django this commend "pip install django" that's installed properly but when i check django version this commend"python -m django --version" there displayed this "/usr/bin/python: No module named django" . django install but i have not run it my system -
ValueError: while trying to use the crispy forms
I am trying to make use of the crispy forms to display the form for inserting the data. I have a model as: class Athlete(models.Model): athlete_name=models.CharField(max_length=50) GENDER_CHOICES=( ('M','Male'), ('F','Female'), ('O','Others') ) gender=models.CharField(choices=GENDER_CHOICES,max_length=100) age=models.IntegerField() athlete_category=models.ForeignKey(Category,on_delete=models.CASCADE) image=models.FileField(upload_to='static/athlete_img', null=True) COUNTRY_CHOICES=( ('np','nepal'), ('in','india'), ('uk','united kingdom'), ('sp','spain'), ('ch','china') ) medals=models.IntegerField country=models.CharField(choices=COUNTRY_CHOICES,max_length=100) def __str__(self): return self.athlete_name In the forms.py...I have modelform as: class AthleteForm(ModelForm): class Meta: model:Athlete fields='__all__' In my views.py I have the following function: def add_athlete(request): if request.method == 'POST': form = AthleteForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Athlete added sucessfully') return redirect('/admin/athletes') else: messages.add_message(request, messages.ERROR, 'Enter the appropriate values') return render(request, 'forgame/addathletes.html', { 'form': form }) context = { 'form': AthleteForm } return render(request, 'forgame/addathletes.html', context) Inside my templates/forgame I have created addathletes.html {% extends 'layouts.html' %} {% load crispy_forms_tags %} {% block title %} <title>Game Category</title> {%endblock%} {% block main_content %} <div class="container-fluid mt-4"> <div class="d-flex justify-content-center"> <div class="col-md-6"> <h2>Add Categories Here!</h2> {% for msg in messages %} {% if msg.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %} <div class="alert alert-success"> {{msg}} </div> {%endif%} {% if msg.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <div class="alert alert-danger"> {{msg}} </div> {%endif%} {%endfor%} <form action="" method="post" class="shadow-lg p-3"> {%csrf_token%} {{form | crispy}} <div class="mt-3"> <input type="submit" value="Add Category" class="btn btn-primary"> </div> … -
Unclosed tag on line 6: 'with'. Looking for one of: endwith
I'm learning how to use Django Templates but im getting this error Unclosed tag on line 6: 'with'. Looking for one of: endwith. this is my html code <!DOCTYPE html> <html> <body> <h1>Favorite rapper:</h1> {% with person="2pac" %} <h1>{{person}}</h1> </body> </html> this is the tutorial that I'm doing -
Animated pictures in JavaScript, problem: flickering screen and resizing
As I mentioned in the title I have a problem properly embedding my animation in my Django project. At some point, I decided to update the logo used by my web page built-in Django. Having small experience with JavaScript I was looking for approaches that fit my needs. I built an animation engine having some inspiration from this StackOverflow answer. (Thanks to user gilly3). My approach is, though, different in this topic because I realised that if I would have a lot of pictures then sticking/concatenating them together in one file might be difficult. I've decided to use another approach and use a bunch of files instead of one. For that sake, I built a function with a generator which I could call in another function to display all pictures in order. This animation engine looks like this: function* indexGenerator() { let index = 1; while (index < 28) { yield index++; } if (index = 28) yield* indexGenerator(); }; var number = indexGenerator(); setInterval(function animationslider() { var file = "<img src=\"../../../static/my_project/logos/media/slides_banner_f/slide_" + number.next().value + ".jpg\" />"; document.getElementById("animation-slider").innerHTML = file; $("#animation-slider").fadeIn(1000); }, 100); $("#animation-slider").fadeIn(1000); doesn't do the trick with values from 10-1000. I record what this looks like: https://youtu.be/RVBtLbBArh0 I … -
Protecting Rest API Routes against expired token using Django Rest Framework and JWT Authentication
I am pretty new to Django Rest Framework and I have created JWT Authentication. I have set the access token expiry time to 4 seconds. After when the token expires, I am still able to access the API route. It is not restricting me, nor it is throwing any error such as 401 unauthorized. Please someone help if you can. This is my SimpleJwt settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=4), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(seconds=4), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=90), } This is my route which I am protecting against expired tokens: @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_notes(request): user = request.user notes = user.notes_set.all() serializer = NoteSerializer(notes,many=True) return Response(serializer.data) -
Can I iterate my context at view to put into my template?
I've created this function at my views to iterate through my pages. for chapter in chapters: context["chapter_page"] = math.ceil((changelogs.index(changelog) + 1) / 2) context["chapter"] = chapters return context I am still making a for a loop in my template, so I cannot remove him. I added this context, but the only returned page is the last page, which means, that my context["chapter_page"] is not iterating. {% for chapter in chapters %} <li> <a href="?page={{ chapter_page }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} Of course, I could not add this logic direct to my template, it is not accepted by Django. {% for chapter in chapters %} <li> <a href="?page={{ math.ceil((chapters.index(chapter) + 1) / 2) }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} I am expecting to do a loop and return each iterated number at my href=page