Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use views like an AJAX call in django?
I have a Django app as shown in image I want to use the delete icon to show confirmation popup and then delete the selected entry from the database. In general, I would use AJAX call and JS for this. How can I achieve this in Django? Template code: index.html <!DOCTYPE html> {% load staticfiles %} {% load pm_extras %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Portfolio</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'portfolio_management_statics/css/style.css' %}"> </head> <body> <div class="container"> <h1>Portfolio</h1> <form method="post">{% csrf_token %} <!-- <label for="stock-name">Stock Name: </label><input id="stock-name" name="stock-name" type="text">--> <!-- <label for="trans-price">Transaction Price </label><input id="trans-price" type="number">--> <!-- <label for="trans-date">Transaction Date </label><input id="trans-date" type="date">--> <!-- <label for="quantity">Quantity </label><input id="quantity" type="number">--> {{ stock_add_form.as_p }} <input type="submit" value="Add Stock"> </form> </div> <div class="container"> <table> <tr> <th>Stock Name</th> <th>Transaction Price</th> <th>LTP</th> <th>Transaction Quantity</th> <th>Transaction Date</th> <th>Invested Value</th> <th>Current Market Value</th> <th>Capital Gains</th> <th>Capital Gains %</th> <th></th> </tr> {% for stock in portfolio %} <tr> <td>{{ stock.stock_name }}</td> <td>{{ stock.trans_price1 }}</td> <td>{{ stock_ltps | dict_key:stock.stock_name }}</td> <td>{{ stock.trans_quantity1 }}</td> <td>{{ stock.trans_date }}</td> <td>{{ stock_invested_value | dict_key:stock.stock_name }}</td> <td>{{ stock_current_value | dict_key:stock.stock_name }}</td> <td>{{ stock_gains | dict_key:stock.stock_name }}</td> <td>{{ stock_gains_per | dict_key:stock.stock_name }} %</td> … -
How to compress a field of django model?
One of my models has a field where I store very large arrays. My frontend app has to load all of them at once which makes the request response a bit slow. I was thinking of compressing the arrays in the backend and decompressing in my react frontend application, is it possible? -
How to Customize Django-allauth and templates?
Is there any tutorial on how to customize django allauth templates and fields I know how to use with existing allauth and add fields. But I would like to learn about customizing templates completely like changing order and other ? -
How to retrieve Jenkins job for a user when google authentication is enabled on jenkins and django application
I have a installed Jenkins on a machine and enabled Google authentication so that it can be restricted to domain. There is a small screen built within django app for job actions which also uses google authentication There is a mistake done by using a constant id with api token between django app and jenkins app. Could someone help me out how i could enable users dynamically (I am currrently using jenkinsapi ) using google authentication so that once a user logs into django app should be logged into jenkins and fetches these jobs with the logged in user id (google mail id) -
Using context variable to name a "section" instead of passing a value
In the following view, the context variable is used to mark the 'section' as 'dashboard'(I think). @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) This then allows me to say {% if section == 'whatever' %}, for example: {% if request.user.is_authenticated %} <ul class = 'menu'> <li {% if section == 'dashboard' %} class='selected' {% endif %}> <a href="{% url 'dashboard' %}">My Dashboard</a> </li> ... continues </ul> {% endif %} Now if the dashboard view is called, .selected will be applied to the 'Dashboard' link (change color to show it's active). I get what it is doing, just don't understand how this works. I have only seen values passed in the context i.e. {'number': 8}. How exactly does django keep track of this naming system? It does not seem to be adding a class or anything of the sorts. -
Django Rest Framework relationship queries in nested serializer
I am having difficulties in implementing nested serializers in Django REST Framework. I'm building an Online score board, for which I currently have three models and I'm trying to serialize it into a single response. models.py class Player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.first_name class Event(models.Model): user = models.ManyToManyField("Player") name = models.CharField(max_length=50) desc = models.CharField(max_length=225) def __str__(self): return self.name class LeadBoard(models.Model): """model for LeadBoard""" player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='leadboard_player', null=True, blank=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='leadboard_event', null=True, blank=True) score = models.IntegerField() def __str__(self): return self.score The event model represent some kind of sports events and each Event can have multiple Players (user filed in Event model), the LeadBoard model stores the score of players in each event. serializer.py class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ('id','first_name', 'last_name', 'bio') class EventSerializer(serializers.ModelSerializer): user = PlayerSerializer(read_only=True, many=True) class Meta: model = Event fields = ('id', 'name', 'user', 'desc') class LeadBoardSerializer(serializers.ModelSerializer): event = EventSerializer(read_only=True) class Meta: model = LeadBoard fields = ('id', 'event', 'score') I have added two Players [ { "id": 1, "first_name": "Jhon", "last_name": "Doe" }, { "id": 3, "first_name": "Anna", "last_name": "Doe" } ] and their scores in LeadBoard model [ { "id": 1, "player": … -
Better environment to develop a Wagtail-based website
I'm going to develop a Wagtail-based website in Windows. If Linux is a better production environment, should I use a subsystem for Linux, a virtual machine for Linux, or docker in development? -
python for backend web app development with flask or django
getting started in the backend in python for web development and wondering what is the best option for web app development: Flask or Django? Also, consider that i am using POSTGRESQL. -
VS Code Django Debugger TemplateDoesNotExist
Using VS Code as my IDE for Django programming. I'm able to start my application via the integrated terminal by running 'python app/manage.py runserver 8000'. This starts no problem. In my launch.json file i have "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/app/manage.py", "console": "integratedTerminal", "args": [ "runserver", "8000", "--noreload", "--nothreading" ], "django": true When i start debugging using F5 or the Debugger tab, the development server starts but then stops with the stack returning raise TemplateDoesNotExist(name, tried=tried) django.template.exceptions.TemplateDoesNotExist: base.html. Site loads with a server 500 error/I'm not sure if something with my path is off? Or theres a config error? Really need to use the build in debugger but can't figure out why it cant start the server when debugging. I've tried removing the args in the dev server launch.json but that doest work either. Any advice would be appreciated! -
psycopg2.OperationalError: FATAL: password authentication failed for user "nouman"
I am trying to configure Postgresql with django 2.2 but ending up getting error. Here is what I did to configure postgres for my project: Installed postgresql latest version with all default configuration and gave my password Created database in SQL Shell (psql) by doing CREATE USER nouman; CREATE DATABASE blog OWNER nouman; Then I updated settings.py file for the database as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', 'USER': 'nouman', 'PASSWORD': 'my password', 'HOST': 'localhost', 'PORT': '', } } I installed psycopg2 by the command: "pip install psycopg2". But when I update the database by "python manage.py migrate" it gives this error: Traceback (most recent call last): File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "nouman" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() -----------snip-------- File "C:\Users\nouma\Desktop\djano2byexample\myenv\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = … -
Mock patch results in error -- TypeError: object() takes no parameters in python 3
This is a bit complicated because I'm debugging some code written a long time ago in python 2.7 In progress of migrating to Python 3 (I know, I know) and facing this problem when trying to fix unit tests The problem is I'm getting an error TypeError: object() takes no parameters I'll list the functions below. I have to replace a lot of names of functions and objects. If you see an inconsistency in module names, assume it's typo. First the class it's calling class Parser(object): def __init__(self, some_instance, some_file): self._some_instance = some_instance self.stream = Parser.formsomestream(some_file) self.errors = [] @staticmethod def formsomestream(some_file): # return a stream class BetterParser(Parser): def parse(self): # skip some steps, shouldn't relate to the problem return details # this is a string class CSVUploadManager(object): def __init__(self, model_instance, upload_file): self._model_instance = model_instance self._upload_file = upload_file # then bunch of functions here # then..... def _parse(self): parser_instance = self._parser_class(self._model_instance, self._upload_file) # bunch of stuff follows def _validate(self): if not self._parsed: self._parse() # some attributes to set up here def is_valid(self): if not self._validated: self._validate() Now the test function from somewhere.to.this.validator import MockUploadValidator from another.place import CSVUploadManager class TestSomething(SomeConfigsToBeMixedIn): @mock.patch('path.to.BetterParser.parse') @mock.patch('path.to.SomeValidator.__new__') def test_validator_is_called(self, mock_validator_new, mock_parse): mock_validator_new.return_value = MockUploadValidator.__new__(MockUploadValidator) mock_parse.return_value … -
Django is giving me an "invalid date format" error when running tests despite specifying date format in settings
My settings file has this date format specified: # settings.py DATE_FORMAT = '%m/%d/%Y' In my test file, I'm creating an object requires a date and looks like this: # tests.py my_model = Thing(a_date='11/22/2019').save() When I run the test, however, the test gets stuck when it goes to create the object and throws the error: django.core.exceptions.ValidationError: ["'11/22/2019' value has an invalid date format. It must be in YYYY-MM-DD format."] Is there something I'm missing? Why would it be throwing this error? -
how to generate token expire itself after 24 hours?
I am trying to create a better way to generate tokens that expire itself after 24 hours, but I want to test it with 1-minute timing that it is really doing the job. I don't know if this is the right way to do it, but if not help me #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six from django.utils.crypto import constant_time_compare from django.utils.http import base36_to_int class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) def check_token(self, user, token): # This is a copy and clean of the super check_token code removing what is not required in this case if not (user and token): return False try: ts_b36, _ = token.split("-") ts = base36_to_int(ts_b36) except ValueError: return False if (self._num_days(self._today()) - ts) > 1: # 1 day = 24 hours return False return True account_activation_token = AccountActivationTokenGenerator() -
Serializing nested objects in DRF
I have a test object on my website that I am trying to get into the database correctly. It's an order object with nested product data. Here's an example of JSON being posted by front-end: { "phone": "123456789", "first_name": "name", "delivery_date": "2020-01-06", "delivery_time": 2, "address": "address", "comment": "comment", "payment": 0, "order_items": [ { "quantity": 2, "pizza": 1 }, { "quantity": 3, "pizza": 2 } ] } Here's my serializers.py class OrderItemSerializer(serializers.ModelSerializer): quantity = serializers.IntegerField() pizza = serializers.SerializerMethodField() print(pizza, quantity) def get_pizza(self, obj): print(obj.pizza.id) return obj.pizza.id class Meta: model = OrderItem fields = ('quantity', 'pizza',) class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() """ Calculate order_items field """ def get_order_items(self, obj): items = obj.orderitem_set.all() print(obj) print(items) return OrderItemSerializer(items, many=True).data class Meta: model = Order fields = ('phone', 'first_name', 'delivery_date', 'delivery_time', 'address', 'comment', 'payment', 'order_items',) As result, order_items is always empty: "order_items": [] I'm using Swagger to test and document API. I can post orders directly from there with no errors but even when I add order items manually, they still don't appear in server response body. Which must mean that I am not processing nested objects properly. POST { "phone": "123456", "first_name": "string", "delivery_date": "2000-10-21", "delivery_time": 2, "address": "string", "comment": "string", "payment": 0, "order_items": … -
Django Queryset - get the newest record per foreign key
I see a lot of similar queries on but none seem to be working for what im after, I have a table as such: class BGPData(models.Model): subnet = models.ForeignKey(Subnet, verbose_name="Subnet", on_delete=models.CASCADE, blank=True, null=True) bgp_peer_as = models.CharField(max_length=20, verbose_name='BGP Peer AS', blank=True, null=True) bgp_session = models.CharField(max_length=10, verbose_name='BGP Session', blank=True, null=True) bgp_routes = models.CharField(max_length=10, verbose_name='BGP Routes Received', blank=True, null=True) timestamp = models.DateTimeField(auto_now=True, blank=True, null=True) I would like to obtain the newest record per foreign key on subnet only. Attempts thus far below: - bgp_data_query = BGPData.objects.filter(subnet__get_bgp=True,subnet__wb_bgp=True) \ .annotate(last_updated=Cast(TruncSecond('timestamp', DateTimeField()), CharField())) d = BGPData.objects.annotate(max_timestamp=Max('timestamp')).filter(timestamp=F('max_timestamp')) Theres something im not quite getting here but im unsure as to what it is... Thanks -
How can I use .format() with urls in Python Django?
I'm writing an app in Django and I would like to format my url in this way: return HttpRedirect("timetable/{0}/{1}/".format(my_grade, my_letter)) But it gives me 404 error because path doesn't match. It's the url I'm redirected to: http://127.0.0.1:8000/timetable/8/%D0%97/ How can I fix encoding? -
best or recommended way to setup CD for a non-dockerized django website?
I am trying to figure out the best way to deploy code that is merged to master of one branch. My jenkins server and my website server are 2 different servers and my best guess for how to do CD is to just use the scp command for copying over the files but was wondering if there is a method that is more sophisticated. I am looking for a method that does not dockerize my django application at this time and most of the search results online keep giving examples of how to do it with a dockerized django application. -
CharField on django is outputted as (<django.forms.fields.CharField object at XXXX>,)
I'd like to output the input field on the template, but it is outputted as django.forms.fields.CharField object at XXXX How can I fix this issue? I have tried many ways to fix it. But I could not solve the issues. source codes occur the error views.py from django.shortcuts import render from . import forms def index(request): form = forms.Page1(request.GET or None) if form.is_valid(): message = 'データ検証に成功しました' else: message = 'データ検証に失敗しました' content = { 'title': 'とあるウェブアプリ', 'form': form, 'message': message, } return render(request, 'forms.html', content) forms.py from django import forms EMPTY_CHOICES = ( ('', '-'*10), ) GENDER_CHOICES = ( ('man', '男'), ('woman', '女') ) class Page1(forms.Form): user_sir_name = forms.CharField( label='姓', max_length=20, required=True, widget=forms.TextInput(), ), user_given_name = forms.CharField( label='名', max_length=20, required=True, widget=forms.TextInput(), ), user_sex = forms.ChoiceField( label='性別', widget=forms.Select, choices=EMPTY_CHOICES + GENDER_CHOICES, required=True, ) forms.html {% extends "base.html" %} {% block content %} {{ message }} <hr> <form method="get" action=""> {{ form.errors.user_sir_name }} <label>{{ form.user_sir_name.label }} {{ form.user_sir_name }}</label><br> {{ form.errors.user_given_name }} <label>{{ form.user_given_name.label }} {{ form.user_given_name }}</label><br> {{ form.errors.user_sex }} <label>{{ form.user_sex.label }} {{ form.user_sex }}</label><br> <br> <input type="submit" value="送信"> </form> {% endblock %} {% load static %} <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="content-language" content="ja"> <meta name="viewport" content="width=device-width, initial-scale=1.0, … -
How to create django project in cmd
I have been unable to create django project via command prompt. Here is the path I set in the environment variable: C:\Users\Freddy\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\Freddy\AppData\Roaming\Python\Python38\site-packages\django. I tried to run this "django-admin" in command prompt I got this message that " django-admin is not recognized as an internal or external command,operable program or batch file" What do I do? -
Input SMPTE Timecode in a Django Form?
What's the best way to input SMPTE timecode when using HTML forms and the Django web framework? Django/HTML supports an <input type="time">, with a format: hh:mm:ss but "time" does not include the frame numbers required for timecode - hh:mm:ss:ff I've been searching around and can't find a solution. I've also checked the djangopackages site, but it doesn't seem to have anything related to timecode. Ideally, the timecode field would allow the user to just enter the integers (eg. "00 59 59 29") and the field would handle the formatting of the input, adding the colons or semi-colons for drop-frame. -
How to match value in database in csv file?
I am trying to compare value from csv files and database. I create a dictionary where I put the name of the city as key and the zipcode as value. So when I'm comparing the name of the city from my database and look into my csv files. The matches has not been done. Here is my code : -
integrate the peyement API Mtn MOMO
good evening everyone please I try to integrate the payment API Mtn MOMO in my django project without success. someone can advise me a tutorial. it's really urgent thank you very much for helping me Body -
Whats the best way to add listener to external resource?
I have a django project and external resource. The external resource has XML data which changes time to time but it still static if nothing happened. I need to collect new data if something happened. The ways I see: 1. Grab content one time in some period and check if it is different. 2. Save content as file and check length (worse way). Unfortunately, I can't predict when content will change also I can't use WebSockets, Long Polling and WebHooks. Please, describe me the ways that in modern WWW today may solve my problem! -
gunicorn ImportError: No module named webob
I run an appengine project by using: gunicorn -b $3000 main:app It is a python (Django) project and i am running it on linux. The exact error is: [2020-01-17 11:30:04 +0000] [4551] [INFO] Starting gunicorn 19.9.0 [2020-01-17 11:30:04 +0000] [4551] [INFO] Listening at: http://0.0.0.0:8000 (4551) [2020-01-17 11:30:04 +0000] [4551] [INFO] Using worker: sync [2020-01-17 11:30:04 +0000] [4556] [INFO] Booting worker with pid: 4556 [2020-01-17 11:30:04 +0000] [4556] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 375, in import_app __import__(module) File "/home/vicktree/Desktop/noah/web/noahs-app/main.py", line 37, in <module> import webapp2 File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 25, in <module> import webob ImportError: No module named webob [2020-01-17 11:30:04 +0000] [4556] [INFO] Worker exiting (pid: 4556) [2020-01-17 11:30:04 +0000] [4551] [INFO] Shutting down: Master [2020-01-17 11:30:04 +0000] [4551] [INFO] Reason: Worker failed to boot. I have webob and i do not know why i am getting this error. I have tried to pip install … -
gunicorn ImportError: No module named webob
I run an appengine project by using: gunicorn -b $3000 main:app It is a python (Django) project and i am running it on linux. The exact error is: [2020-01-17 11:30:04 +0000] [4551] [INFO] Starting gunicorn 19.9.0 [2020-01-17 11:30:04 +0000] [4551] [INFO] Listening at: http://0.0.0.0:8000 (4551) [2020-01-17 11:30:04 +0000] [4551] [INFO] Using worker: sync [2020-01-17 11:30:04 +0000] [4556] [INFO] Booting worker with pid: 4556 [2020-01-17 11:30:04 +0000] [4556] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 375, in import_app __import__(module) File "/home/vicktree/Desktop/noah/web/noahs-app/main.py", line 37, in <module> import webapp2 File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 25, in <module> import webob ImportError: No module named webob [2020-01-17 11:30:04 +0000] [4556] [INFO] Worker exiting (pid: 4556) [2020-01-17 11:30:04 +0000] [4551] [INFO] Shutting down: Master [2020-01-17 11:30:04 +0000] [4551] [INFO] Reason: Worker failed to boot. I have webob and i do not know why i am getting this error. I have tried to pip install …