Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Inconsistent Versioning - Pipenv
I tried to install pipenv, but it seems like it's running with an incorrect version of Python. The result is a namedtuple issue shown below, where the defaults were added in Python version 3.7. However, the pipenv source code checks for version 3.7 or above. Do I need to fix my Python setup for this to work properly? ➜ lead-manager-react-django python -V Python 2.7.16 ➜ lead-manager-react-django pip --version pip 19.0.3 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg/pip (python 3.7) > ➜ lead-manager-react-django pip install pipenv Collecting pipenv Using cached https://files.pythonhosted.org/packages/df/c5/2ebf6fcab61826a6e886531d67bb9776b4027c3094fbf2fbbaa2c9075d92/pipenv-2020.11.15-py2.py3-none-any.whl Requirement already satisfied: setuptools>=36.2.1 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pipenv) (51.1.1) Requirement already satisfied: certifi in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pipenv) (2019.11.28) Requirement already satisfied: virtualenv-clone>=0.2.5 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pipenv) (0.5.4) Requirement already satisfied: virtualenv in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from pipenv) (20.2.2) Requirement already satisfied: pip>=18.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg (from pipenv) (19.0.3) Requirement already satisfied: six<2,>=1.9.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from virtualenv->pipenv) (1.15.0) Requirement already satisfied: filelock<4,>=3.0.0 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: importlib-metadata>=0.12; python_version < "3.8" in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from virtualenv->pipenv) (3.3.0) Requirement already satisfied: distlib<1,>=0.3.1 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from virtualenv->pipenv) (0.3.1) Requirement already satisfied: appdirs<2,>=1.4.3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: typing-extensions>=3.6.4; python_version < "3.8" in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from importlib-metadata>=0.12; python_version < "3.8"->virtualenv->pipenv) (3.7.4.3) Requirement already satisfied: zipp>=0.5 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from … -
pytest-django: how to change PASSWORD_HASHERS
I want to use a weaker password hashing algorithm when testing for less time consuming. According to doc and this article article, I add below code inside settings.py import sys if 'test' in sys.argv: PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ] when I run python3.7 manage.py test the tests run very fast, but if I run pytest it just cost the same time as before, what should I do? -
How to use login_required decorator once to make it effective on every single function without hardcoding and putting it on every single function?
so I am building an app where I want users to login before accessing certain pages. To do that, I need to use the login_required decorator. But I find it annoying to use that decorator on every single function that renders a page to make it useful. Do you know a way, that I can use it once and make it effective on every single page or function that renders the page? -
Custom Django form validation does not raise ValidationError
I have a form that otherwise works. Normal validation errors are raised; however, my custom validation function does not raise the validation error. How can I fix this to make it show the custom validation error? from django import forms class UserRegistrationForm(forms.Form): GENDER=[('male','MALE'), ('female', 'FEMALE')] firstName=forms.CharField() lastName=forms.CharField() email=forms.EmailField() gender=forms.CharField(widget=forms.Select(choices=GENDER)) password=forms.CharField(widget=forms.PasswordInput) emp_id=forms.IntegerField(label="Employee ID") def clean_firstName(self): inputFirstName = self.cleaned_data['firstName'] if len(inputFirstName)>20: raise forms.ValidationError('First Name must not exceed 20 characters.') return inputFirstName I also tried inputFirstName = self.cleaned_data.get('firstName') In either case the form will submit with data that doesn't fit the custom validation. -
AttributeError 'QuerySet' object has no attribute '_meta'
I'm getting this error when I try to load the page. this is the view: def neworder(request): products = Product.objects.all().prefetch_related('supplier') total_products = products.count() supplier = Supplier.objects.all() form = OrderForm(instance=supplier) if request.method == 'POST': form = OrderForm(request.POST, instance=supplier) if form.is_valid(): print('order updated') form.save() return redirect('suppliers') context = {'products': products, 'suppliers': suppliers, 'total_products': total_products} context['form'] = form return render(request, 'crmapp/neworder.html', context) and this is my form class OrderForm(ModelForm): class Meta: model = Order fields = [ 'supplier', 'item', 'item_qty', ] Can anyone tell me what I'm doing wrong? -
How to treat some value with post requisition Django Rest Framework?
I'm making this API that I have 2 options(Register a Piece and Register a Position in the Chess board). To you register your position, you need to register the piece first to be able to indentify a ID, i want that when I register a piece position in board, I could treat one of these values and return it treated. For exemple: Piece have 3 fields: "piece_id", "piece_name", "piece_color". Board have 3 fields: "boardpiece_id", "position_x", "position_y". Ok, so I registered a new Piece, it's piece_id "3", piece_name "king" and piece_color "black". Now I will register the Board position, the boardpiece_id will be 3, position_x will be "a" and position_y will be "2". I want that when I use the Post request method, it return to me, for exemple, what is the next position_x, but I not knowing how to get only this position. models.py: from django.db import models from uuid import uuid4 # Create your models here. COLOR_CHOICES = ( ('white','WHITE'), ('black', 'BLACK'), ) PICES_NAMES = ( ('king','KING'), ('queen','QUEEN'), ('rook','ROOK'), ('bishop','BISHOP'), ('knight','KNIGHT'), ('pawn','PAWN'), ) WHITE_KING_POSITION = ['e1'] BLACK_KING_POSITION = ['e8'] WHITE_QUEEN_POSITION = ['d1'] BLACK_QUEEN_POSITION = ['d8'] WHITE_ROOK_POSITION = ['a1','h1'] BLACK_ROOK_POSITION = ['a8','h8'] WHITE_BISHOP_POSITION = ['c1','f1'] BLACK_BISHOP_POSITION = ['c8','f8'] WHITE_KNIGHT_POSITION = … -
Django Single Record Model With Immutable & Mutable Values?
I am creating a portable Django project that will be used on many separate AWS servers. I need to allow the user to adjust certain fields of a model, but also have other fields be immutable. I also do not want them to create multiple records of this model Here is what the model looks like: class InstanceSettings(models.Model): # Immutable api_key = models.CharField(max_length=500) # Mutable stripe_api_key = models.CharField(max_length=500) time_zone = models.CharField(max_length=75) calendar_appearence = models.CharField(max_length=750) thankyou_redirect = models.CharField(max_length=1000) I will be fetching this data such as the api key through this line: api_key = models.InstanceSettings.objects.all().values() There needs to be only one record for these values in the database, so the user should not be able to create multiple records of the InstanceSettings model. How do I make some values immutable, and only allow one record to be created for the model? -
Python, Django and yFinance - Need help making it work
newbie to the group here, and new to algo trading as well... I am attempting to integrate a platform with yfinance but am having a heck of a time. I decided to use PyCharm with Django. I've been able to pull data from yahoo successfully, but am not able to print the data through to a web browser. Does anyone have experience with this? any tutorials you can share to help me with this? Much appreciated, -
Django raw count column
Im been confused when I tried to count the append paid_count the error says AttributeError: 'NoneType' object has no attribute 'count'. In my query navicat it runs fine like the image below , the only problem is when I count the specific attribute in my database count(paid). It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance. for p in Person.objects.raw('SELECT id,paid, category, category_status, count(paid) FROM app_person WHERE paid_by != "" GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid'): rpts_paid.append(p.paid) rpts_paid_by.append(p.paid_by) rpts_category.append(p.category) rpts_paid_count.append(p.paid).count() #Error -
Javascript how to pass json content to a variable in Django?
I'm trying to parse a JSON file into a variable, but it would not work for some reason. If I run the following, it works just fine. I can see the three years printed in the console. {% block javascripts %} <script> var mydates = { "2018": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8","week9","week11"] }, "2019": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8","week10","week11"] }, "2020": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8"] } }; for (let year in mydates){ console.log(year) }; </script> {% endblock javascripts %} However, if I run the following, it doesn't work, the console prints 'undefined'. What am I doing wrong? {% block javascripts %} {% load static %} <script> var mydates; fetch("{% static 'dates.json' %}") .then(response => {mydates = response.json() }) for (let year in mydates){ console.log(year) }; </script> {% endblock javascripts %} dates.json is correctly stored in my static folder and it includes the following: { "2018": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8","week9","week10","week11"] }, "2019": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8","week9","week10","week11"] }, "2020": { "January": ["week1","week2","week3","week4"], "February": ["week5","week6","week7"], "March": ["week8","week9","week10","week11"] } } Many thanks for your help ! -
Getting clean mail data from Microsft Graph API
I have been trying to get clean mail data from Microsoft Graph API into a Django template. I have tried using ''' headers={'Prefer': 'outlook.body-content-type="text"' ''' and ''' headers={'Prefer': 'outlook.body-content-type="html"' ''' headers in my python GET request but both of them result in data with tags in them. I have tried using regex to clean my data but it is not as effective because regex removes some important texts. Is there a simpler way of getting a cleaner mail data? -
Django: URLs contain 127.0.0.1 and not the real host-name
I run Django in gunicorn (started via systemd) behind Apache: <VirtualHost *:443> ... <Location /relayrace/> ProxyPass unix:/run/gunicorn-traverse.sock|http://127.0.0.1/ ProxyPassReverse unix:/run/gunicorn-traverse.sock|http://127.0.0.1/ </Location> But the URLs (for example email created by django-allauth) use 127.0.0.1 and not the real FQDN. How to fix this? -
Adding Chart JS to Django App Showing Blank
I have the following HTML that is showing up blank when I run it on my local server. This is the first time that I am trying to use chart.js so maybe there is an installation requirement that I am missing? Am I missing a step or not including something in my code below? <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> </head> {% block content %} <canvas id="myChart" width="400" height="400"></canvas> {% endblock %} {% block javascript %} <script> $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> {% endblock javascript %} -
form.is_valid() not validating properly
Following is my insert.html {% csrf_token %} <div class="col-md-10"> {{form.taxauthority|as_crispy_field}} </div> </div> <div class="row"> <div class="col-md-4"> Select Tax Rate: </div> <div class="col-md-4"> <span id="taxrange"></span> </div> </div> <div class="row"> <div class="col-md-10"> <div class="slidecontainer"> <input type="range" name="TaxRateRange" class="form-range slider" min="0" value="16" max="100" step="0.5" id="myRange"> </div> </div> </div> <div class="row"> </div> <div class="row"> <div class="col-md-12"> <button type="submit" class="btn btn-success col-md-8"> <i class="fas fa-database"></i>Submit</button> </div> Here is my views.py to handle request ` if request.method=="GET": if id==0: #id is zero for the insert operation form=TaxAuthorityForm() else: obj_taxauthority=TaxAuthority.objects.get(pk=id) form=TaxAuthorityForm(instance=obj_taxauthority) return render(request,'TaxAuthority/insert.html',{'form':form}) else: if id==0: form=TaxAuthorityForm(request.POST) form.taxrate=request.POST["TaxRateRange"] print("######### POST id=0 ##########") print(form.taxrate) print(form.errors) print("###################") else: obj_taxauthority=TaxAuthority.objects.get(pk=id) obj_taxauthority.taxrate=request.POST["TaxRateRange"] print("#########POST id Non Zero ##########") print(form.taxrate) print("###################") form=TaxAuthorityForm(request.POST,instance=obj_taxauthority) if form.is_valid(): print("###################") print("save called") print("###################") form.save() return redirect('/taxauthority/') I am trying to get value of slider and saving it back to the database.where TaxAuthorityForm has two fields taxauthority and taxrate. how can i set taxrate value from the range slider. -
Django-filters: Displaying a list of choices for filtering a TextField
In my django based web application I have a model which is defined as following in models.py: class Machine(models.Model): ip_address = models.TextField(blank=False, unique=True) hostname = models.TextField(blank=False, unique=True) In my filters.py file I would like to create a filter based on the ip_address field where the user will select the IP from a list of choices. I defined it as following: class MachineFilter(django_filters.FilterSet): ip_address = ModelChoiceFilter(queryset=Machine.objects.all().values_list('ip_address', flat=True)) class Meta: model = Machine fields = ['ip_address', 'hostname'] However, when selecting the desired IP in the web form I get the following error: Ip address: Select a valid choice. That choice is not one of the available choices. I tried removing the flat=True from the value list definition but this still did not work. What am I doing wrong? -
Serialization and deserialization of objects based on Primary keys
I have several related objects, say, user and location. User and location have a one to one relation class Location(models.Model): county = models.CharField(max_length=100) class CustomUser(AbstractUser): first_name = models.CharField(null=True, max_length=500) last_name = models.CharField(null=True, max_length=500) location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE) while working with django rest framework, a get request on users will return something like { "id": 123, "first_name": "first_name", "last_name": "last_name", "location": 34 } I would like to get a response to something similar to, { "id": 123, "first_name": "first_name", "last_name": "last_name", "location": { "id": 34, "name": "No Man's Land" } } Nested serializers and PrimaryKeyRelatedField work but not in all situations. Is there a way this is achievable? -
Django - Query count of each distinct status
I have a model Model that has Model.status field. The status field can be of value draft, active or cancelled. Is it possible to get a count of all objects based on their status? I would prefer to do that in one query instead of this: Model.objects.filter(status='draft').count() Model.objects.filter(status='active').count() Model.objects.filter(status='cancelled').count() I think that aggregate could help. -
from geopy.geocoders.google import GQueryError ModuleNotFoundError: No module named 'geopy.geocoders.google'
this the code but getting this error can anyone help me the error is on (from geopy.geocoders.google import GQueryError). the error is a show in picture[enter image description here][1] from django.db import models from urllib.request import URLError from django.contrib.gis.db import models from geopy.geocoders import GoogleV3 from django.contrib.gis import geos from geopy.geocoders.google import GQueryError from geopy import geocoders # Create your models here. class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) address = models.CharField(max_length=100) city = models.CharField(max_length=50) def save(self, **kwargs): if not self.location: address = u'%s %s' % (self.city, self.address) address = address.encode('utf-8') geocoder = GoogleV3() try: _, latlon = geocoder.geocode(address) except (URLError, GQueryError, ValueError): pass else: point = "POINT(%s %s)" % (latlon[1], latlon[0]) self.location = geos.fromstr(point) super(Shop, self).save() ``` [1]: https://i.stack.imgur.com/wG9KO.png -
Strange generation of arrays using numpy
I faced such a problem that with one algorithm different arrays are generated for me. Why is this happening to me? def formation(self): tickets = 0.00 new_tickets = 0.00 chanse = {} for item in items: new_tickets = tickets + item.item.quality.chance print(tickets,new_tickets) chanse[item.item.name] = numpy.arange(tickets,new_tickets,0.01) tickets = new_tickets return tickets,chanse And I get a result like this: 0.0 70.0 70.0 145.0 [0.000e+00 1.000e-02 2.000e-02 ... 6.997e+01 6.998e+01 6.999e+01] [ 70. 70.01 70.02 ... 144.97 144.98 144.99] -
How to do CRUD operation in any subpage
Basically i want to do CRUD operation in one specific table Id for example if i am in 'http://127.0.0.1:8000/view/1' this page i want to do crud operation for this specific id and have small table below it. class Allinvoice(models.Model): company_choice = ( ('VT_India', 'VT_India'), ('VT_USA', 'VT_USA'), ) company = models.CharField( max_length=30, blank=True, null=True, choices=company_choice) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) project = models.ForeignKey(Allproject, on_delete=models.CASCADE) invoice_title = models.CharField(max_length=15) invoice_id = models.IntegerField(primary_key=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) invoice_amount = models.IntegerField() invoice_date = models.DateField( blank=True, null=True) invoice_duedate = models.DateField( blank=True, null=True) invoice_description = models.TextField() def __str__(self): return str(self.invoice_id) class Invoicedetails(models.Model): invoice = models.ForeignKey( Allinvoice, on_delete=models.CASCADE) total_amount = models.IntegerField() payment_id = models.IntegerField(primary_key=True) amountreceived = models.IntegerField() amount_left = models.IntegerField() date = models.DateField( blank=True, null=True) paymentmethod = models.ForeignKey( Allpaymentmethod, on_delete=models.CASCADE) def __str__(self): return str(self.payment_id) **So here for each individual Allinvoice table object i want to have multiple Invoicedetails record and with functional based views only,anyone please recommend me any example for such case ** Thanks -
How to connect in django s3 files storage from yandexcloud?
There are s3 from yandex cloud https://cloud.yandex.com/docs/storage/tools/?utm_source=console&utm_medium=empty-page&utm_campaign=storage How kan I configure django to use it ? -
Include foreign key in saving Django-Rest-Framework serializer
I am creating an API with Django Rest Framework. You can give a term to the api, it looks up data on a third party API and then everything should be stored to the database. All is handled in user scope and I have two tables, one with the search term and the ID of the user and another with the data received, which has the search_id as a foreing key. I now want that if you send a term to the API everything is stored and you get the search back, with ID and all dates. so far so good. I am now stuck, where I need to save the third party data to the database. The serializer demands the model object at saving and not the serializer from the user input. I tried around, but can't figure out, what I am doing wrong: models.py: class Search(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) term = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.term class foundTables(models.Model): search = models.ForeignKey(Search, related_name='search', on_delete=models.CASCADE) code = models.CharField(max_length=200) content = models.CharField(max_length=1000) time = models.CharField(max_length=200, blank=True, default='') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.content serializers.py class SearchSerializer(serializers.ModelSerializer): class Meta: model = … -
printing only first return HttpResponse in django
when i use 2 return HTTP Response in views.py in Django it is printing only first return. can anyone help to print the both return in the localhost of Django? -
formset factory with initial values or null
My models.py is rather simple: class Person(models.Model): name = models.CharField(max_length=254) class Question(models.Model): question_text = models.CharField(max_length=254) class Answer(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) question = models.ForeignKey(Question, on_delete=models.RESTRICT) answer_text = models.CharField(max_length =254) And now I want to create form, where user can enter answers for all questions. And the same form would be for editing it... (formset_factory looks properly) But there's a problem.... The user can answer none, all or some questions (I want to add questions after answering it, then user enters form, add some answers, maybe change already answered) So I be stacked if FormFactory should produce Question or Answer form. And how to show all even null answers? -
How to set default and auto_now value for django datetime model field
I want to set a default DateTime for my Django model that will be used in querying data from google fit api. Since this field will be empty in the beginning, the default value will allow for the first query and the auto_now will keep updating as more queries are made. Django seems not to allow both auto_now and default as arguments. Could anyone please assist with a workaround I could use to achieve this? models.py class GoogleStep(models.Model): user = models.OneToOneField(User, related_name='googlestep', on_delete=models.CASCADE) starttime = models.DateField(null=False) endtime = models.DateField(null=False) steps = models.IntegerField(null=False) last_sync = models.DateTimeField(auto_now=True, null=False) class Meta: ordering = ('-starttime',)