Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data from Django One to Many Fields Model using views into templates
I want to display 1 Parent Field with associated Child and further there Childs I have a Model class GrandParent(models.Model): name= models.CharField(max_length=50) .... class Parent(models.Model): parent = models.ForeignKey(GrandParent, on_delete=models.CASCADE) name= models.CharField(max_length=50) .... class Child(models.Models): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name= models.CharField(max_length=50) ... I am able to render objects from Grand Parent But I m unable to link further Parent Class objects and Child class objects in templates This approach I used in views.py def list(request): object_list = GrandParent.published.all() ... return render('app/list.html') def detail(request, post,): post = get_object_or_404(GrandParent, slug=post, status='published') return render(request, 'app/detail.html', {'post' : post, ... }) Now how to link further Classes in Same Detail View But Associated with there Parent Classes using Foreign Key. I'm following Django docs but they only giving max 2 examples using python shell with just One subclass I m confused How to implement there in this structure. Or anyone have already developed any project specifically with this type of models so please share any link of repo or something, would be wonderful. -
How can I move the Django URL requests from https:// to http:/?
All of the Django requests are directed to https:// but I want to direct all of my URL requests to http:// by default. Currently I have to manually remove s from every URL. Any solutions? -
Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. in Django
I'm getting this error whenever i'm trying to run my server locally. Here is how i've configured the allowed hosts: But it doesn't seem to work... ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["*", '127.0.0.1:8000']) -
Parsing an array of dictionnaries in a django for loop
In a Django application, I want to use a dictionary as elements of a result.html page: <tbody> {% for element in products%} <tr> <td>{{ element['q0']['Results'][0]['Name'] }}</td> </tr> {% endfor %} </tbody> But it returns Could not parse the remainder: '['q0']['Results'][0]['Name']' from 'element['q0']['Results'][0]['Name']': return render(request, 'todo/result.html', {'products': top_products}) File "C:\Python36\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Python36\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Python36\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Python36\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Python36\lib\site-packages\django\template\loaders\base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "C:\Python36\lib\site-packages\django\template\base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File "C:\Python36\lib\site-packages\django\template\base.py", line 193, in compile_nodelist return parser.parse() File "C:\Python36\lib\site-packages\django\template\base.py", line 478, in parse raise self.error(token, e) File "C:\Python36\lib\site-packages\django\template\base.py", line 476, in parse compiled_result = compile_func(self, token) File "C:\Python36\lib\site-packages\django\template\defaulttags.py", line 814, in do_for nodelist_loop = parser.parse(('empty', 'endfor',)) File "C:\Python36\lib\site-packages\django\template\base.py", line 449, in parse raise self.error(token, e) File "C:\Python36\lib\site-packages\django\template\base.py", line 447, in parse filter_expression = self.compile_filter(token.contents) File "C:\Python36\lib\site-packages\django\template\base.py", line 563, in compile_filter return FilterExpression(token, self) File "C:\Python36\lib\site-packages\django\template\base.py", line 663, in __init__ "from '%s'" % (token[upto:], token)) … -
Not understanding this Python script
in this example of Django project enter link description here, and in the templates section (book_detail.html), There is a code i do not understand: book.genre.all|join:", " "book.genre.all" are List of all objects from the Genre class that are connected to the book object (from Book class) by a ManyToMany key. why using pipe character for join or split these objects ? and why dont use ", ".join(book.genre.all) ? -
Using Django ORM in plain python script / infinite task
I have application in plain python with some basic libraries. I'm looking to use Django as main framework for this application and maintain frontend. My question is, can I still use my already written application and switch to Django ORM and maybe controlling the application via some callbacks. This application is running infinitely with asincio library. Or is there any way how to run background tasks in Django? I found celery but I'm not sure about starting this process. Maybe use of some Django commands and supervisor. TLDR: I need some way of running background task (command, controller, python script) infinitely long without user interaction. -
Django Querry Include Join
I tried to calculate the count of the increased and decreased competitor product price which are related to products. I couldn' handle it. Can I do this by overriding get_context_data method? I couldn't write a querry to get the data from comp_product model. How can I handle this? models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products') category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products") competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) view: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Products = context['object_list'] context['distinct_category_count'] = Products.values('category').distinct().count() context['distinct_brand_count'] = Products.values('brand').distinct().count() context['product_count'] = Products.values('product').count() context['out_of_stock'] = Products.filter()values('stock').count() return context -
Min_value, max_value validation doesn't work if i use widget for FloatField
For use a custom css class in a input text, I had to add a widget. But now validation in django forms doesn't work anymore. class NewBind(forms.Form): new_bind=forms.FloatField(max_value=999999.99,min_value=1, widget=forms.TextInput(attrs={'class' : 'mk-off-inp'})) In this case validation doesn't works class NewBind(forms.Form): new_bind=forms.FloatField(max_value=999999.99,min_value=1) In this case validation works but i've lost css I also tried to add min e max inside widget but validation still not working -
provider-agnostic oauth2 library for django
I am looking for a django library, that can support oauth2 authentication, which is not specific to any provider. I tried django-allauth, social-auth libraries, but cant find anything general-purpose. -
Password validation not work in django-rest-framework
when I register new user at that time password validator not work.(e.g. When I enter admin123 and password is also admin123 at that time password validator not saw like this error: password must not same as username.) serializer.py: from rest_framework import serializers from django.contrib.auth import get_user_model User = get_user_model() class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password'] write_only_fields = ('password',) read_only_fields = ('id',) views.py: from rest_framework import status from django.contrib.auth import get_user_model from .serializers import SignUpSerializer from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError User = get_user_model() @api_view(['POST']) @permission_classes([AllowAny,]) def signup(request): serializer = SignUpSerializer(data=request.data) if serializer.is_valid(): username = serializer.data['username'] try: validate_password(serializer.data['password'], username) except ValidationError as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) user = User( username = username, email = serializer.data['email'] ) user.set_password(serializer.data['password']) user.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thanks. -
How is this done to work in production, Django
I have a Django rest API. The API consumes Google Vision Api. When I try a call with a local file on localhost, it works just perfectly. However, when I do the same in production on a live server, the file is not found. Basically, what am doing is getting a local file path to do the vision API query like this: http://localhost:8000/api/search/image?q=/Users/user/Documents/graphics/images/testlogo.png That works fine. But if I try the same thing when the site is live in production http://vesm.com/api/search/image?q=/Users/user/Documents/graphics/images/testlogo.png I get a file not found exception. So my question is, how do I do a get request with a locally stored image? I am trying to create an image search API. What I have been doing is when someone picks a file, I get the local file path, as vision API just requires the file path. Any guide here will be helpful. -
How to pass request user to serializer in UpdateApiView with partial_update?
I have view like below. I have edited_user in my model . I want to pass current_user to serializer and in serializer I will override update() function. Problem is I cant find way to pass current user. Can Anyone help ? class Update(UpdateAPIView): serializer_class = serializer_class queryset = model.objects.all() def put(self, request, *args, **kwargs): if self.request.user.field == 1: return self.partial_update(request, *args, **kwargs) -
HTML autocomplete is not working along with Django extension in VSCode
I am currently using the latest version of VSCode and Django. Whenever I enable the Django extension by Baptiste Darthenay, HTML autocomplete stops working. If I disable the Django extension and reload VSCode, it will start to work again. What should I do to make the HTML autocomplete work along with the Django extension? -
What is acess_token and code in google auth?
I am trying to implement google authorization in django rest. I followed this instruction, but I can't figure out what code and access_token are. Where can I get them? -
Django rest framework - how can i limit requests to an API endpoint?
I created an API using Django Rest Framework, now i'm working on a rate limiting system, to avoid spam. The built-in throttling system works great, and i managed to add multiple throttles: REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES': ( # "xapi.authentication_backends.TokenBackend", # ), 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '70/minute', 'user': '70/minute', 'user_sec': '2/second', 'user_min': '120/minute', 'user_hour': '7200/hour', }, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } And in my views.py: class UserSecThrottle(UserRateThrottle): scope = 'user_sec' class UserMinThrottle(UserRateThrottle): scope = 'user_min' class UserHourThrottle(UserRateThrottle): scope = 'user_hour' So if some user performs more than 120 queries in a minute, that user will be blocked for a minute, if the hour limit is breached, the user is blocked for one hour. Is there some way to decide for how much is a user blocked? For example, if i want to block someone for 10 minutes if they perform more than 120 queries in a minute. Any advice is appreciated. -
ImportError: cannot import name 'routers' from 'rest_framework'
I just started learning the Django REST framework. I'm trying to complete the Quickstart in the official docs. I am getting this error: Exception in thread django-main-thread: Traceback (most recent call last): File "F:\Python\lib\threading.py", line 932, in _bootstrap_inner self.run() File "F:\Python\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "F:\Python\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "F:\Python\lib\site-packages\django\core\management\commands\runserver .py", line 118, in inner_run self.check(display_num_errors=True) File "F:\Python\lib\site-packages\django\core\management\base.py", line 392 , in check all_issues = checks.run_checks( File "F:\Python\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "F:\Python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "F:\Python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 408, in c heck for pattern in self.url_patterns: File "F:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 589, in u rl_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_modul e) File "F:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\Python\lib\site-packages\django\urls\resolvers.py", line 582, in u rlconf_module return import_module(self.urlconf_name) File "F:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File … -
python django queryset merge
I got a problem here and I know you are my saviors... This is the query... flights_table = Flight.objects.values('station__station_name', 'flight_date__month').annotate( flights_number=Count('id')).filter(flight_date__year=datetime.date.today().year).order_by('airline_name') This is the result.. <QuerySet [{'station__station_name': 'ROME', 'flight_date__month': 2, 'flights_number': 1}, {'station__station_name': 'ROME', 'flight_date__month': 2, 'flights_number': 1}]> All I need is to convert the result into this.. [{'station__station_name': 'ROME', 'flights_number' :[0,2,0,0,0,0,0,0,0,0,0,0]}, {'station__station_name': 'PARIS', 'flights_number' :[0,2,0,6,0,12,0,0,0,0,0,0]}] mixing all the 'station__station_name' which has the same name together arranging the list of the values of 'flights_number' based on 'flight_date__month' and months of the year sum 'flights_number' with same 'flight_date__month' and same 'station__station_name' I know it's complicated but I think it's not impossible , I appreciate it -
Run docker with django html button
1-this is my html code <i class="tim-icons icon-laptop" (click)="makeCallToFoo()" style="cursor: pointer; color: #1d8cf8" rel="tooltip" title="View Machine Details"></i>&nbsp;&nbsp; <i class="fa fa-edit" (click)="makeCallToFoo()" style="cursor: pointer; color: #00f2c3" rel="tooltip" title="Write Review"></i>&nbsp;&nbsp; <button onclick="location.href='{% url 'script' %}'" type="button" class="btn btn-danger btn-sm" id="btn2" (click)="changeBtn('btn2')">Off</button> 2- this is urls code path('', views.button), path('output/', views.output, name="script") 3- this is view file def button(request): return render(request, 'home.html') def output(request): data=requests.get("dockerscript/start.py") print(data.text) data=data.text return render(request, 'home.html', {'data':data}) how can i run start.py script through html code that is above -
Django: Database Keys regularly out of sync
I'm running a django app with postgresql in production. I noticed that the database indicies get regularly out of sync after some time, but I couldn't figure out exactly when this happens. Can somebody share a good workflow to find out how this happens or how to prevent this? The customer isn't really happy about this :). I "fixed" it now by running ./manage.py sqlsequencereset every hour by cron and in my deployment script, but this solution looks a bit awkward to me. I use Django 3.1.4 and postgresql 10.14 -
How to get id field from model class in Django using Class-based views
I am using DeleteView in order to allow users to delete their own uploaded images. I want that by clicking on Html link, users will get redirected to the DeleteView confirmation page to delete their images. Problem is that i am getting the next error when trying to display the HTML with the link. Reverse for 'deletegaleria' with arguments '('',)' not found. 1 pattern(s) tried: ['galeria/delete/(? P<pk>[0-9]+)$'] 1.- I know this error is in the template that has the link and it's in this line. <a href="{% url 'deletegaleria' object.id %}"> Sure you want to delete?</a> 2.- If instead i write like this, with the id of the image, i get no error when displaying the HTML <a href="{% url 'deletegaleria' 14 %}"> Sure you want to delete?</a> So in the first example i try to redirect to the url by passing it the id, which was supossedly gotten on the view.py: class imagenDeleteView(DeleteView): model = imagen success_url = reverse_lazy("galeria") def getid(self, request): self.get_object() My urls.py looks like this: urlpatterns = [ path('', views.galeria, name='galeria'), path('delete/<int:pk>', views.imagenDeleteView.as_view(), name='deletegaleria'), ] -
Im trying to get the table from this website and the links of one row [closed]
i need to get all the td texts but find a href get just the link exemple Text result = Text Text2 result = http://test.com import requests import bs4 url = 'https://ticker11.com.br/emissoes/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} data_scraped = requests.get(url=url, headers=headers) soup = bs4.BeautifulSoup(data_scraped.text, features='html.parser') data = soup.find('table') soup = bs4.BeautifulSoup(data_scraped.text, 'html.parser') table_andamento = soup.find('table', {'id': 'tablepress-6', }) headers = [heading.text.replace("Fundo", "Fundo") for heading in table_andamento.find_all('th')] removetable = str.maketrans('', '', '@#%-?/()$ ') out_list = [s.translate(removetable) for s in headers] table_rows = [row for row in table_andamento.find_all('tr')] results_andamento = [{out_list[index]: cell.text for index, cell in enumerate(row.find_all("td"))} for row in table_rows] print(results_andamento) -
Error when deplyoing Django-React app to Heroku
I'm deploying my Django-backend, React-frontend app to Heroku and when running git push heroku master I'm running into a weird error: Could not find a required file. Name: index.html Searched in: /tmp/build_7abd977a/public This is my project frontend structure: As you can see the index.html file is there inside the public folder. There is also a build folder that has no public folder inside it but it does also have the same index.html but compressed. Maybe thats the one its looking for? -
Django block page title
I'm trying to create a custom page title for each page but I've not been successfull. The following is the general setup for all my html pages (And what I thought would work; it doesn't) and would appreciate any solutions. head.html something something <title>{% block title %}Default Value{% endblock title %}</title> something something base.html <!DOCTYPE html> <html> {% include "head.html" %} <body> {% include 'header.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html> 404 html file {% extends 'base.html' %} {% load static %} {% block title %}404{% endblock title %} {% block content %} <div id="main404"> <div class="fof"> <h1>Error 404 :(</h1> </div> </div> {% endblock content %} Currently it still displays the default value indicated in head.html. I would like to customise the page title of each page using the block as attempted above. Thanks. -
JavaScript it's not running in page from a .js file
I have a problem with some scripts of JavaScript. I render on my page some charts from Charts.js, the values for the charts are sent from the backend with some view functions from Django, these function return a JsonResponse, on the urls which are connected with these functions are sending some array which contains a hash-map aka json file that contains the values for the charts fields. With Ajax I take those values from the urls and inject them in JavaScript code that handles the charts rendering. If I put the JavaScript code in a .js file and call the file in HTML it doesn't work, if I put the JS code in a <script> tag it works. How can I put the code into a file? The JS code: // Set new default font family and font color to mimic Bootstrap's default styling Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; Chart.defaults.global.defaultFontColor = '#858796'; function number_format(number, decimals, dec_point, thousands_sep) { // * example: number_format(1234.56, 2, ',', ' '); // * return: '1 234,56' number = (number + '').replace(',', '').replace(' ', ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === … -
Why does it says array.fillter is not a function
I'm making an todolist and each list has checkbox and if user clicks checkbox it calls function below. and when i clicked the checkbox, the console said span.filter is not a function. Please help. It's BOTHERING me. Code: function controlCheck(event) { let ischecked = event.target.checked; const checkobj = { checked: ischecked, }; const span = document.querySelectorAll(".span"); const veryspan = span.filter((e) => e.id === event.target.id); }