Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get multiple object count uptade each own data
I need that books_to_discardfield (in Purchased), get the count objects that rating = 1 (in Rating). I try it, def discard(request): discard_today = Rating.objects.filter(user=request.user, rating__lte=1) a = discard_today.count() purchased.update(books_to_discard=a) for object in purchased: object.save() but it get the same value to all books_to_discard field : sum of all objects like rating=1. It didn't separate for each collection. So, how can I return this update that can I get all of count objects of each own collection like rating=1and post on each own books_to_discard field, separated into their own object with the correct collections.? rating/models.py class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) rating = models.IntergerField(default=0) book/models.py class Books(models.Model): collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=250, blank=True, null=True) collection/models.py class Collection(models.Model): title = models.CharField(max_length=50) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) purchased_collections/models.py class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) date = models.DateTimeField(default=datetime.now) books_to_discard = models.IntegerField(default=0) -
Reverse for 'program' with arguments '('',)' not found. 1 pattern(s) tried: ['home/(?P<program_id>[0-9]+)/program/$']
when i added the url it showing this error {% for prgmm in programinfo.all %} <a href="{% url 'program' prgm.id %}"> <div id="prgmm" style="width:50%"> <img src="{{ prgmm.titleimage.url }}" alt=""> </div> </a> my url is: urlpatterns = [ path('', views.homepage, name='home'), path('<int:services_id>/', views.details, name='details'), path('<int:prgm_id>/program/', views.program, name='program') and my view: def program(request, prgm_id): programdetail = get_object_or_404(prgm, pk=prgm_id) return render(request, 'program.html', {'programdetail': programdetail}) -
The Django admin page is not opening. Where am I going wrong?
I've just started working with Django 3.0.1. I used the python manage.py runserver command and tried opening localhost:8000/admin page but I get hit with a "GET / HTTP/1.1" 200 3731 in the command prompt and the server stops running. This is the urls configuration for the basic page I have been working on. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), #navigation url for admin page path('', include('blog.urls')), ] Is there any error which I have to rectify? -
can you solved this problem AttributeError: 'tuple' object has no attribute 'Command'
Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe__main__.py", line 9, in File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 38, in load_command_class return module.Command() AttributeError: 'tuple' object has no attribute 'Command' C:\Users\LENOVO\PycharmProjects\Soil>workon demo (demo) C:\Users\LENOVO\PycharmProjects\Soil>django-admin startproject App Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe__main__.py", line 9, in File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 38, in load_command_class return module.Command() AttributeError: 'tuple' object has no attribute 'Command' (demo) C:\Users\LENOVO\PycharmProjects\Soil>django-admin startproject App Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe__main__.py", line 9, in File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\users\lenovo\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management__init__.py", line 38, in load_command_class return module.Command() AttributeError: 'tuple' … -
Django-PolymorphicModels - Error when deleting an instance
It's the first time I'm trying 'PolymorphicModel', maybe there is something I'm doing wrong or I'm trying to do something that is not supported. Is there anyway to get around this? My simplified model: from django.polymorphic import PolymorphicModel class Question(PolymorphicModel): description = models.TextField(default='') compound_question = models.ForeignKey('CompoundQuestion', on_delete=models.CASCADE, blank=True, null=True, related_name='sub_questions') bonus_question = models.OneToOneField('BonusQuestion', on_delete=models.CASCADE, blank=True, null=True, related_name='question') class SimpleQuestion(Question): pass class CompoundQuestion(Question): pass class BonusQuestion(Question): pass If I create the necessary instances, compound_q = CompoundQuestion() compound_q.save() simple_q2 = SimpleQuestion(compound_question=compound_q) simple_q2.save() bonus_q = BonusQuestion(compound_question=compound_q) bonus_q.save() simple_q1 = SimpleQuestion(bonus_question=bonus_q) simple_q1.save() so that in the end I end up with: compound_q.sub_questions.all() >>> <PolymorphicQuerySet [<BonusQuestion: BonusQuestion object (5)>, <SimpleQuestion: SimpleQuestion object (8)>]> After I do compound_q.delete() I get: Traceback (most recent call last): File "<console>", line 1, in <module> File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/base.py", line 936, in delete collector.collect([self], keep_parents=keep_parents) File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 245, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 17, in CASCADE source_attr=field.name, nullable=field.null) File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 226, in collect sub_objs = self.related_objects(related, batch) File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 257, in related_objects **{"%s__in" % related.field.name: objs} File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File ".../Python/Django/env/lib/python3.6/site-packages/polymorphic/query.py", line 173, in _filter_or_exclude negate, *(list(q_objects) + additional_args), **kwargs File ".../Python/Django/env/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) … -
AngularJS and Django: :8000/uploaded_file:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I am trying to pass a file from my front-end (AngularJS) to my back-end(Django). It was working well yesterday, but however, when I logged in today, I will have this error that says: :8000/uploaded_file:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). .html: <body ng-app="myApp" ng-controller="appCtrl"> <input type="file" id="file" name="files" accept="text/*" data-url="file" class="inputfile_upload" select-ng-files ng-model="uploadedFile"/> <label for="file"> <span id="chooseFile"></span>Upload a file!</label> <button id="submitBtn" type="submit" ng-click="upload()">Upload</button> </body> directive.js: app.directive("selectNgFiles", function($parse) { return { require: "ngModel", link: function postLink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } } }); controller.js: var app = angular.module('myApp', []) app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){ $scope.upload = function() { var file = $scope.uploadedFile; console.log('file is ' ); console.dir(file); var uploadUrl = "/uploaded_file"; fileUploadService.uploadFileToUrl(file, uploadUrl); $http({ method:'POST', url: '/uploaded_file' }).then(function successCallback(response) { console.log("success"); }, function errorCallback(response){ console.log("failed"); }) }; } service.js: app.factory('fileUploadService', function ($rootScope, $http) { var service = {}; service.uploadFileToUrl = function upload(file, uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': 'multipart/form-data'} }).then(function successCallback(response){ console.log("Files added"); }, function errorCallback(response){ console.log("Files not successfully added"); }) } return service; }); urls.py: urlpatterns = [ url(r'^uploaded_file$', uploadFile, name='uploadFile'), url(r'^admin/', admin.site.urls), ] if … -
django.db.utils.IntegrityError, invalid foreign key. Can someone help me and teach me what happens?
can someone help me and teach me what happens? For me not to make mistakes again? I want to bind a foreign key (class category) to my course class. And I did something that doesn't allow me to get out of it. Error: django.db.utils.IntegrityError: The row in table 'courses_course' with primary key '3' has an invalid foreign key: courses_course.category_id contains a value 'outros' that does not have a corresponding value in courses_category.id. CATEGORY = [('eng','ENGENHARIA'),('prog','PROGRAMAÇÃO'),('hum','HUMANAS'),('saude','SAÚDE'), ('outros','OUTROS')] // i'm from brazil class Category(models.Model): title_category = models.CharField('Nome da Categoria', max_length= 63 , choices = CATEGORY ) class Course(models.Model): title = models.CharField('Nome', max_length= 100) slug = models.SlugField('Atalho',max_length=50) description = models.TextField('Descricao',blank = True) follows = models.IntegerField(default = 0) //allows negative numbers, I know. I'll fix it ... imagem = models.ImageField(upload_to = 'courses/images',verbose_name= 'Imagem', null=True, blank = True) category = models.ForeignKey('Category', on_delete = models.CASCADE) created_at = models.DateTimeField('Criado em',auto_now_add = True ) updated_at= models.DateTimeField( 'Atualizado em', auto_now = True ) Does anyone imagine another structure or class that allows you to create educational courses / videos that have categories? Or am I on the right track for a beginner? -
What is the best way to handle backend in flutter? Can it be linked with django?
I was researching and I could not find a proper solution. If you have some examples, please also explain why. -
Accessing context variable (a list) in Django Views in Javascript HTML
I am facing some problems trying to access a context variable in my django views in my html javascript. I would like to access 'unclean' context which is a list and USE IT AS A LIST in my html script tag. Any help is appreciated. Thank you. Below are some of my code: views.py context = { 'unclean' : unclean } -
Undefined variable url in vscode anacondapython
i have created a view in views.py and when i try to add the url i get the error. I am following a tutorial and doing exactly as told.created view adding url tutorial im following -
ModuleNotFoundError: No module named 'django.utils.six'
HTTP GET /admin/ 500 [0.00, 127.0.0.1:51425] Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\daphne\http_protocol.py", line 180, in process "server": self.server_addr, ModuleNotFoundError: No module named 'django.utils.six' Installed Django 3. Django.utils.six is no longer supported. Thoughts? -
creating a hyperlink in django using href
I tried to copy the way this django tutorial did their hyperlinks for my own project: https://docs.djangoproject.com/en/3.0/intro/tutorial01/. However, on my screen, I do not have hyperlinks, just regular text. What I currently have in my index is a bunch of names of units, and I want the user to be able to click on that unit to get a more detailed view of that unit's information. This is what I currently have in my templates, views, and urls: urls: from django.urls import path from . import views app_name = 'calc' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.UnitView.as_view(), name='unit'), ] views: from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from django.shortcuts import render from django import forms from .models import Unit, Class # Create your views here. class IndexView(generic.ListView): template_name = 'calc/index.html' context_object_name = 'unit_list' def get_queryset(self): return Unit.objects.all() class UnitView(generic.DetailView): model = Unit template_name = 'calc/unit.html' index.html: {% if unit_list %} <ul> {% for unit in unit_list %} <li><a href="{% url 'calc:unit' unit.id %}"></a>{{ unit.unit_name }}</li> {% endfor %} </ul> {% else %} <p>No units are available.</p> {% endif %} unit.html: {{unit.unit_class}} My guess is that either I'm using href … -
How to create a query function that will set a dynamic variable foreach selected column
Sorry if the title is misleading , i have a page that has many select option element , that will make you choose the database name , table name , column name , and filter .. here's the html div class="row mt"> <div class="col-lg-12"> <div class="form-panel"> <form class="form-horizontal style-form" action="#"> <div class="form-group"> <label class="control-label col-md-3">Database Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <option disabled selected value>-- Choose --</option> <!-- <li><a href="#"></a></li> --> {% for table in obj2 %} <option value = "{{table}}" >{{ table }}</option> {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> <div class="form-group" id="column-name"> <button class="btn btn-theme" onclick="return appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class = "columnselect" id="headerselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> <div class="form-group" id="condition"> <button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button> <label class="control-label col-md-3">Filter</label> <div class="col-md-4" id="filtbox"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class = "columnselect" id="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;"></select> <select id="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> <option disabled selected value>-- Choose --</option> <option> > </option> <option> < </option> <option> … -
Foreignkey in Django. How to properly create models
Hi everyone and merry Christmas. I am new to Django and I am trying to create a model for a website I am developing. So far I know how to implement everything I want to, but there is one thing that I cannot properly understand. So my idea is the following, in the models: A class "Class" that can have as many "Teacher" and "Student" as wanted by the admin. I've been playing for a while with foreign key, but I can only manage to associate one student and teacher to a class, and whenever I want to display the "Class" info there is no Student or Teacher to display. Help would be very appreciated ! from django.db import models from datetime import datetime # Create your models here. LANGUAGE_CHOICES = ( ('english','ENGLISH'), ('spanish', 'SPANISH'), ('german','GERMAN'), ('french','FRENCH'), ('portuguese','PORTUGUESE'), ) class Clase(models.Model): name = models.CharField(max_length=300) language = models.CharField(max_length=10, choices=LANGUAGE_CHOICES, default='english') def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=300) clase = models.ForeignKey(Clase, on_delete=models.CASCADE) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) total_earnings = models.IntegerField() month_earnings = models.IntegerField() clase = models.ForeignKey(Clase, on_delete=models.CASCADE) def __str__(self): return self.name -
passing django object context to sendgrid email via sendgrid-python API lib
my django app has a view for an account can send out newsletter emails to its contacts using Sendgrid's API. sending is working with a plaintext email: from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import (Mail, Subject, To, ReplyTo, SendAt, Content, From, CustomArg, Header) def compose_email(request, send_to, *args, **kwargs): ... if request.method == 'POST': subject = request.POST.get('subject') from_name = request.POST.get('from_name') body = request.POST.get('body') reply_to = request.POST.get('reply_to') test_address = [request.POST.get('test_address')] # send test email if request.POST.get('do_test'): if form.is_valid(): message = AccountEmailMessage(account=account, subject=subject, from_name=from_name, destination=destination, body=body, reply_to=reply_to, is_draft=True, is_sent=False) message.save() email = Mail( subject=subject, from_email=hi@app.foo, html_content=body, to_emails=test_address, ) email.reply_to = ReplyTo(reply_to) try: sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sendgrid_client.send(email) message.sendgrid_id = response.headers['X-Message-Id'] message.save() except Exception as e: log.error(e) messages.success(request, 'Test message has been successfully sent') else: messages.error(request, 'Please, check for errors') this works. but we want to render django object properties (model fields via template tags) in an html email template from Account (account) [assume it's just a vanilla obj req query account = Account.objects.get(id=selected_account) in the view], and I'm not clear what's the recommended docs approach. the attempt: if request.method == 'POST': subject = request.POST.get('subject') from_name = request.POST.get('from_name') body = request.POST.get('body') reply_to = request.POST.get('reply_to') if request.POST.get('send'): if form.is_valid(): message = AccountEmailMessage(account=account, subject=subject, from_name=from_name, … -
Permission denied when uploading file (Django, Apache2)
I deployed a beta version of my django app to DigitalOcean and I am serving it using Apache2 for both python and static files. Here is the issue, when I upload a file, it gives me the following error: PermissionError at /admin/dashboard/marque/add/ [Errno 13] Permission denied: '/verauto/site/public/media/marques' Here is an excerpt of my settings.py file, as well as the sites-available configuration for apache2: settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' #MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = '/verauto/site/public/media' MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' #STATICFILES_DIRS = ( # os.path.join(BASE_DIR, 'verautonoapi/static'), # os.path.join(BASE_DIR, 'boot'), #) #STATIC_ROOT = os.path.join(BASE_DIR, 'root') STATIC_ROOT = '/verauto/site/public/static' apache2 configuration: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog /verauto/site/logs/error.log CustomLog /verauto/site/logs/access.log combined alias /static /verauto/site/public/static <Directory /verauto/site/public/static> Require all granted </Directory> alias /media /verauto/site/public/media <Directory /verauto/site/public/media> Require all granted </Directory> <Directory /verauto/app/verauto-staging/verautonoapi/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess verauto python-path=/verauto/app/verauto-staging/ python-home=/verauto/verenv WSGIProcessGroup verauto WSGIScriptAlias / /verauto/app/verauto-staging/verautonoapi/wsgi.py </VirtualHost> As you can see, in my attempts to solve the issue, I added the media directory in the apache2 configuration, I also did the following commands for chmod rights: sudo groupadd XXXXXX sudo adduser www-data XXXXXX sudo chgrp -R XXXXXX /verauto/site/public/media/ sudo chmod -R 760 … -
Add queryset as_manager to the AbstractUser model
I have a simple model User that simply extends the AbstractUser class with some extra fields. I tried adding "objects = UserQuerySet.as_manager() but is giving me an error "get_by_natural_key() is not defined" when i try to create a superuser. It seems that it is overwriting the regular user manager so i am losing the methods that it comes with. I tried renaming the objects field to something else so I wouldnt be overwriting the default one but it still the same error. Is there any way to simply add querysets without creating whole new manager class, extending the BaseUserManager, adding all of the default methods from scratch, and adding my custom queryset to it? I just want to keep the regular USerManager and just add querysets. -
How to access Django session in React
If I am using Django REST framework for session authentication https://www.django-rest-framework.org/api-guide/authentication/ And React on the frontend, I am wondering how I can determine if I my session is active in Django in React? I'm assuming that the session is implemented via setting a cookie in the clients browser, so that every time a request is sent from the client it will have this cookie in the header, which Django automatically reads from. If this is the case, what is the best way to access this cookie? Or rather, what is the ideal way to check if a user is still authenticated directly? Right now I can send a request to an endpoint and if I am not authenticated, it will throw a 403 error, but this is not an elegant way to check logged in status on the frontend, in my opinion. -
Delete all tables in the postgresql database using Django without deleting the database
I am running AWS Elastic Beans which automatically set up a working postgresql database instance and connection for me. Therefore I do not want to just delete the database instance and configure it myself. I would rather just delete all tables in the database from python/django. I also do not want to delete the content of all tables (what python manage.py flush does). I want the database to return to a state where I can just run python manage.py migrate and it will create all empty tables from my current model definitions. Thanks -
How can I show calendar but not input box of input type=date WITHOUT USING JAVASCRIPT/JQuery (only through HTML) in Django?
enter image description here input type="text" placeholder="dd/mm/yyyy" name ="detail" data-date-inline-picker="true" ''' Calendar not showing by above method ''' ''' Solution required because I need to save multiple data types in Model than JUST date''' -
Object is not iterable - Django
I'm having an object "Movie" not iterable, I can't find my errors. I have two similar views I'm wondering if it's the issue. I want to display just 5 actors and then a link to see all actors from the movie. Could you please give me a hand? Thanks template: View.py def home(request): date = datetime.date.today() start_week = date - datetime.timedelta(date.weekday()) end_week = start_week + datetime.timedelta(7) movie_semaine = Movie.objects.filter(release_date__range=[start_week, end_week])[:4] #descending order by '-release_date' movie_cinema = Movie.objects.filter(is_available_in_theaters=True).order_by('-release_date')[:4] context = {'movies_list': movie_semaine, 'movies_cinema': movie_cinema} return render(request, 'bms/visitor/index.html', context) def movies(request): all = Movie.objects.all() return render(request, 'films.html', {'films': all}) def movie_detail(request, id): #movie = Movie.objects.get(id=id) movie = Movie.objects.get(pk=id) #order by order column to get only the Top 5 Actors role = Role.objects.filter(movie=movie).order_by("order")[:5] actor = Actor.objects.filter(movie_list=movie) #cinema = Cinema.objects.filter(movies=movie) return render(request, 'bms/visitor/film.html', {'movies': movie, 'roles': role, 'actors': actor}) def movie_actors(request, id): movie = Movie.objects.get(pk=id) role = Role.objects.filter(movie=movie) actor = Actor.objects.filter(movie_list=movie) return render(request, 'bms/visitor/actors.html', {'movies': movie, 'roles': role, 'actors': actor}) def movie_review(request, id): movie = Movie.objects.get(pk=id) return render(request, 'bms/visitor/critique.html', {'movies': movie}) def actor_detail(request, id): #movie = Movie.objects.get(pk=id) actor = Actor.objects.get(pk=id) role = Role.objects.filter(actor=actor) return render(request, 'bms/visitor/actor.html', {'roles': role, 'actors': actor}) -
How to output the full path of a FilePathField in Django?
Consider the following model: STOCK_IMAGE_DIR = os.path.join(settings.MEDIA_ROOT, 'stock_images') class Product(models.Model): stock_image = models.FilePathField(path=STOCK_IMAGE_DIR, default='image.png') When accessing the stock_image of a product, it only returns the name of the image: >>> p = Product.objects.first() >>> p.stock_image 'image.png' How can I output the entire path of the file? -
How do you change the currency in open edx ironwood?
I have open edx and its ecommerce application fully installed and working. The platform has a default currency set to USD but I need it set to Euros Some forums online suggested changing the currency variable in lms.env.json as well as the currency variable in course mode within the LMS admin. However this hasn't worked for me. There are no other solutions on the internet. Has anyone incurred and solved this problem? -
How to use OpenID in Django
I'm trying to use SSO in my application provided by Ping Identity and from what I could tell they support both OAuth and ODIC if specified in the scope. While I haven't found a specific client library for Ping Indentity, I did find packages like python-social-auth and django-allauth which include an OpenID connect integration. I tried both of them but unfortunately, I didn't understand the fields required to set it up. According to the OAuth and OpenID specifications, I was looking for fields like client id, client secret, authorization and token endpoints, redirect URI, and optional claim-to-user attribute mappings. But I have no idea what handle, issued, lifetime, association type are. Can anyone explain how to get a Ping Identity SSO fully integrated with Django such that I can still use permissions on my own local API with the authenticated and authorized users? -
Getting error when I import LoginBackEnd module into settings.py
I am using just phone number alone as the only field for login. So I am trying to write my custom backend authentication. On trying to import the LoginBackend module, I am getting the error below. ERROR WHEN I CONFIGURE THE AUTH BACKENDS: File "C:\Users\UBITEK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def logins(request): phone_number = request.data.get("phone_number") if phone_number is None: return Response({'error': 'Please provide your phone number'}, status=HTTP_400_BAD_REQUEST) user = authenticate(phone_number=phone_number) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) backends.py from django.contrib.auth.backends import ModelBackend from .models import User class LoginBackend(ModelBackend): def authenticate(self, request, **kwargs): phone_number= kwargs['phone_number'] user = User.objects.get(phone_number=phone_number) if user: return user else: return None settings.py from .backends import LoginBackend from django.contrib.auth.backends import ModelBackend AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'findr.backends.LoginBackend']