Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need help to integrate duo_python 2FA into Django-mama-cas
I've setup django-mama-cas as a primary central authentication server for serveral department websites. The websites reside in a drupal/php web framework and use phpCAS for the CAS client. I need to integrate duo_python somehow to the django-mama-cas server. I am not sure where to start and any advice on what files or classes to edit is what I am looking for. From what I imagine those [files, classes, etc] to be, are below: settings.py import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! with open('/n/fs/stage/signon/cas_container/casServer/secret_key.txt') as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['signon.example.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mama_cas', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'casServer.urls' # Django Templates Settings: https://docs.djangoproject.com/en/2.2/topics/templates/ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # WSGI Settings: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ WSGI_APPLICATION = 'casServer.wsgi.application' # Database Settings: https://docs.djangoproject.com/en/2.2/ref/databases/ DATABASES = … -
login_required decorator on a class based view in django
I have a working class based view. But when adding @login_required I get the error: AttributeError: 'function' object has no attribute 'as_view' Something is happening to the ResultListView here: from django.urls import path from .views import ResultListView urlpatterns = [ path('meetings/', ResultListView.as_view(), name='meetings'), ] My views.py: @login_required class ResultListView(ListView): template_name = ... def get_queryset(self): return Result.objects.filter(rider__user=self.request.user) Which is all working fine until I put the decorator in. Very confused now, I don't see why ResultListView should loose its attributes when sending it through the decorator. -
Get the last and unique element of the list based on date
Here is my data and code: [ (datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 24), 'Raport'), (datetime.date(2020, 3, 23), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 24), 'Document'), (datetime.date(2020, 3, 23), 'Document'), (datetime.date(2020, 3, 25), 'Analize'), (datetime.date(2020, 3, 24), 'Analize'), (datetime.date(2020, 3, 23), 'Analize'), ] Here is django (2.2) code: sorted(DataSet.objects.values_list('doc_type', flat=True).distinct(), reverse=True) I need to get the last and unique element of each document doc_type together with the date. At the moment I have the same list of documents: ['Raport', 'Document', 'Analize'] but I need: [(datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 25), 'Analize')] Can someone provide me some hint? Thanks. -
Django View: ConnectionError: HTTPSConnectionPool
I have a django view in a production project: @csrf_exempt def test_view(request): ... Clients who intended to use this endpoint for a redirect says that its not working. I try to test it locally. If I access the url using the browser it works fine but every time I try to access this endpoint in a script locally. I get this error: import requests r = requests.get('http://mywebsite.com/test/?test_run=me') print(r.text, r.status_code) error: File "venv\lib\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='mywebsite.com', port=443): Max retries exceeded with url: /test/?test_run=me(Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000011424D0ABE0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) Process finished with exit code 1 Any idea of resolving ? -
Linking a model in Django
I have two models LeaveType and MyUser class LeaveType(models.Model): type_ = models.CharField(max_length=50, null=False, blank=False) total_leave_per_year = models.IntegerField(null=False, blank=False, default = 0) def __str__(self): return self.type_ Say, Leave types are: 1. Annual Leave of 20 days per year 2. Sick Leave of 5 days per year class MyUser(models.Model): dob = models.DateField(auto_now_add=True) leave = models.ForeignKey(LeaveType, on_delete=models.CASCADE, related_name="lms_leave_type") Now, When a user apply for an annual for 2 days then his/her remaining leave will be 18 days per year. Now how can I manage this? I have tried to use Inline ways but it does not work for me. Another method I tried is building another model containing user object, leave type object and his/her remaining leaves. Is this a better way or we have another better than this? Thank You. :) -
Order a Django queryset by another dict
So, right now I have this model and a calculated dictionary class User(models.Model): user_id = models.AutoField(primary_key=True) #scores dict {user_id: score} scores = {1: 9, 2: 2, 3: 1, 4: 5} I need to order the queryset based on each user score in the scores dict. Something like this Views.py queryset.annotate(score=scores['user_id']).order_by('score') -
get django rest api Image field url as data to generate QRcode
Im absolute beginner and currently trying to generate qr code so ,how would i get or retrive the url of image field in views.py so that i can add data to make qr code basically the original image is first posted in aws with django rest framework models.py from django.db import models class Picture(models.Model): Original_Image = models.ImageField(upload_to="media/images") QR_Embedded_Image = models.ImageField('QR_Embedded_Image') created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('App', views.PictureView) urlpatterns = [ path('', include(router.urls)), path('upload-image/', views.UploadImage.as_view(), name="UploadImage"), ] views.py class PicturesView(viewsets.ModelViewSet): queryset = Pictures.objects.all()[:2] serializer_class = PicturesSerializer def create(self, request): image_url = upload_files_to_s3("image.jpeg") qr_code = qrcode.QRCode(box_size=2) qr_code.add_data('image url ') qr_code.make() qr_code_img = qr_code.make_image(fill_color= "#000000" , back_color= "white") qr_code_img.save(' ') -
How to get key-value of context in Django?
I try to query to get all of Topic of Post. Each Post belong multiple Topic. I got this but i don't know how to pass to Template. This is my code. In template i got posts but i can't access topics of single posts. Thank for help. models.py class Post(models.Model): title = models.CharField(unique=True, max_length=121) content = models.TextField() published = models.DateField(default=timezone.now) def __str__(self): return self.title class Topic(models.Model): topic_name = models.CharField(primary_key=True,unique=True, max_length=60) posts = models.ManyToManyField(Post) def __str__(self): return self.topic_name views.py def codinglife(request): posts = Post.objects.filter(topic__topic_name__contains='codinglife') #Get posts belong topic 'codinglife' context = { 'posts': Post.objects.filter(topic__topic_name__contains='codinglife') } # for each post get topic this post belong many topic for post in posts: context[post.id] = Topic.objects.filter(posts=post) return render(request, 'site/topiclistview.html', context) Template {% extends "site/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ post.published }}</small> {% comment 'need to show topic her' %} {% endcomment %} </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} -
Django Quiz make it repeatable
I found this via google: https://github.com/sibtc/django-multiple-user-types-example I would like to change this quiz so that a checkbox asks if the quiz may be repeated when creating it. I have added the repeat in the models. class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') name = models.CharField(max_length=255) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='quizzes') repeat = models.BooleanField(default=False) and also ind the craete and updateview class QuizCreateView(CreateView): model = Quiz fields = ('name', 'subject', 'repeat', ) Now of course I would like the quiz to be repeated. For this purpose I have in the appropriate view: @method_decorator([login_required, student_required], name='dispatch') class QuizListView(ListView): model = Quiz ordering = ('name', ) context_object_name = 'quizzes' template_name = 'classroom/students/quiz_list.html' def get_queryset(self): student = self.request.user.student student_interests = student.interests.values_list('pk', flat=True) taken_quizzes = student.quizzes.values_list('pk', flat=True) queryset = Quiz.objects.filter(subject__in=student_interests) \ #.exclude(pk__in=taken_quizzes) \ .annotate(questions_count=Count('questions')) \ .filter(questions_count__gt=0) return queryset Here I have temporarily removed the corresponding exclude. Then I see the quiz in the list, but unfortunately I cannot call it up again. Now I get the template error: Exception Type: TemplateDoesNotExist Exception Value: students/taken_quiz.html How can I have the quiz repeated now? -
django-pytest error creating test database containing many to many field
I have a model having many to many field like the following. I am using pytest to write unit test cases for it. models.py class CustomerMaster(models.Model): customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase. first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase. last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase. gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase. dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase. address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'customer_master' def __str__(self): return self.first_name + self.last_name class Segment(models.Model): name = models.CharField(max_length=100) folder = models.CharField(max_length=100) selection = JSONField() createdAt = models.DateTimeField(null=True) updatedAt = models.DateTimeField(null=True) createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) contact = models.ManyToManyField(CustomerMaster) def __str__(self): return self.name I need to check if only the logged in user is able to acces the view. For that, I am using the @login_required decorator provided by the django itself. For creating a dummy user I am using the following fixture: conftest.py import uuid import pytest @pytest.fixture def test_password(): return … -
Django: Filter object and create for million of records
get_or_create() is just a convenience function, but if i need to have (Filter+create) million of record in a single go?. bulk_create only create objects but not filtering. Can i do it using with transition or rawquery is the only solution? result = Model.objects.filter(field__lookup=value)[0] if not result: result = Model.objects.create(...) return result -
Web Application preferably in Django or Laravel with fingerprint detection
i got a project for school that asked me this stuff: It is a simple web application for fingerprinting users or visitors. Something similar as this one, except that we don't need to check if fingerprint is unique. https://amiunique.org/fp So the app should be modern and should respond to the visitor details of his device (OS, browser, IP address, country, city - this can be done via API /maxmind/... and some other information from device) Here you can use any framework as you want bootstrap or anything else... Design should be simple - in front page should have one button in the middle which says: Scan me or whatever, after clicking all results should appear on the page in organized way. Here is one example of front page: https://fingerprintjs.com/open-source/ The purpose of app is to detect if OS is outdated or browser is not latest version to inform user in some sort of windows. But that we can discuses later. Can you provide me some sources on how can i start this fingerprint thing, i have good knowledge of web developing html css js back-end and front-end, but implementing fingerprint is first time in my life. THANKS!!!! -
Django Model details displayed in the Bootstrap modal
Not sure if this question was asked before, but even that it is, it's out-dated, so pardon my repetition. I'll jump straight to it - I have a datable which is rendered from a complicated cross tabbed query, and it returns like 10 000+ rows, and in the very table I have a "detail" button which triggers a bootstrap modal, and when it opens it just shows some more unique details about the current object, or row. Now, the problem is, when the page where the table is, gets called, it takes so much time to load, it has 20 megabytes, which is a lot, and it takes like 5 seconds depending on the processor because every object gets loaded with his own modal (its happening inside the for loop). My question is, what is the best approach to load the details(bootstrap modal) only when the "details" button gets pressed. I tried something with Ajax, which was confused for me, so I would appreciate every suggestion. Thank you! This is the html of a table : % block content_row %} {% include 'partials/_alerts.html' %} <div class="card-body container-fluid"> {% include 'opportunity/opp_breadcrumb.html' %} <h2 class="-heading" style="margin-left: 50%">OPTIKA</h2> <table class="table table-bordered table table-hover … -
ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice'
Folder Structure of my project where apidjangowithjwt is the project name & emailservice and user are the apps. views.py in user app where I am importing emailservice app which is giving the error Detailed error: File "F:\DjangoDemo\JWTAuthentication\apidjangowithjwt\user\views.py", line 17, in from apidjangowithjwt.emailservice.views import send_email ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice' from apidjangowithjwt.emailservice.views import send_email **#giving error** views.py in emailservice app where I defined a function send_mail. from django.core import mail def send_email(**kwargs): with mail.get_connection() as connection: email=mail.EmailMessage(kwargs['subject'],kwargs['body'],kwargs['from_email'],kwargs['to_email'],kwargs['bcc'], connection,kwargs['attachments'],kwargs['header'],kwargs['bcc'],kwargs['reply_to']) email.send() I have also registerd my both apps in settings.py as: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'rest_framework', 'emailservice' ] -
FDB connection on Python closes itself
I am using FireBird connector for Python in my django app. I have a single connection per session, in order to minimize the loading times and increase the efficiency, but whenever the connection is being alive for more than 10 minutes, the connection "closes" itself. It's quoted because it doesn't really close itself, the object connection is still alive and the attribute closed of the class is set to False. In this state, whenever you try to execute a query, and fdb.fbcore.DatabaseError is thrown. This is my connector class I use to create a connection: class DBConnector(object): def __init__(self): print("Init Connector") self.host = 'the_host' self.database = 'the_database' self.user = 'the_user' self.password = 'the_super_secret_and_secure_key' self.charset = 'the_most_common_charset' self.dbconn = None def create_connection(self): print("Creating Connection") connection = fdb.connect( host=self.host, database=self.database, user=self.user, password=self.password, charset=self.charset, ) return connection def __enter__(self): self.dbconn = self.create_connection() return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): self.dbconn.close() When I do con = DBConnector() cursor = con.cursor() cursor.execute(MY_SELECT) It works perfect. Now if i let the connection alive for more than 10 minutes and try again to execute a query: cursor.execute(ANOTHER_SELECT) It throws fdb.fbcore.DatabaseError: Error while preparing SQL statement:\n- SQLCODE: -902\n- Unable to complete network request to host .\n- Error writing … -
DJANGO project admin page not opening
I was making a to do website using Django. And i encountered a weird error. As soon i start my server and type /admin to the url my server gets close. Not able to access the admin page. Any fixes? thanks. PS: my url file doesn't have any error. Image of the terminal : terminal screnshot -
Travis CI failing flake8 tests despite flake8 tests passing on local development environment?
Background I am building a project using Django, Docker, Travis CI and Flake8. My flake8 file: [flake8] max-line-length = 119 exclude = migrations, __pycache__, manage.py, settings.py, env When I run local flake8 tests using: docker-compose exec app python manage.py test && flake8 I receive an ok message with no error messages. My code is good! The problem When I push my code to master which automatically starts Travis CI, the Travis build fails due to the following errors: ./project/settings.py:94:80: E501 line too long (91 > 79 characters) ./project/settings.py:97:80: E501 line too long (81 > 79 characters) ./project/settings.py:100:80: E501 line too long (82 > 79 characters) ./project/settings.py:103:80: E501 line too long (83 > 79 characters) ./core/models.py:7:80: E501 line too long (93 > 79 characters) ./core/models.py:13:80: E501 line too long (104 > 79 characters) ./core/migrations/0001_initial.py:18:80: E501 line too long (126 > 79 characters) The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. My flake8 file specifically states that the max line length is 119 so these errors should not be happening (like they are not when running the test on my local machine). Does anyone know whats going on? -
How do i add a form to blog post detail?
So I Have a small django blog project. i have successfully built a blog post views and a blog post detail view. but i want to add a small form in the post detail page; so whenever you add a new post, a new form would be made in the detail page.i know how to make forms in general. please help me with the code -
websockets using django channels and angular 2+
I'm trying to create a simple create, retrieve, update, delete using django channels and have angular 2+ as my fronted. I'm unsure if I am on the right path but here is what I have so far. Below is my django consumers code: consumers.py class CourseConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'couses' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) code = text_data_json['courseCode'] name = text_data_json['courseName'] description = text_data_json['courseDescription'] created_by = text_data_json['course_created_by'] professor = text_data_json['course_professor'] course = models.Course.objects.get(pk=id) course.code = code course.name = name course.description = description course.created_by = created_by course.professor = professor async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'add_course', 'id': id, 'course': title, 'name': name, 'professor': professor, 'description': description, 'created_by': created_by } ) def add_course(self, event): code = event['courseCode'] name = event['courseName'] description = event['courseDescription'] created_by = event['course_created_by'] professor = event['course_professor'] self.send(text_data=json.dumps({ 'id': id, 'course': title, 'name': name, 'professor': professor, 'description': description, 'created_by': created_by })) routing.py from django.urls import path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from course.consumers import CourseConsumer application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter([ path('courses/', CourseConsumer), ]) ), }) Below is my angular code: course.service.ts webSocket: WebSocketSubject<any>; messages: Observable<any>; connect(): void … -
nginx fails while the website somehow still works
Description I have built my Django3, gunicorn, nginx, Ubuntu 18.04, Digital Ocean project based on this guide. I only had 1 problem that it does not shows the CSS and all other static files like images. Before during the whole guide nginx have given the correct answers as the guide says and also currently the html site still online and running To solve this I was in the process of using this another guide to make my static files displayed on my site. I have done all the steps what the creator recommended but at the What I have tried After each step of the following [1.2.3...] commands I have executed the following commands to refresh: python3 manage.py collectstatic sudo nginx -t && sudo systemctl restart nginx sudo systemctl restart gunicorn 1.RUN: sudo ln -s /etc/nginx/sites-available/ch-project /etc/nginx/sites-enabled 1.RESULT: ln: failed to create symbolic link '/etc/nginx/sites-enabled/ch-project': File exists 2.RUN: /etc/nginx/sites-enabled/my-project 2.RESULT: -bash: /etc/nginx/sites-enabled/my-project: Permission denied 3.RUN: systemctl status nginx.service 3.RESULT: ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2020-03-26 13:27:08 UTC; 13s ago Docs: man:nginx(8) Process: 11111 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile … -
Is there a way to combine view functions of similar structures into one? Django
I'm a beginner at Django. Recently, I started writing a web app for inventory management and I realised that when i was writing the views, there were a lot of them with similar structures. For instance: def invoices(request): """The page for displaying invoices.""" invoice_list = Document.objects.filter(type_name__name='Invoice') page = request.GET.get('page', 1) paginator = Paginator(invoice_list, 10) try: invoices = paginator.page(page) except PageNotAnInteger: invoices = paginator.page(1) except EmptyPage: invoices = paginator.page(paginator.num_pages) context = {'invoices':invoices} return render(request, 'imsapp/invoices.html', context) and this one: def credit_notes(request): """The page for displaying credit notes.""" credit_notes_list = Document.objects.filter(type_name__name='Credit Note') page = request.GET.get('page', 1) paginator = Paginator(credit_notes_list, 10) try: credit_notes = paginator.page(page) except PageNotAnInteger: credit_notes = paginator.page(1) except EmptyPage: credit_notes = paginator.page(paginator.num_pages) context = {'credit_notes':credit_notes} return render(request, 'imsapp/credit_notes.html', context) So, I'm just thinking if there is a more elegant way to represent the above functions. Is class based view what I'm looking for? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f197e469a60>
hi guys i'm working in project with cms called tendenci which required to work with PostgreSQL and python django, I've been working on it on a virtual machine with Ubuntu and when i tried to migrate to production server (with Ubuntu also) i faced a lot of issues the last is migrate the db, actually i did all the required steps but it still showing an error when i try to run the server this is the command that i run python manage.py runserver this is the error that i get Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fadbc707a60> Traceback (most recent call last): File "/srv/mysite/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "site_settings_setting" does not exist LINE 1: SELECT (1) AS "a" FROM "site_settings_setting" WHERE ("site_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/srv/mysite/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/srv/mysite/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/srv/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/srv/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in … -
Template Not Found Error in Django while inlcuding html comments
Django version 2.0.7, Python3.6 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>My Own Website via base file</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <!-- {% include 'navbar.html' %} --> {% block content %} {% endblock %} </body> </html> The above code throws an error, whereas the following one doesn't. The only difference is in the content of comment. Could someone explain ? I am using this code template to learn Django and this example of inheritance in templates throws TemplateDoesNotExist at /home/ error. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>My Own Website via base file</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in … -
Django custom permissions unable to call in decorator as i passed in params
I want to apply django permissions on viewsets and I create a decorator for this but its not working. I just want to call the permission class in decorator as passed in argument. views.py ''' class MapViewSet(viewsets.ModelViewSet): serializer_class = MapSerializer @permission_decorator(permission_class=MapPermission) def get_queryset(self): return Map.objects.all() ''' utils.py ''' METHODS = {'GET': 'view_permission', 'PATCH': 'add_permission', 'POST': 'add_permission', 'PUT': 'add_permission', 'DELETE': 'delete_permission'} def check_user_permission(permission, user, tag): # logic here return True/False class CustomBasePermissions(permissions.BasePermission): @abstractmethod def has_permission(self, request, view): pass class PermissionError(APIException): status_code = status.HTTP_403_FORBIDDEN default_detail = {'message': "You Don't have required permission"} class MapPermission(CustomBasePermissions): def has_permission(self, request, view): if request.role == "owner": return True else: permission = METHODS.get(request.method) return check_user_permission(permission, request.user, 'map') ''' decorators.py ''' def permission_decorator(permission_class): assert permission_class is not None, ( "@permission_decorator() missing required argument: 'permission_class'" ) def decorator(func): func.permission_classes = permission_class return func return decorator ''' -
Python - Covert enum to Django models.CharField choices tuple
I have this enum: class Animal(Enum): DOG = 'dog' CAT = 'cat' and in a Django model I have this: possible_animals = ( ("DOG", "dog"), ("cat", "cat"), ) animal = models.CharField(choices=possible_animals, ...) I know I can use the enum like this: possible_animals = ( (Animal.DOG.name, Animal.DOG.value), (Animal.CAT.name, Animal.CAT.value), ) but is there any other elegant dynamic way to convert the enum into this kind of nested tuple?