Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I render content page to another html page
I have already base.html page. How I can get my specific contact page information into my home page with jinja -
Is it possible to check if a function has a decorator from a class attribute in DRF and Django?
I'm currently thinking of how to implement permissions in my Django application using DRF. My idea is to have several generic classes that inherit BasePermission and to define those classes in the view, ex: class ExampleView(ModelViewSet): permission_classes = (ExamplePermissionClass,) However, this might not suffice for some views that I have i.e. I might declare a generic class on the whole view but I might also want one @action to use different permissions. For this, I though of making decorator permissions which would check permissions on a per method basis. However, I do think that permission_classes are executed first and this won't work. Is there a way arround this? Example: class ExampleView(ModelViewSet): permission_classes = (ExamplePermissionClass,) @permissions(PermissionName etc...) @action(...) def example_action How can I circumvent the permission class and only check the decorator here? -
Use an existing HTML Template Form and submit data through Django
I'd like to make a POST REQUEST with an existing HTML FORM, to store it in a database, but everytime I tried to submit data through the form, it doesn't do nothing. it doesn't add data to the database. What should I do? By the way I'm doing this following those post: Django form using HTML template MultiValueDictKeyError generated in Django after POST request on login page Registro.html {% extends "RegistrarProyecto/layout.html" %} {% block title %} {% endblock %} {% block content %} <h1>Crear Usuario</h1> <form class="CrearUsuario" action="{% url 'registro' %}" method="POST"> {% csrf_token %} <input type="text",name="NombreProyecto", placeholder="Nombre del Proyecto" > <br> <br> <input type ="text", name="ResponsableProyecto", placeholder ="Responsable del proyecto"> <br> <br> <textarea name="DescripcionProyecto", rows="4", cols="50"></textarea> <br> <br> <input type="submit" value="Registrar"> </form> <br> <a href="{% url 'index' %}">Ir a Bienvenido</a> {% endblock %} views.py def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') NombreProyecto = request.POST.get('ResponsableProyecto') NombreProyecto = request.POST.get('DescripcionProyecto') return render(request, 'RegistrarProyecto/Registro.html') else: return render(request, 'RegistrarProyecto/Registro.html') models.py from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" class Evaluador(models.Model): NombreEvaluador = models.CharField(max_length=64) Proyecto = models.ManyToManyField(Proyecto, blank=True, related_name="Evaluador") def __str__(self): return … -
How to connect jupyter-lab in my Django project to the Django's models?
I am a bit new to Django and was wondering on how to do this. I have a jupyter-lab called forecasting.ipynb in the same folder as my manage.py and db.sqlite3. I want to connect to the db.sqlite3 to access the models that are in my models.py. I have a model called Coin. I want to basically be able to do Coin.objects.all() and access all my coins but I'm a bit confused on how to do this. In my jupyter-lab file I have this: forecasting.ipynb import sqlite3 connection = sqlite3.connect('db.sqlite3') for row in cur.execute('SELECT * FROM Coin;'): print(row) connection.close() I tried this but it says 'OperationalError: no such table: Coin'. I also tried both coin and COIN as well but both didn't work. I'm really confused because I have a model called Coin in my models.py. models.py from django.db import models class Coin(models.Model): ticker = models.CharField(primary_key=True,max_length=10, unique=True) baseVolume = models.BigIntegerField(default=0) coin_name = models.CharField(default="", max_length=50) coin_description = models.TextField(default="") # price = models.FloatField() def __str__(self): return "{}-{}".format(self.ticker,self.baseVolume) And when I do Coin.objects.all() in my tasks.py, it works perfectly. Is my syntax/code wrong or am I misinterpreting something? Thank you so much! -
Django: Corresponding values to String options
Let's say, I have a hotel booking form and I want to have 'room types' with different prices. Then after selecting a room type, I add its corresponding price to the Total Price. So my questions are: How do I make such option list with corresponding prices, where I can use the price and add it to the total? (maybe through javascript). Right now, I have the models & forms set up, and the javascript code for adding the other option (one being an input field for no. of nights, and another being a checkbox for including breakfast). I was thinking of using a list of tuples, but I don't particularly know how to implement it. -
Populate Django database(SQL)
I am learning Django, a little difficult for me, so i have some problem with Fields M2M, OTO, FK and i'm stuck, I'm trying to fill in the database(SQL), everything seems to work, but there is an intermediate field authors = models.ManyToManyField(Author) book_authors this table is empty, read the documentation, didn't help :p models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField('date published') class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) admin.py from django.contrib import admin from annotate_aggregate.models import Author, Publisher, Store, Book admin.site.register(Author) admin.site.register(Publisher) admin.site.register(Book) admin.site.register(Store) management/commands/seed.py class Command(BaseCommand): def handle(self, *args, **options): User.objects.filter(~Q(is_superuser=True) | ~Q(is_staff=True)).delete() Publisher.objects.all().delete() Book.objects.all().delete() Store.objects.all().delete() authors = [Author(name=fake.name(), age=random.randint(20, 70)) for _ in range(1, 6)] Author.objects.bulk_create(authors) # create 5 publishers publishers = [Publisher(name=fake.company()) for _ in range(1, 6)] Publisher.objects.bulk_create(publishers) # create 20 books for every publishers books = [] counter = 0 for publisher in Publisher.objects.all(): for i in range(20): counter = counter + 1 books.append( Book( name=fake.sentence(), price=random.uniform(29.99, 225.9), pages=random.randint(50, 300), rating=round(random.uniform(1, 5), 2), pubdate=timezone.now(), publisher=publisher) ) Book.objects.bulk_create(books) # create … -
django-haystack relevants suggestions
I'm using Django-haystack + Elasticsearch. I have INCLUDE_SPELLING set to True and {{ suggestion }} tag in my template. When for example I search for émile zola I get émile zozo (which doesn't exist in the index or db) as suggestion instead of emile zola. Anyway to fix this? Thanks -
Google Cloud Video Intelligence Annotate Video JSON vs example code
Google Cloud Video Intelligence provides the following code for parsing annotation results with object tracking: features = [videointelligence.Feature.OBJECT_TRACKING] context = videointelligence.VideoContext(segments=None) request = videointelligence.AnnotateVideoRequest(input_uri=gs_video_path, features=features, video_context=context, output_uri=output_uri) operation = video_client.annotate_video(request) result = operation.result(timeout=3600) object_annotations = result.annotation_results[0].object_annotations for object_annotation in object_annotations: print('Entity description: {}'.format(object_annotation.entity.description)) print('Segment: {}s to {}s'.format( object_annotation.segment.start_time_offset.total_seconds(), object_annotation.segment.end_time_offset.total_seconds())) print('Confidence: {}'.format(object_annotation.confidence)) # Here we print only the bounding box of the first frame_annotation in the segment frame_annotation = object_annotation.frames[0] box = frame_annotation.normalized_bounding_box timestamp = frame_annotation.time_offset.total_seconds() timestamp_end = object_annotation.segment.end_time_offset.total_seconds() print('Time offset of the first frame_annotation: {}s'.format(timestamp)) print('Bounding box position:') print('\tleft : {}'.format(box.left)) print('\ttop : {}'.format(box.top)) print('\tright : {}'.format(box.right)) print('\tbottom: {}'.format(box.bottom)) print('\n') However, I want to parse the json file that is generated via output_uri. The format of the json file is as following : { "annotation_results": [ { "input_uri": "/production.supereye.co.uk/video/54V5x8q0CRU/videofile.mp4", "segment": { "start_time_offset": { }, "end_time_offset": { "seconds": 22, "nanos": 966666000 } }, "object_annotations": [ { "entity": { "entity_id": "/m/01yrx", "description": "cat", "language_code": "en-US" }, "confidence": 0.91939145, "frames": [ { "normalized_bounding_box": { "left": 0.17845993, "top": 0.44048917, "right": 0.5315634, "bottom": 0.7752136 }, "time_offset": { } }, { How can I use the example code to parse the JSON that is provided with output_uri ? What kind of conversion is needed for this … -
Identify updated field in update or create django
How do I detect which data has been updated and which has been created in a MyModel.objects.update_or_create() method? try: new_data = MyModel.objects.update_or_create( data_1 = active_sheet["{}{}".format("A", row)].value, data_2 = active_sheet["{}{}".format("B", row)].value, ) # default url url = reverse('admin:index') + 'some-url/' # if some users were only updated, not uploaded # pass the updated data to custom template # return the current page with a table of the entries that were not added self.message_user(request, 'Tagged Profile uploaded.') # redirect to selected url return HttpResponseRedirect(url) except Exception as e: messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e) -
How to give access to only specific group of user for login - django
I'm struggling with login for users from specific django group , unfortunately any group user is able to login without knowing whether he belongs to a group or not. def loginstaff(request): if not request.user.is_authenticated: if request.method == "POST": fm= AuthenticationForm(request=request, data=request.POST) if fm.is_valid(): uname= fm.cleaned_data['username'] upass= fm.cleaned_data['password'] User = authenticate(username=uname,password=upass) if User is not None: login(request,User) messages.success(request,'Logged in Successfully..!') return HttpResponseRedirect('/staffprofile/') else: fm=AuthenticationForm() return render(request,'loginstaff.html',{'form':fm}) else: return HttpResponseRedirect('/staffprofile/') I created only two groups. help me with my code guys, but in brief:) bcz im just learning. thanks -
Zabo create_user api
I'm trying to use the Zabo rest api for create user which can be found here: https://zabo.com/docs/?shell#create-a-user The api says to do this (copied and pasted here): curl "https://api.zabo.com/sandbox-v1/users" \ -X POST \ -H "X-Zabo-Key: adminApiKey-established-in-dash" \ -H "X-Zabo-Sig: signature-of-request-using-paired-secret-key" \ -H "X-Zabo-Timestamp: 1420069800000" \ -d '{ "id": "8b0a037f-67cb-44b7-ac2a-18e7a54561a8", "token": "zabosession-abcdef1234567890" }' I'm doing this in Python: def _get_signature_and_time(self, url, body, secret): mtime = round(time.time() * 1000) json_body = json.dumps(body) logger.info(mtime) logger.info(url) logger.info(secret) logger.info(json_body) text_value = "%d%s%s" % (mtime, url, json_body) logger.info(text_value) signature = hmac.new(bytes(secret, "UTF-8"), bytes(text_value, "UTF-8"), hashlib.sha256).hexdigest() return signature, mtime I keep getting a different signature than what their library (currently only available in nodeJS) is providing. However, I'm doing it as per documentation. Is there something im missing here? -
Appending parameters to a form
Let's say I have the following: form = MyForm(request.POST or None, request.FILES or None, instance=instance) One the form variable has been established, how would I append the following to it initial = {'my_id': my_id} initial can't be added to the form declaration for various reasons that are specific to my project. THanks! -
django for professionals book
I am currently on page 241 of the "Django for professionals" book. Adding command gunicorn config.wsgi -b 0.0.0.0:8000 to docker-compose-prod.yml made it impossible to rebuild docker image with docker-compose up -d --build command, error is yaml.scanner.ScannerError appears : mapping values are not allowed here in ". \ docker-compose.yml", line 7, column 12. Is this a bug of the author of the book? version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn config.wsgi -b 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=ldBHq0YGYxBzaMJnLVOiNG7hruE8WKzGG2zGpYxoTNmphB0mdBo" db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: -
Django Model Field Inline
In Django, you can use inline to make new instances of models by just clicking the add instance button on the bottom of the admin site. Is there a way to do this for a model field inside a model. For example, if you were cataloging a book and you want to capture all the chapters in each books name. Every book has a different number of chapters so you could not just do chapter1 = CharField(max_length = 200) chapter2 = CharField(max_length = 200) and so on. Like the picture below but not for model instances for model fields. -
request.user.is_authenticated is false on certain HTML on certain pages but not in views
Most pages on this website I'm creating for practice {% if request.user.is_authenticated %} go through as true. But there is one page that always returns this as false (i've pasted that section of code below)... Even though in views.py the function that controls that page, show when I run print(request.user.is_authenticated) outputs: true html: {% extends "page0/layout.html" %} {% load static %} {% block body %} <h2>{{ listing.listingTitle }}</h2> {% ifequal listing.validURL listing.valid %} <img src="{{listing.picture}}" alt="picture!" style="width:150px"> {% else %} <img src="https://www.drupal.org/files/issues/2018-07-26/no%20thumbnail%20found%20suggestion.png" alt="no picture!" style="width:150px"> <p>NOTE: no image provided</p> {% endifequal %} <p>{{bidPrice}} $</p> {% if user.is_authenticated %} <form action="{% url 'bid' listing.listingTitle %}" method = "post"> {% csrf_token %} {{form2}} <input class="btn btn-primary" type="submit" value="button"> </form> {% else %} Not signed in. <a href = "\register">Sign in or create an account </a> {% endif %} </div> {% endblock %} views.py: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from markdown import Markdown from django.contrib.messages.api import success from django.contrib import messages import os.path from .models import User import datetime import time import validators import requests from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404 from django import forms … -
django custom template tag, pass multiple arguments
I need to be able to pass multiple parameters to a custom template tag. I dont know how to do it but I've seen an example like this somewhere. If you got the idea, is it possible to do it in some way? template {% for right in people_rights|user_available_rights:rooms, user.id %} {{right.room}} {% endfor %} template tag def user_available_rights(rights, rooms, user_id): available_rights = [] user_rooms = [] for right in rights: if right.user.id == user_id: user_rooms.append(right.room) for room in rooms: for ur in user_rooms: if room.id != ur.id: available_rights.append(room) return available_rights -
Adding parameters into formset declaration
I'm building a formset based on a few variables FormSet = eval("modelformset_factory(TemplateModel, form=%s, extra=extra, max_num=max_forms, can_delete=True)" % formname) I want to pass some perameters into this FormSet variable so that I can pick them up in my forms.py form_kwargs={'user': user} How would I add these forms_kwargs perameters into the first line of code? -
Whenever user signs up smtp authentication error is thrown in django
While signing in smtp error is thrown.I have On the less secure apps still the error is thrown Smtp Error on the Screen -
How to update folium map with javascript
I have a map generated by folium with python. The hml and JavaScrip code are in the snippet. I have added a drop down list. I would like to change the color of line when selecting 'Lanes (input)' value. For example here : all lines with number of lanes = 1 will be colored in green all lines with number of lanes = 2 will be color in blue etc How can I do that ? Here is the ouput generated by folium <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script> L_NO_TOUCH = false; L_DISABLE_3D = false; </script> <style>html, body {width: 100%;height: 100%;margin: 0;padding: 0;}</style> <style>#map {position:absolute;top:0;bottom:0;right:0;left:0;}</style> <script src="https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/python-visualization/folium/folium/templates/leaflet.awesome.rotate.min.css"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <style> #map_8a24bb442b2741ed8240d6265f6ae4a8 { position: relative; width: 100.0%; height: 100.0%; left: 0.0%; top: 0.0%; } </style> </head> <body> <div class="folium-map" id="map_8a24bb442b2741ed8240d6265f6ae4a8" ></div> </body> <script> var map_8a24bb442b2741ed8240d6265f6ae4a8 = L.map( "map_8a24bb442b2741ed8240d6265f6ae4a8", { center: [0, 0], crs: L.CRS.EPSG3857, zoom: 1, zoomControl: true, preferCanvas: true, } ); function geo_json_b105cf0f04474ba9b67fc8685c26a8ae_styler(feature) { switch(feature.id) { case "(1, 2)": case "(1, 3)": case "(1, 4)": case "(1, 5)": … -
How to add different domain to a URL path in django-rest-frame-work?
My endpoints and front end domain names are different. I've an email-verify endpoint which has a url https://test.com/email-verify?token=TOKEN. My front end url is https://trial.com. Currently, I'm sending an email to user with test url. I want to change it to https://trial.com/email-verify?token=TOKEN. I'm a bit stuck to come up with a way to do it. urls.py: from authentication import views from django.urls import path from rest_framework_simplejwt.views import ( TokenRefreshView, ) urlpatterns = [ ... path("email-verify", views.VerifyEmail.as_view(), name="email-verify"), ... ] view.py: ... class VerifyEmail(views.APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( "token", in_=openapi.IN_QUERY, description="Description", type=openapi.TYPE_STRING, ) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request): token = request.GET.get("token") try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) user = User.objects.get(id=payload["user_id"]) if not user.email_verified: user.email_verified = True user.save() return response.Response( {"email": "Successfully activated"}, status=status.HTTP_200_OK ) except jwt.ExpiredSignatureError as identifier: return response.Response( {"error": "Activation Expired"}, status=status.HTTP_400_BAD_REQUEST ) except jwt.exceptions.DecodeError as identifier: return response.Response( {"error": "Invalid Token"}, status=status.HTTP_400_BAD_REQUEST ) ... -
Adding Nodejs to Django
I hope this post doesn't get removed for not being specific enough but I am trying to get regular barcodes read in a Django project and I am not finding a way to do it that matches my ability to implement it in the time that I have allotted. I see a lot of ways to do it using Nodejs and I really don't want to add another framework for just this one function but I am not seeing any other way to do it that has good browser support. My specific question is: is this a bad route to take or is it common practice to add another framework like this? -
Monkeypatch in a Django TestCase
I want to test a view which call an API and to do this, I need to use monkeypatch, but the method only take 1 positionnal argument : "self", what should I do ? (What I want to do should be pretty clear on my code) class SearchCompanyTestCase(TestCase): def setUp(self): user = User.objects.create_user('temporarySC', 'temporarySC@gmail.com', 'temporarySC') user_info = UserInfos.objects.create(user=user, address='address', latitude='45.7595253', longitude='45.7595253') test_rome_code = RomeCode.objects.create(code='ABC24') TradeToRomeCode.objects.create(job_name='test', job_code=test_rome_code) user_info.job_code = test_rome_code user = authenticate(username='temporarySC', password='temporarySC') def test_api_valid_token(self, monkeypatch): class Token: status_code = 200 content = json.dumps({ "access_token": "wehqh8238eg2q8ge8" }).encode() data = json.dumps({ "companies": [{ "distance": 2, "headcount_text": "6 à 9 salariés", "lat": 48.97609, "city": "PAGNY-SUR-MOSELLE", "naf": "4711D", "name": "LIDL", "naf_text": "Supermarchés", "lon": 5.99792, "siret": "34326262214546" }], "companies_count": 1}).encode() def mockreturnToken(request): return Token def mockreturnData(request): return data monkeypatch.setattr(requests, 'post', mockreturnToken) monkeypatch.setattr(requests, 'get', mockreturnData) response = self.client.post(reverse('main_platform:searchCompany')) self.assertEqual(response.context['companies'], [{'distance': 2, 'headcount_text': '6 à 9 salariés', 'lat': 48.97609, 'city': 'PAGNY-SUR-MOSELLE', 'naf': '4711D', 'name': 'LIDL', 'naf_text': 'Supermarchés', 'lon': 5.99792, 'siret': '34326262214546'}]) self.assertEqual(response.context['companies_count'], 1) -
Is it better to make separate django models, or add various foreign keys to one model?
I have a model to capture comments from a user, DocumentComment. The comments are tied to a particular document in the database, and created/edited/displayed on the page that displays that particular document: class DocumentComment(Model): """ Captures a user's comment about a document """ document_id = models.ForeignKey(Document, on_delete=models.CASCADE, verbose_name="document file name", related_name='document') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField('comment', blank=True) moderated = models.BooleanField(default=False) added_to_description = models.BooleanField(default=False) marked_for_deletion = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") I now find I need to record comments based on other objects displayed on different pages in the site, e.g. albums (collections of document) is a page and word clouds (derived from all the words in various documents) is another page. Since these new comments are not tied to one document, but a collection of documents, I don't think they should be added to the DocumentComment model for every document_id in the collection. I wouldn't necessarily want the comments on a collection to be displayed on the page with one of the documents in that collection. Which approach is better (django-yy or pythonic or idiomatic or by whatever standard you choose): create separate models as above for each display object … -
Is it possible to recreate an app in django with only the migrations?
I have a set of Django migrations without the models of a Django app. Is it possible to recreate the models automatically with the migrations? -
Autofill my author field with foreign key
I am trying to autofill my user foreign key in my note project with authentication in django. I tried, but it's not working and asking that owner is required field. Please, help! Thanks in an advance. views.py @login_required(login_url='login') def index(request): tasks = Task.objects.filter(owner=request.user) form = TaskForm() if request.method=='POST': form = TaskForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.owner = request.user instance.save() context = { 'tasks':tasks, 'form':form, } return render(request, 'list.html',context) models.py class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.title