Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating model and views
I would need help creating models and views for my project. I need a model that will extend the auth.user model that I use to authorize users. There should also be three int columns, game1-score, game2-score, and game3-score, in this model, into which I will insert data using views. I need to make sure that the logged-in user is found in views and then find out if his record already exists in the created model and insert the score into the correct column using the value game_id, which also comes with a score to views, and if the column already has a value he has to compare it with the new one and save the bigger one. I would really appreciate the help, especially with the views part, I have a model created somehow, but I don't know if well, see below. class UserGameScore(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) -
UnboundLocalError: local variable 'currency' referenced before assignment Django
There are many questions with this similar error but can't find the particular solution to my case. I have a form that has a list of currency symbols, when selected by the user, the values on the page will change. I am using the symbol selected by the user as a dict key to change the rates. However, I'm getting the error in the title. FORM class CurrencyForm(forms.Form): currency = forms.ChoiceField(initial=('USD', 'USD'), choices=['USD', 'AUD', 'GBP' 'CAD'], label='Choose Currency:') VIEW class MyDashboardView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request, **kwargs): form_c = CurrencyForm(prefix='form_c') return render(request, self.template_name, { 'form_c': form_c, }) def post(self, request): form_c = CurrencyForm(request.POST, prefix='form_c') if request.method == 'POST': if form_c.is_valid(): currency = form_c.cleaned_data['currency'] rates = {'USD': 1.0, 'AUD': 1.321, 'GBP': 0.764, 'CAD': 1.249} deposit = 10000 / rates['currency'] context = { 'deposit': deposit } return render(request, 'coinprices/my-dashboard.html', context) HTML <span> <form method="post"> {% csrf_token %} {{ form_c.as_p }} <button class="btn btn-outline-success btn-sm">Submit</button> </form> </span> UnboundLocalError: local variable 'currency' referenced before assignment -
Dynamic Extraction from MySQL cloud database
I have a django project connected to a MySQL cloud table that extracts charts from the downloaded data. the database is huge (more than 10M rows and 30 columns), I want to dynamically extract data from the table in the fastest and most efficient way so that users don't have to wait 10 minutes to load the charts. I'm thinking about doing a one time full extraction and then saving the extracted data somehow in the django project, and then tell the script to only download new data on the table. what would be the best approach for this? -
Django Unit Testing for standalone variables (coverage)
I'm starting to write unit tests for a django project, and running coverage shows I have 0% coverage over a simple list of tuples. Example: STATE_CHOICES = [ ("MO", "Missouri",), ("AL", "Alabama",), ] Is there some kind of test I could write to get coverage over this list of tuples? I assumed simple len() > 0 and is not None tests would cover it, but apparently not. -
django: pass json string to url as parameter
How can I define a regex for pass json string to url as parameter in django framework? Now I use (?P<query>\w+) but it doesn't work because json string is a entire string made with different words. Using the URLconf defined in giustiziasite.urls, Django tried these URL patterns, in this order: ^pygiustizia/ ^exportcsv-show-results/q/(?P<query>\w+)$ [name='exportcsv-show-results'] admin/ The current path, pygiustizia/exportcsv-show-results/q/{"query": {"bool": {"must": [], "should": []}}, "_source": ["annoruolo", "annosentenza", "codiceoggetto"]}, didn’t match any of these. -
why i am unable to load static files in django?
SCREENSHOT IMAGE you can check my project structure and code in the above screen shot. when I give the command 'python manage.py collectstatic' in my terminal, it's collecting only the default django admin dashboard related static files, but it's not collecting the static files which are in the folder 'home/static/' can you please check what's wrong in that? -
How to do SELECT/DELETE WHERE column IN list in Django
Let us say I have model like this: class Tmp(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) Then we have a list of id's let us say (1, 4, 5, 9, 10) and let us say I want to run: SELECT * FROM tmp WHERE id IN (1, 4, 5, 9, 10) or I want to delete these users: DELETE FROM tmp WHERE id IN (1, 4, 5, 9, 10) How do I achieve this in Django? I believe if I only wanna do it on primary keys, I can use filter and achieve something like this for select: Tmp.objects.filter(pk__in=(1, 4, 5, 9, 10)).get() or like this for delete: Tmp.objects.filter(pk__in=(1, 4, 5, 9, 10)).delete() However, what if I do not want to use the primary key? How can I achieve the same effect? As an example what if I wanted to delete or select by name? -
How do I pass a specific CustomUser to the class-based CreateView in Django?
After finishing a tutorial, I decided to convert the function-based views in the app to class-based views as a way to learn both better. But I got stumped with passing the fields of a CustomUser to the CreateView: #model: class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1, choices=user_type_data, max_length=10) class Staff(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) email=models.EmailField() address=models.TextField(blank=True) objects=models.Manager() #view: @method_decorator(csrf_exempt, name='dispatch') class SubjectCreateView(CreateView): model = Subject fields = ['id', ... ] What I want to put in the fields= are: staff.first_name, staff.last_name, but none of the combinations I tried worked. This is my first encounter with CustomUser, so my searches weren't fruitful. Appreciate some pointers. -
I am unable to use function inside another function in django
@csrf_exempt def handlerequest(request): # paytm will send you post request here form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('payment succesfull') def function_name(request): UserProfile.objects.filter(user=request.user).update(payment=True) else: print('payment was not successful because' + response_dict['RESPMSG']) return render(request, 'app/paymentstatus.html', {'response': response_dict}) -
'flex' applies the same CSS property as 'hidden'
The error is 'flex' applies the same CSS property as 'hidden'. and also vice versa 'hidden' applies the same CSS property as 'flex'. -
Django websites not loading
I have two Django websites on one server running off Apache with mod_wsgi on Windows 10. For some reason the Django websites don't load, however, I have a normal website that does. I've had it work in the past when I was using one, but I had to change some stuff to make two work. I understand Linux is better for this, however, I understand Windows better as I have more experience with it. Here is my config file and WSGI files for both websites, thank you WSGI 1 import os import sys from django.core.wsgi import get_wsgi_application # Add the site-packages of the chosen virtualenv to work with sys.path.append('C:/xampp/htdocs/neostorm') sys.path.append('C:/xampp/htdocs/neostorm/neostorm') os.environ["DJANGO_SETTINGS_MODULE"] = "neostorm.settings" application = get_wsgi_application() WSGI 2 import os import sys from django.core.wsgi import get_wsgi_application import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('C:/Users/taber/.virtualenvs/htdocs-auttCy-h/Lib/site-packages') sys.path.append('C:/xampp/htdocs/astinarts') sys.path.append('C:/xampp/htdocs/astinarts/astinarts') os.environ["DJANGO_SETTINGS_MODULE"] = "astinarts.settings" application = get_wsgi_application() My Vhosts ##<VirtualHost *:80> ##ServerAdmin webmaster@dummy-host.example.com ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com" ##ServerName dummy-host.example.com ##ServerAlias www.dummy-host.example.com ##ErrorLog "logs/dummy-host.example.com-error.log" ##CustomLog "logs/dummy-host.example.com-access.log" common ##</VirtualHost> #LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" ##<VirtualHost *:80> ##ServerAdmin webmaster@dummy-host2.example.com ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com" ##ServerName dummy-host2.example.com ##ErrorLog "logs/dummy-host2.example.com-error.log" ##CustomLog "logs/dummy-host2.example.com-access.log" common ##</VirtualHost> LoadFile "C:/Users/taber/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/taber/.virtualenvs/htdocs-auttCy-h/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/.virtualenvs/htdocs-auttCy-h" ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName … -
How can I use the django as database layer in the API application developed in Flask?
I want to use the Django as database module like an installable module in an API application developed in Flask -
django 'str' object has no attribute 'id' in getlist()
I have this function that I tried to use to perform a delete operation on some items def return_buk(request): books = Books.objects.all() selected = request.POST.getlist('marked_delete') for book in books: for select in selected: if select.book_id_id == book.id: print(select.id) However, when I try to access the attributes, I get an error like this. Obviously the items in the getlist are coming as in str format. How can I get their attributes? 'str' object has no attribute 'id' -
Browser not setting cookie (set-cookie is in the header) - Django backend, Express fetch frontend
Apologies if this has been asked before, but I've scoured Google for 5 days and am just plain stuck. I have a Django/DRF API backend that I'm POSTing login credentials to and expecting a "sessionid" cookie in return. It's running at https://url.com/api/. The login endpoint is https://url.com/api/api_login/. I'm using ExpressJS and fetch on the frontend to make the call. It's running at https://url.com/. The login form is located at https://url.com/login. I have an Nginx reverse proxy mapping "url.com/api" to "url.com:8002", and "url.com" to "url.com:8003". Here is the simplified code for the backend: # views.py @method_decorator(csrf_exempt, name='dispatch') class ApiLogin(APIView): def post(self, request): form = LoginForm(request.POST) if form.is_valid(): user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: auth_login(request, user) # at this point, you are either logged in or not if request.user.is_authenticated: response = HttpResponse(f"Successful login for {form.cleaned_data['username']}.") return response else: response = HttpResponse("Login failed.") return response Here is the full code for the frontend: //*** server.js const express = require('express'); const app = express(); app.use(express.static('static')); app.use(express.json()); app.use(express.urlencoded({extended: true})); const router = require('./router'); app.use(router); //*** router.js const express = require('express'); const router = express.Router(); const qs = require('qs'); const fetch = require('node-fetch'); // temporarily running on a self-signed cert, so this … -
How to monitor the transactions of a Terra (LUNA) address in real time?
This is for a Django project so I'd prefer using the Terra Python SDK. If it is impossible in Python, I don't mind using the Javascript SDK. Ethereum has a subscription function, is there an equivalent thing for the Terra network? -
External API Calls are blocking django view
I am facing a problem. Django view is not rendering until the api calls are fininshed. Here is code below. the following code takes data from google autocomplete api and store it in database. from django.http import HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import redirect, render import requests import uuid import json from api.models import report # Create your views here. headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def index(request): if(request.method == 'GET'): return redirect('/') elif(request.method == 'POST'): var = request.POST['keyword_google'] if(var == ""): return HttpResponse("You should have entered something") else: identifier = str(uuid.uuid4()) insert = report() insert.id = identifier insert.title = var google_autocomplete_url = "https://google.com/complete/search?client=chrome&q=" insert.null_keywords = json.loads(requests.get(google_autocomplete_url+var, headers=headers).text)[1] insert.vs_keywords = json.loads(requests.get(google_autocomplete_url+var+"+vs", headers=headers).text)[1] insert.versus_keywords = json.loads(requests.get(google_autocomplete_url+var+"+versus", headers=headers).text)[1] insert.or_keywords = json.loads(requests.get(google_autocomplete_url+var+"+or", headers=headers).text)[1] insert.and_keywords = json.loads(requests.get(google_autocomplete_url+var+"+and", headers=headers).text)[1] insert.like_keywords = json.loads(requests.get(google_autocomplete_url+var+"+like", headers=headers).text)[1] insert.with_keywords = json.loads(requests.get(google_autocomplete_url+var+"+with", headers=headers).text)[1] insert.near_keywords = json.loads(requests.get(google_autocomplete_url+var+"+near", headers=headers).text)[1] insert.is_keywords = json.loads(requests.get(google_autocomplete_url+var+"+is", headers=headers).text)[1] insert.for_keywords = json.loads(requests.get(google_autocomplete_url+var+"+for", headers=headers).text)[1] insert.to_keywords = json.loads(requests.get(google_autocomplete_url+var+"+to", headers=headers).text)[1] insert.without_keywords = json.loads(requests.get(google_autocomplete_url+var+"+without", headers=headers).text)[1] insert.can_keywords = json.loads(requests.get(google_autocomplete_url+var+"+can", headers=headers).text)[1] insert.why_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=why+"+var, headers=headers).text)[1] insert.where_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=where+"+var, headers=headers).text)[1] insert.who_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=who+"+var, headers=headers).text)[1] insert.when_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=when+"+var, headers=headers).text)[1] insert.will_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=will+"+var, headers=headers).text)[1] insert.are_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=are+"+var, headers=headers).text)[1] insert.which_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=which+"+var, headers=headers).text)[1] insert.can_keywords = json.loads(requests.get("https://google.com/complete/search?client=chrome&q=can+"+var, headers=headers).text)[1] insert.how_keywords … -
Django How to check id of ForeignKey?
I have models.py like this. which api_key in table UserKey is ForeignKey to api_key in table DeviceKey. class DeviceKey(models.Model): api_key=models.CharField(max_length=100,unique=True) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.api_key class UserKey(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) def __str__(self): return self.username The data in table DeviceKey and Userkey show like this code. Table DeviceKey id api_key 1 abc1 2 abc2 Table Userkey id api_key_id 1 1 I want to check if api_key exists in table Userkey but I can't search with text beacause table UserKey keep api_key as id. So, I have to get id from table DeviceKey like this code key="abc2" if UserKey.objects.filter(username=username,api_key_id=DeviceKey.objects.get(api_key=key).values_list('id')).exists(): It show error like this. 'DeviceKey' object has no attribute 'values_list' How to fix it? -
How to skip http headers when receiving and writing file from POST request?
In my Django POST request, I am getting a json file and writing it locally in the server like this: up_file = request.FILES['file'] full_file_path = <my file path> destination = open(full_file_path, 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() But the file is written like this: ------WebKitFormBoundary2df6tPQtB97uXIt6 Content-Disposition: form-data; name="myFile"; filename="input.json" Content-Type: application/json {"x": 1} ------WebKitFormBoundary2df6tPQtB97uXIt6-- as input.json. Obviously, this is invalid so I want the file to only contain: {"x": 1} How do I make this file writing skip the headers and footers and write only the actual content? -
AssertionError: Template was not a template used to render the response
I'm encountering an issue with my TestCase where it's asserting that the actual template used to render a response doesn't match the template I'm expecting. The error being raised is: AssertionError: False is not true : Template 'posts/question.html' was not a template used to render the response. Actual template(s) used: posts/ask.html, ..., ... Everything after posts/ask.html refers to built-in templates. Sequence of events involved: Click "Ask Question" -> post QuestionForm -> redirect to question page -> click edit -> post question edits -> redirect to question page I cannot pinpoint where or why Django is saying that posts/ask.html is being rendered. As far as I can tell I'm redirecting to the right URL where it's suppose to render posts/question.html. class TestPostEditQuestionPage(TestCase): '''Verify that a message is displayed to the user in the event that some aspect of the previous posted question was edited.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username="OneAndOnly", password="passcoderule" ) profile = Profile.objects.create(user=cls.user) tag = Tag.objects.create(name="TagZ") question = Question.objects.create( title="This is Question Infinity", body="The is the content body for This is Question Infinity", profile=profile ) question.tags.add(tag) cls.data = { "title": "This is Question Zero", "body": "The is the content body for This is Question Infinity", "tags": ["TagZ", "TagA"] … -
Django Rest framework - I am trying to convert a property received in Response object to JSON object and iterate through it. But response is string
In views.py VENDOR_MAPPER is list of dictionary each dictionary has id, name, placeholder and autocommit key. I also tried sending json instead of Response object. resp_object = {} resp_object['supported_vendors'] = VENDOR_MAPPER resp_object['vendor_name'] = "" resp_object['create_vo_entry'] = False resp_object['generate_signature_flag'] = False resp_object['branch_flag'] = False resp_object['trunk_flag'] = False resp_object['branch_name'] = "" resp_object['advisory'] = "" data = {'data': resp_object} return Response(data) On home.html I am accessing the vendors_supported which is list and iterate through it, however instead of object i am getting string as type of variable. var supported_vendors = "{{data.supported_vendors|safe}}"; console.log(supported_vendors); console.log("Supported_vendors ", supported_vendors); console.log("Supported_vendors_type:", typeof(supported_vendors)); data.supported_vendors|safe (django template tagging) is used to remove the unwanted characters in the response i have also tried without safe, but still the type was string also tried converted as well as parse the response but type is shown as string var supported_vendors = "{{data.supported_vendors}}"; console.log(JSON.parse(supported_vendors)); console.log(JSON.stringify(supported_vendors)); Output generated, i have printed the response type and values i get, also converting using JSON.parse and JSON.stringify did not work and output every time was string [1]: https://i.stack.imgur.com/DuSMb.png I want to convert the property into javascript object and perform some computations -
Django CreateView Trying to register a client With a specific number that goes from 15 to 15
I am trying to make a small system in which I have to put a client number that goes from 15 to 15, but the truth is that I did not succeed to change a global variable. I am trying to learn how class based views work. I hope you can help me. What I'm looking for is to get the find the last record in the database and add 15 to it. thank you. models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=50) customer_num = models.IntegerField(unique=True) def __str__(self): return self.name views.py from re import template from django.shortcuts import render from aplicacion.models import * from django.views.generic import * from django.http import HttpResponse # Create your views here. class CreateCustomer(CreateView): model = Customer template_name = 'createcustomer.html' fields = ['name'] success_url = "/admin/aplicacion/customer/" aa = Customer.objects.last().customer_num def form_valid(self, form): global aa while True: try: Customer = form.save(commit=False) Customer.customer_num = self.aa print(self.aa, "jjjj") """If the form is valid, save the associated model.""" #form.instance.customer_num = self.request.POST['name'] break aa = self.aa + 15 except: pass return super().form_valid(form) -
How to get total sum in multiple lists using python
[templatetag.py] def total_sum(value): value_list = value[:, 1:] return [sum(i) for i in zip(*value_list)] [html] {% load total_sum from templatetag %} <tr> <td>Monthly Total</td> <td>{{ monthly_enroll_list|total_sum }}</td> <!-- Total (Jan) --> <td>{{ monthly_enroll_list }}</td> <!-- Total (Feb) --> <td>{{ monthly_enroll_list }}</td> <!-- Total (Mar) --> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> <td>{{ monthly_enroll_list }}</td> </tr> The value of the "monthy_enroll_list" variable is as follows. [['A', 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8], ['B', 1, 8, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], ['C', 0, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 2], ['D', 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] If I remove the index at the beginning and the end of each list, I get the number of enrolls from January to December. I want to get the total sum per month. The values I want to get are: ['6', '10', '12', '6', '0', '0', '0', '0', '0', '0', '0', '0'] But i got the following error: list indices must be integers … -
Django debug tool bar not showing
enter image description here I want to show debug tool bar but it looks like above.. what's wrong? -
Dynamically change values based on user selected option django
I'm trying to change a value based on the exchange rate selected by the user within the <option> tag. I don't want to save the form result to the database. I just want it to dynamically change whenever the user changes the currency option. Say a user selects a currency from the below form with the options in the view: VIEW def view(request): currency_dict = {'EUR': 0.9154994049253867, 'JPY': 123.86706948640484, 'BGN': 1.7905337361530713, 'CZK': 22.375720955781375} cur = currency_dict.items() deposit = 10000 context = { 'currency_dict': currency_dict, 'cur': cur, 'deposit': deposit, } return render(request, 'coinprices/my-dashboard.html', context) HTML - FORM <div class="container"> <div> <span> <h1>My Dashboard</h1> </span> <span> <label>Choose Currency:</label> <input list="ex-currency"> <datalist id="ex-currency"> {% for k, v in cur %} <option value="{{ k }}"></option> {% endfor %} </datalist> </span> </div> </div> Then based on the users selection, multiply the {{ deposit }} value by the currency_dict[user_selected_currency] and change the bold text (see below): DESIRED OUTCOME <span> <div><b>Total Investment {{ user_selected_currency }}</b></div> <span class="text-xl">${{ deposit * currency_dict[user_selected_currency] }}</span> </span> Any ideas how this can be achieved? -
Remove update profile Image url field in django
Does anyone know how to remove the url link