Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aws lambda deployed by zappa is not able to connect to remote database
I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database. I'm tring to connect to the database using djongo. I set my django_setting in the zappa_settings.json to my project's django settings. The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST). The actual error I get is: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused The above exception was the direct cause of the following exception: djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT If anyone has an idea I'd would love to hear. attaching the settings with some fields unset (but set at my settings) DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db', 'HOST': 'mongodb://<username>:<password>@<> 'USER': 'username', 'PASSWORD': 'password', } } { "dev": { "aws_region": "eu-west-1", "django_settings": settings, "profile_name": "default", "project_name": name, "runtime": "python3.6", "s3_bucket": bucket, "timeout_seconds": 900, "manage_roles": false, "role_name": name, "role_arn": arn, "slim_handler": true } } -
ORM trouble with Django
I want two lists of books, 1 of books that has already been "liked" by the user aka 'myBooks', and another list of all other books, 'otherBooks'. Instead, I can only get 1 book on the first list (the first one liked) and after that the list doesn't change (it doesn't even disappear from second list which excludes any liked books). I am using the filter command which I know is for multiple, and my queries work fine in shell, and yet in my actual program I only get that single query. def books(request): if 'userid' not in request.session: return redirect('/') else: num = request.session['userid'] thisUser = User.objects.get(id=num) myfavorites = Favorite.objects.filter(user=thisUser) context = { "user" : thisUser, "otherBooks" : Book.objects.exclude(favorites=myfavorites), "myBooks" : Book.objects.filter(favorites=myfavorites) } return render (request, 'app1/books.html', context) -
Django DRF : how change to change Date format in my serializer.py?
I am new to Django DRF and I need a small tip. My Problem : I want to change the standart models.DateField to the following format "%d-%m-%Y". I want to do it for the field "birthday" or in general for the project. I tried in directlty in the model.py with : .... birthday = models.DateField(null=True , input_formats= "%d-%m-%Y" ) but it did not work . .... I also added in the setting.py REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"],} but it did not work. Now i want to try in the serializer.py but given my class I don't know where to do it . My serializer.py looks like that : from rest_framework import serializers from payload.models import Payload class PayloadSerializer(serializers.ModelSerializer): class Meta: model = Payload fields = ['first_name', 'last_name', 'email', 'birthday',] def create(self, validated_data): """ Create and return a new `payload` instance, given the validated data. """ return Payload.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `payload` instance, given the validated data. """ instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.birthday = validated_data.get('birthday',instance.birthday) instance.save() return instance SO the question : Where and how do I change in this class the the format of the … -
How to get the minimum value of an instance of django model
I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows class Hotels(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) mobile_number = models.CharField(max_length=12) created_at = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) description = models.TextField() slug = models.SlugField(unique=True) property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos') star_rating = models.PositiveIntegerField() contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,) class Room(models.Model): hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,) room_photo = models.ImageField(default='default.jpg', upload_to='room_photos') room_Name = models.CharField(max_length = 200) room_details = models.CharField(max_length = 500) room_Capacity = models.PositiveIntegerField(default = 0) slug = models.SlugField(unique=True) # guest_numbers = models.IntegerField(default=0) room_Price= models.PositiveIntegerField(default = 0) total_Rooms = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,) More details From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist -
Loading Django model data into HTML from specific model
When I click on a link on my homepage I want to go to a page with a dynamic URL. I managed this by changing my URLS.py to urls.py urlpatterns = [ path('', views.home, name='home'), path('<str:god_url>', views.godpage, name='godurl'), ] homepage.html <a class="button" href="{{ GodList.god_name }}">Watch now</a> This post is in a for loop, cycling trough godnames. So when clicking on the button above, the god name of that button is added to the url and a new page is loaded. views.py def godpage(request, god_url): godlink = GodList.objects.get(god_link=god_url) context = {'godlink': godlinklink} return render(request, 'my_app/god.html', context) models.py class GodList(models.Model): godName = models.CharField(max_length=50, unique=True) godFoto = models.CharField(max_length=100, unique=True) godlink = models.CharField(max_length=100, unique=True) def __str__(self): return self.godName In this new page I want to load a link which is in the database / models (using postgresql) This link can be found in the same model as the god name that was added to the url. How can I find this link inside of the models and get it in the HTML? <img src="{{ context }}"/></a> -
Django Celery task received, execute, but not finished with GlobalBestPSO pyswarms
I have Django app with Celery in Docker. Have Django container, Celery container. django==1.11.4 gunicorn==19.7.1 celery==4.4 redis==3.4.1 sqlalchemy==1.3.13 raven==6.1.0 requests==2.22.0 numpy==1.13.3 pandas==0.20.3 keras==1.2.1 theano==0.9 scikit-learn==0.18.1 matplotlib==2.1.1 seaborn==0.8.1 salib==1.1.2 pyswarms==1.1.0 deap==1.3.0 In my celery task I have code: from celery import shared_task from pyswarms.single.global_best import GlobalBestPSO @shared_task() def predict_task(): # Some code for i in range( print ('print 111') optimizer = GlobalBestPSO(n_particles=n_part, dimensions=sample_vals.shape[0], \ options=options, bounds=bounds, \ init_pos=positions) print ('print 222') cost, pos = optimizer.optimize(predict_seeded_func, iters=1000, **kwargs) costs.append(cost) poses.append(pos) # Some code Run task with delay function: predict_task.delay(19, test_id, sample_data.to_json()) Then I see, that [2020-03-16 22:26:11,689: INFO/MainProcess] Received task: app.tasks.predict_task[f207ac10-5eb5-464b-aed7-b3ec3d2d029d] [2020-03-16 22:26:11,750: WARNING/ForkPoolWorker-2] print 111 And after then nothing happens. But, if I run without celery delay(): predict_task(19, test_id, sample_data.to_json()) Then code is successfully executed to the end. And I get the result. What can be wrong? Why GlobalBestPSO not executed in task? -
How to correctly localize fields in forms?
I use Django 3.0.4 and Crispy Forms 1.9.0 I have the following model: class App(models.Model): name = models.CharField(max_length=256, db_index=True, verbose_name=_('Name')) platform = models.ForeignKey(Platform, on_delete=models.CASCADE, verbose_name=_('Platform')) package_name = models.CharField(max_length=512, unique=True, verbose_name=_('Package name')) created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name=_('Created Date')) Form: class CreateAppForm(forms.ModelForm): class Meta: model = App fields = ('name', 'platform', 'package_name',) localized_fields = '__all__' # I've tried to enumerate fields as tuple # labels = { # I've tried to uncomment it # 'name': _('Name'), # 'platform': _('Platform'), # 'package_name': _('Package name'), # } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['platform'].queryset = Platform.objects.filter(is_enabled=True) And template: {% extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block title %}{% trans "Create application" %}{% endblock %} {% block page_title %}{% trans "Create application" %}{% endblock %} {% block content %} <div class="row"> <div class="col"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{% trans "Create application" %}</h6> </div> <div class="card-body"> <form class="form" action="{% url 'apps:create' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success btn-lg" type="submit"><i class="fa fa-check"></i> {% trans "Create" %}</button> </form> </div> </div> </div> </div> {% endblock %} All strings in .po files are localized and compiled (and work everywhere but in forms). The … -
How do you effectively cache a large django queryset?
I am working on a Django project using a PostgreSQL database in which I need to run a sometimes complex query on a user profile table with ~1M records, and the dataset returned can be anywhere from 0 to all 1M records. My issue is that once I grab all of the records, I want to be able to filter them further to run analytics on these profiles. The analytics cannot be completed in the same request/response loop, as this will time out for all but the smallest querysets. So I am using async javascript to shoot off new requests for each type of analytics I want. For example, I will grab all of the profiles in the initial request and then i will send subsequent requests to take those profiles and return to me the % of genders or % of users who have a certain job title, etc. The issue is that every subsequent request has to run the original query again. What I would love to do is somehow cache that query and then run my query on this subset of the profile table without having to execute the original, long-running query. I have tried to use … -
what is the difference this two pieces of code
I tried replacing this cood in Django Documentation def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) with this code def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] for q in latest_question_list: output = ', '.join([q.question_text]) return HttpResponse(output) -
How to use date widget in django-import-export?
I'm new to programming so please bear with me in case I ask silly questions. I'm working on my first project which will gather data from Excel file. I'm trying django-import-export for that purpose but ran into a problem with date containing field. As far as I could understand searching this issue I need to use Date widget, cause it basically reads it as string while importing. But I couldn't find any example where this widget is used so I can see it's syntax. The model I'm working on is shown below. Hope some of you can help me on this. Thanks. from django.db import models from import_export.admin import ImportExportModelAdmin from import_export import widgets class Employee(models.Model): name = models.CharField(max_length=200) badge = models.CharField(max_length=15) start_date = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=True,widget=widgets.DateWidget(format=None)) end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) status = models.BooleanField(choices=( (True, 'Active'), (False, 'Inactive') ), default=True) job = models.ForeignKey(Matrix, on_delete=models.CASCADE, blank=True, null=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.badge)+ str(" - ") + str(self.name) class Meta: ordering=('name', 'badge', 'start_date', 'status',) verbose_name='Employee' verbose_name_plural='Employees' -
Send email using django without a settings file
Is it possible to do something like the following using the utility django sendmail? >>> import os >>> from django.core.mail import send_mail >>> os.environ['EMAIL_HOST'] = 'smtp.sendgrid.net' ... etc. >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'from@example.com', ... ['to@example.com'], ... fail_silently=False, ... ) django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If so, how could I do this? -
Django admin page. When i run the server everything will be fine, but when i try log into the admin page i will lose my connection
Am getting back the last line after i navigate to the 127.0.0.1:8000/admin the browser message This site can’t be reached127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED my terminal message "C:\Program Files\JetBrains\PyCharm 2019.2\bin\runnerw64.exe" C:\Users\UCHE\PycharmProjects\blog\venv\Scripts\python.exe C:/Users/UCHE/PycharmProjects/blog/manage.py runserver 8000 Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). March 16, 2020 - 22:15:50 Django version 3.0.4, using settings 'blog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [16/Mar/2020 22:16:26] "GET / HTTP/1.1" 200 19 Not Found: /favicon.ico [16/Mar/2020 22:16:28] "GET /favicon.ico HTTP/1.1" 404 2136 [16/Mar/2020 22:16:34] "GET /admin/ HTTP/1.1" 302 0 [16/Mar/2020 22:16:34] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [16/Mar/2020 22:16:35] "GET /static/admin/css/base.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/login.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:35] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:36] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 [16/Mar/2020 22:16:49] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Process finished with exit code -1 -
Django queries: When to use ' '
I just don't get why sometimes have to use something like Model.objects.filter('fieldname'=foo) and sometimes it is okay to use just fieldname without the ''. Could you explain that to me, please? -
Django page update without refresh
I have a small Django project consisting of one app. I am very very new to Django and have run into a problem. I have an app that is a webpage with a question posed and a form that must have input. Once the button is pressed to submit the form, I would like to update the page without refreshing. I have heard AJAX is a good way to handle this but I have not been able to find any examples working with just forms. My Forms from django import forms from . import models class AnswerForm(forms.Form): answer = forms.CharField(label='Answer', required=True, max_length=500) def save(self): answer_instance = models.Answer() answer_instance.answer_txt = self.cleaned_data["answer"] answer_instance.save() return answer_instance My Models from django.db import models from django.forms import ModelForm class Riddle(models.Model): riddle_txt = models.CharField(max_length=900) def __str__(self): return self.riddle_txt class Answer(models.Model): answer_txt = models.CharField(max_length=900) def __str__(self): return self.answer_txt My Views from django.http import JsonResponse from django.shortcuts import get_object_or_404, render from django.template import loader from .models import Riddle, Answer from . import forms # Create your views here. def index(request): form = forms.AnswerForm() if request.method == "POST": form = forms.AnswerForm(request.POST) if form.is_valid(): form.save() form = forms.AnswerForm() else: form = forms.AnswerForm() riddle_list = Riddle.objects.all() answer_list = Answer.objects.all() form = … -
Why i create two records at once using django-bootstrap-modal-forms
I'm using django-bootstrap-modal-forms. My forms.py: class UserAppForm(BSModalForm): class Meta: model = UserApp fields = ('app', 'app_type') In view, in order to attach current user, i override form_valid(): class AppCreateView(BSModalCreateView): template_name = 'apps/app_create.html' form_class = UserAppForm success_message = 'Success: App was created.' success_url = reverse_lazy('dashboard') def form_valid(self, form): app = form.save(commit=False) profile = Profile.objects.get(user=self.request.user) app.profile = profile app.save() return redirect(self.success_url) But, if i try to create UserApp, i get two instances at once. Where is my mistake? -
How to get image file from azure blob storage in django?
I habe build an app using django rest framework,react and deployed it to azure container service. I can successfully upload image on azure blob storage.but i need to process the image by a AI model to predict a result. I can easily get the image data from local database by 'instance.Image.path'. But when i connect the database to azure database then i cant get the image file.it throws an error called 'this backend doesn’t support absolute path'.so i changed the image.path to image.name but it always get the image name not the image file.I actually need the image file to process.what is the solution for azure service to get the image file. -
Can't access to django models with an external script
I have created a Django project with a series of tables (models) using postgresql. The thing, is that one of them I want to be able to access it also from outside the Django project, because from Django I simply want to see its content, but with an external script I want to insert the data. The problem I have is that when I try to access any of the tables created in django from an external script, the windows terminal, or even the program that postgresql offers. It tells me that the table does not exist. What am I leaving or doing wrong? The problem I have is that when I try to access any of the tables created in django from an external script, the windows terminal, or even the program that postgresql offers. It tells me that the table does not exist. What am I leaving or doing wrong? Below I show a screenshot with the tables I have and how it gives me an error. As you can see I have the ability to see all the tables, but then it doesn't let me select any of them. I have tried everything with lowercase and neither, … -
Modify certain sectioins of the django admin page in order to display user posted content
I'm attempting to allow users of my site to send in post suggestions, etc., which will be viewable only by admins through a read-only view on the Django administration page. Previously, when i ran all of this it returned: TypeError: __init__() takes 1 positional argument but 2 were given which I believe is related to this: # forms.py from django import forms class Form(forms.Form): username = forms.ChoiceField() message = forms.CharField() def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(Form, self).__init__(*args, **kwargs) I'm trying to load the desired content with this in messages.html: # messages.html {% for form in all_forms %} {{ form.username }} said: <br /> {{ form.message }} {% endfor %} This is my admin.py file: # admin.py from django.contrib.admin import AdminSite from django.http import HttpResponse from .models import Post from django.views import generic from .forms import Form from django.contrib.auth.urls import urlpatterns from django.shortcuts import render class MyAdminSite(AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) app_list += [ { "name": "Communication", "app_label": "communication", "models": [ { "name": "Messages", "object_name": "messages", "admin_url": "/admin/messages", "view_only": True, } ], } ] return app_list def get_urls(self): from django.urls import path urlpatterns += [ path('messages/', self.admin_view(self.Messages)) ] return urlpatterns class Messages(generic.ListView): def get(self, request, *args, **kwargs): … -
Error with Django formset when using ajax
I am trying to get an formset back with ajax but I get this error. I have {{ form.management_form }} and in my ajax, I am sending the management_form with the data back. Can someone see what I am doing wrong? ManagementForm data is missing This is my ajax: function plot() { $.ajax({ url: '', method: "POST", async: true, data: { 'form-0-new_mwant': $('#id_form-0-new_mwant').val(), 'form-0-new_rwant': $('#id_form-0-new_rwant').val(), 'form-0-new_fwant': $('#id_form-0-new_fwant').val(), 'form-1-new_mwant': $('#id_form-1-new_mwant').val(), 'form-1-new_rwant': $('#id_form-1-new_rwant').val(), 'form-1-new_fwant': $('#id_form-1-new_fwant').val(), 'form-TOTAL-FORMS': $('#id_form-TOTAL-FORMS').val(), 'form-INITIAL-FORMS': $('#id_form-INITIAL-FORMS').val(), 'form-MIN_NUM_FORMS': $('#id_form-MIN_NUM_FORMS').val(), 'form-MAX_NUM_FORMS': $('#id_form-MAX_NUM_FORMS').val(), csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val() }, dataType: 'json', beforeSend: function(){ $('.loader').css("display", "block"); $('#plot_image').css("display", "none"); }, success: function(json){ complete: function(){ }, error: function(xhr,errmsg,err){ console.log("error"); console.log(xhr.status + ": " + xhr.responseText); } }); }; This is my template: <div id="add_user_form"> <form action="{% url 'eci:index' %}#additional_user_form" method="POST" id="post-add-user-form"> {% csrf_token %} {{ addition_user_form.management_form }} {%for form in addition_user_form %} <span class="add_user_text"> Add More Point To Plot: </span> {{ form }} {% endfor %} </form> </div> This is from my view: from django.forms import formset_factory from .forms import AdditionalUserForm def get_variables(request): add_user_point_form = formset_factory(AdditionalUserForm, extra=2) context = {'addition_user_form': add_user_point_form()} response = render(request, 'index.html', context) # if this is a POST request we need to process the form data if request.method == 'POST': add_user_form = add_user_point_form(request.POST) -
How to run a python script from clicking a button on a HTML webpage?
I currently have a python script that updates certain CSV files when ran (it web scrapes and updates the information of a CSV file). In my HTML page (index.html), I have a script tag inside index.html that reads the CSV file and displays it as a table on the webpage. However, what I now need to do is update the CSV file by pressing an HTML button on the webpage. This will update the CSV file so when I run the button to run the JS script, it will have updated values from the file. I searched and found it very hard to understand what they meant by using flask and Django (I don't know anything about setting up servers). I don't want to set up a Django webpage because I want to work with my current pure HTML webpage I wrote. I would appreciate it if the answer is up to date with the current standard solutions for running python scripts in HTML. Please ask if you need more information. Thanks. -
Django models Foreign key select_related
class A(models.Model): field = models.CharField(max_length=200) class B(models.Model): field = models.CharField(max_length=200) a = models.ForeignKey(A, related_name='my_set', on_delete=models.CASCADE) I wanna get "B" models from A queryset: Such as: qs = A.objects.all().select_related('my_sets') -
django updateview not showing existing data to form
update is working but template form is not showing existing data. django updateview not showing existing data to form. when update page is showing only existing file is showing but object data is not showing. updateview cannot send existing data to form view.py from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from .forms import BookForm from .models import Book from django.views.generic import TemplateView, ListView, CreateView, UpdateView from django.urls import reverse_lazy class BookUpdate(UpdateView): model = Book form_class = BookForm success_url = reverse_lazy('class_book_list') template_name = 'updatebook.html' model.py from django.db import models from django.urls import reverse # Create your models here. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) pdf = models.FileField(upload_to='books/pdfs/') cover = models.ImageField(upload_to='books/covers/', null=True, blank=True) def __str__(self): return self.title forms.py from django import forms from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'author', 'pdf', 'cover') urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('books/', views.book_list, name='book_list'), path('books/upload/', views.upload_book, name='upload_book'), path('books/<int:pk>/',views.delete_book, name='delete_book'), path('class/books/',views.BookListView.as_view(), name='class_book_list'), path('class/books/upload/',views.UploadBookView.as_view(), name='class_upload_book'), path('class/books/update/<int:pk>/',views.BookUpdate.as_view(), name='class_update_book'),''' updatebook.html {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2> Upload Book to Database</h2> <form … -
How to get data out of a Django Model and in to the HTML Template?
I'm new to Django (and french so sorry if I'm not writing well) and I'm trying to display informations from my model Administrateur into my HTML Templates login.html but nothing is happening. This my Model class Administrateur(models.Model): nom = models.CharField(max_length=30) prenom = models.CharField(max_length=30) mdp = models.CharField(max_length=30) mail = models.CharField(max_length=30) def _str_(self): return self.name This is my view def Pseudo(request): administrateurs = Administrateur.objects.all() context={'administrateurs':administrateurs} return render(request, "login.html",context) This is my HTML {% load static %} {% block content %} {% for n in administrateurs %} {{ n.nom }} {{ n.prenom }} {% endfor %} {% endblock %} I'm not sure what to do with urls.py Thank you for help ! -
Remember users chosen theme
I'm making a toggle button for the user to choose between light and dark theme. I want Django to remember what them the user chose when they come back to the website. What would be the best approach to do this? Should I have an attribute for the user? Perhaps should I use a cookie? -
Django Extract Vimeo and Youtube Duration From The API
I have the following code that I am using to embed both Youtube and Vimeo videos into my django site. <div style="padding:56.25% 0 0 0;position:relative;"> <iframe src="{{ object.video_url }}?dnt=1&autoplay=0&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="encrypted-media; fullscreen" allowfullscreen></iframe> </div> <script src="https://player.vimeo.com/api/player.js"></script> Where {{ object.video_url }} can be either the following examples: https://player.vimeo.com/video/336812660 https://www.youtube-nocookie.com/embed/YE7VzlLtp-4 How would you be able to extract the {{ object.video_url }} duration which can either be from a Youtube or Vimeo video from the Youtube and Vimeo APIs?