Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save only a single element into a ManyToManyField
I have an app wich has a Meet and this meet could have only one guest or more than one guest. I defined Meet model with a ManyToManyField relationship with User and a field to choice if the meet is going to be with single guest or it'll be in a team (with many guests) as follow: class Meet(IndexedTimeStampedModel): kind_meet = models.CharField(max_length=50, choices=MEET_CHOICES) guests = models.ManyToManyField(User, related_name='guests') I did a form with Meet Model, so first the user select the kind of meet that he would like to do and on the next page he will select the guest or guests of the meeting. My fight is, if the user choose a single meet how can I force him to select just one guest on a select box in a template? On my ModelForm, I try to restrict this defining the widget of guests field as Select but ManyToManyField just accept a list of values and Select return the value as string not a list. This cause an error "Enter a list of values" when I submit the form. My second try was change the widget to SelectMultiple but this allow the user to select more than guest. class Meta: … -
At Django pagination template code <a href="?page=...">, why does url link start with "?page="?
At Django pagination template code <a href="?page={{page_obj.previous_page_number}}> why does url link start with ?page=? Why is there no root(?) url in this code? for example, at url pattern path('post/', views.PostLV.as_view(), name='post_list'), <a href="post/?page={{page_obj.previous_page_number}}> I think post/?page=... is right than ?page=. -
How to prevent Django from renaming key column in model with managed=False?
I have two models in Django with managed=False, because they are generated by SQL. Django's Querysets based on these models do not generate the SQL queries they should. They add an '_ID' suffix to a column name that I never specified. This causes the queries to fail. The models: class MaterialsPerBatch(models.Model): BATCH = models.CharField(null=False, max_length=255) MATERIAL = models.ForeignKey('ColumnsPerMaterialStatic', on_delete=models.CASCADE) class Meta: db_table = "CDH_MATERIALS_PER_BATCH" managed = False class ColumnsPerMaterialStatic(models.Model): MATERIAL = models.CharField(primary_key=True, null=False, max_length=255) MATERIAL_LINK = models.CharField(null=False, max_length=255) class Meta: db_table = "CDH_COL_PER_MAT_STATIC" managed = False I want to filter the first model by BATCH, and find all corresponding second models that share the MATERIAL field. The query looks like this: qs = models.MaterialsPerBatch.objects.filter( BATCH__in=['foo', 'bar']).values('BATCH', 'MATERIAL__MATERIAL_LINK') I get this error: "django.db.utils.DatabaseError: ORA-00904: CDH_MATERIALS_PER_BATCH"."MATERIAL_ID": invalid identifier" Inspecting qs.query shows that Django runs the following query in the background: SELECT "CDH_MATERIALS_PER_BATCH"."BATCH", "CDH_COL_PER_MAT_STATIC"."MATERIAL_LINK" FROM "CDH_MATERIALS_PER_BATCH" INNER JOIN "CDH_COL_PER_MAT_STATIC" ON ("CDH_MATERIALS_PER_BATCH"."MATERIAL_ID" = "CDH_COL_PER_MAT_STATIC"."MATERIAL") WHERE "CDH_MATERIALS_PER_BATCH"."BATCH" IN ('foo', 'bar') So the question is, why does Django turn "CDH_MATERIALS_PER_BATCH"."MATERIAL" into "CDH_MATERIALS_PER_BATCH"."MATERIAL_ID"? I never specified any '_ID' suffix. How do I tell Django not to add that suffix? -
Generate automatic username for user upon registration using their input and my python script
I have a Django project set up with the basic User Registration models set up as standard. My user database currently collects a username, email and password on registration. I would like to make it so that the username is generated for the user automatically and stored with the email and password in my database. I have how the I'd like to generate this username with the below python script - import random import string import datetime def getFirstInitial(): firstInitial = firstName[0] return firstInitial def getMidInitial(): middleInitial = middleName[0]; return middleInitial def getLastInitial(): lastInitial = lastName[0] return lastInitial def createUsername(): username = getFirstInitial() + getMidInitial() + getLastInitial() + randomStringDigits(6) + getDateTimeStr() firstName = input(); middleName = input() or "0"; lastName = input(); createUsername() My current user forms.py - from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() firstname = forms.CharField(max_length=20) middlename = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'firstname', 'middlename', 'lastname'] My current user views.py - from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() … -
Django looks in `templates` when loading static file
I am new to Django and I have the following issue: when I try lo link my layout.html to styles.css Django looks in the wrong place. The layout.html code which reads: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css'}" rel="stylesheet"> </head> and the structure of my encyclopedia dir is as follows: ├── db.sqlite3 ├── encyclopedia │ ├── __init__.py │ ├── __pycache__ │ ... │ ├── models.py │ ├── static │ │ └── encyclopedia │ │ └── styles.css │ ├── templates │ │ └── encyclopedia │ │ ... └── search.html │ ├── tests.py │ ├── urls.py │ ├── util.py │ └── views.py ├── manage.py └── wiki I did check the `settings.py` file in dir `wiki` and it does have a: `STATIC_URL = '/static/'` line. Yet Django keeps looking in `templates` as per the following error message: [![error message from VS Code][1]][1] Can anyone tell me what I am doing wrong? [1]: https://i.stack.imgur.com/SoBYv.png -
DRF How to structure urls for photo sharing web app? (Structure/Best practice)
Currently building backend API using Django Rest Framework for a group photo-sharing project. I'm trying to understand what's the best way to structure my API endpoints and I've encountered a problem (more like a question) for the best way to implement it. Here are my models: class Photo(models.Model): uploader = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="photos" ) image = models.ImageField(upload_to=get_image_path) upload_date = models.DateField(auto_now_add=True, editable=False) class Collection(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=500, blank=True) thumbnail = models.ImageField(blank=True) creator = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="created_collections" ) members = models.ManyToManyField(CustomUser, related_name="collections") photos = models.ManyToManyField(Photo, related_name="collections") Basically each user can create a Collection model which holds different photos he can share with others and they can upload too. The endpoints I have right now are the basic ViewSet ones: Photo: /api/photo GET/POST /api/photo/id GET/DELETE/PATCH Collection: /api/collection GET/POST /api/collection/id GET/DELETE/PATCH My question is: What should be the endpoint for a user to add a photo to a collection? (the best way to implement it) I've thought of a few options which are: 1.POST request to /api/collection/id containing the ID of the photo I want to add. 2.POST request to /api/photo/id containing the ID of the collection I want to add the photo to. 3.Using a PATCH method maybe? … -
How to implement concurrent requests rate limit at client side
My python/django distributed application has to integrate with a third party api which has a restriction of say 20 concurrent requests per minute. It blocks us for a specified period of time if we exceed this limit. How do we implement this limit in our application so that we do not end up making more than 20 concurrent requests to the client. We have been able to implement per min or per hour based rate limit using redis but I am not sure how to achieve this concurrent requests issue. Is this possible to achieve this using redis ? -
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