Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to change nav "active" class on different pages with base.html
I have my navbar on my base.html, so I extend it on all other pages. But I have a class "active" on the home page, so it also stays active in all other pages. <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" href="http://127.0.0.1:8000/backend/"> <i class="ni ni-shop text-primary"></i> <span class="nav-link-text">Dashboard</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes"> <i class="ni ni-ungroup text-orange"></i> <span class="nav-link-text">Clients</span> </a> </li> </ul> How can I change the active class to a different menu item based on the page I am? -
question regarding User model architecture
I would like to ask you about some architectural issues I face in my first django App in scope of User model. This App is used to manage employees and support their activities. Because I have no prior experience with Django I have decided to follow easiest path and use django built in User model. Based on it I have created a User model which should meet following requirements: there must be a User class, which represents App user and store all login data That User model must bee able to keep different attributes, specific for employee: like e.g. position, salary, There must be possibility to keep relations between Employees and Manager Each user needs to have its own profile which is used for customising App view Each user needs to belong to specific user groups which have a specific rights to view/modify/delete data from database - this is not implemented yet! As you can see on the diagram this model Is quite complicated and thus hard to manage. Even relativelly simple task (like get my manager id and assign a task for him) are complicated because I need to operate on 3 user classes (User, Employee, Manager) which keeps … -
Creating different admin that everyone has permission to see only the products he enter
I want to allow different sellers to see only their products on their ADMIN site, add products that only they will see (except the general manager) I attach the model of the products: class Item(models.Model): ***seller = models.ForeignKey(Seller, on_delete=models.CASCADE)*** name = models.CharField(max_length=20) manufacturer = models.CharField(max_length=20, blank=True) category = models.ForeignKey(Categories, on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_DEFAULT, default=types.item_types.GENERAL) slug = models.SlugField(max_length=200, db_index=True, blank=True) description = models.TextField(blank=True) image = models.ImageField(upload_to=r'ecommerce/pictures', blank=True) # adding date to the path? price = models.DecimalField(max_digits=10, decimal_places=2, blank=True) stock = models.PositiveIntegerField(blank=True) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) sales = models.BooleanField(default=False) Thanks to those who can advise me. -
Celery task as action in Django admin panel
I'm generating static website version through Django admin. It takes some time so I decided to use Celery. But it throws me this error: EncodeError at /admin/pages/project/ Object of type Project is not JSON serializable How can I call a command as action in Django admin panel using celery? admin.py from .tasks import command_task @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'updated', 'created', 'is_active') actions = ['export_to_static_version'] def export_to_static_version(self, request, queryset): if len(queryset) > 0: project = queryset[0] command_task.delay(project) models.py class Project(models.Model): dev_list = ['1', '2', '3', '4'] title = models.CharField(max_length=100) author = models.CharField(choices=dev_list), max_length=100, blank=True) comment = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(null=False, default=False) settings CELERY_BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_BEAT_SCHEDULE = {} celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic.settings.development') app = Celery('basic') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py from celery import task from django.core.management import call_command @task def command_task(project): call_command('generate_static_website', id=project.id) -
Django Form: Only show manytomany objects from logged in user
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created. Something like this: associated_portfolios manytomany field = ...objects.filter(user=user_id) I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin. Models.py class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250, blank=True, null=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = RichTextUploadingField(blank=True, null=True) associated_portfolios = models.ManyToManyField(Portfolio, blank=True) created_on = models.DateField(auto_now_add=True, editable=False) Views.py class PostCreate(CreateView): model = Post form_class = PostCreateForm def formfield_for_manytomany(self, db_field, request, **kwargs): self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user) return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs) forms.py class PortfolioCreateForm(ModelForm): class Meta: model = Portfolio fields = ['user', 'name', 'description'] class PostCreateForm(ModelForm): class Meta: model = Post fields = ['user', 'title', 'body', 'category', 'associated_portfolios'] -
Django Page not found (404) but URLs are correct
I encountered such an error, I get 404 error when trying to open the URL http://127.0.0.1:8000/account/ # apps/accounts/urls.py from django.urls import path from django.contrib.auth.views import LoginView from . import views urlpatterns = [ path('', views.index), path('login/', LoginView.as_view(template_name='account/login.html'), name="login") ] And the strangest thing is that if I add something like qwe/ in path http://127.0.0.1:8000/account/qwe it will work, and 2nd path login/ is working Can anyone tell me what the problem is? #apps/accounts/views.py from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('<h1>Hello</h1>') Main urls.py #project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("apps.main.urls")), path('account/', include("apps.account.urls")), ] -
How to avoid "'NoneType' object has no attribute" in Django query
A very simple questions, when I do complex query in Django, filter by item's foreign key's foreign key is common. just like # find out which house's owner's manager's company have a specific car House.objects.filter(Q(owner__manager__company__cars=specific_car)) So I have to ensure every foreign key in the chain is not None. Any field in the chain is None will couse AttributeError: 'NoneType' object has no attribute That is a nightmare. I could deal with that in real object by house.owner or house.owner.manager but how can I deal with queryset? -
relation "<a new model>" does not exist
I have a Django project consist of several apps. I've added a new model on my settings app: class DataFrameAdjustment(models.Model): """Configure Database bunch settings""" bunch_size = models.PositiveSmallIntegerField( default=0, blank=True, null=True) timeout = models.CharField( max_length=3, choices=Strings.TIMEOUT, default="3", blank=True, null=True) def __str__(self): return f"{self.bunch_size} - {self.timeout}" class Meta: verbose_name = 'Data Frame Adjustment' verbose_name_plural = 'Data Frame Adjustments' At the moment, I'm dealing with the following error: from settings.models import DataFrameAdjustment df = DataFrameAdjustment.objects.all() print(df) # For test. Out: Out[11]: --------------------------------------------------------------------------- UndefinedTable Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 UndefinedTable: relation "settings_dataframeadjustment" does not exist LINE 1: ...e", "settings_dataframeadjustment"."timeout" FROM "settings_... ^ The above exception was the direct cause of the following exception: ProgrammingError Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in pretty(self, obj) 403 if cls is not object \ 404 and callable(cls.__dict__.get('__repr__')): --> 405 return _repr_pprint(obj, self, cycle) 406 407 return _default_pprint(obj, self, cycle) /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle) 693 """A pprint that just redirects to the normal repr function.""" 694 # Find newlines and replace them with p.break_() --> 695 output = … -
How to save image on shared host filestorage from django app?
I have made an app using django and deployed it to heroku. I am using mysql database from a shared host & its working . I want to save my image file on shared host public_html folder & i created a folder named media inside public_html. So i changed the media url & root in django settings , the link is working but images doesn't save on public_html folder.But if i manually upload image in cpanel public_html folder then i can access it from my app. But i can not send image to that shared host. here is my settings.py: MEDIA_URL = f'http://www.example.com/media/' MEDIA_LOCATION = "media" -
Send X-CSRF Token to a Django server using XHTTP Request or jQuery Ajax
I've been trying to make a POST to my Django application via XHTTP Request and jQuery with no correct result at all. The fact is that the Django app is on one of my subdomains, and the web app is in another, not being part of the Django app, just only a separated app. I've been reading the docs, but none of this works. All of my subdomains are in the ALLOWED HOSTS list and in the CORS ORIGIN WHITELIST, and the petition works correctly with GET, but POST returns me a Forbidden 403 error telling CSRF Cookie not found. This is the code of my petition. var petition = new XMLHttpRequest(); petition.open('POST','http://localhost:8000/login/',true); petition.setRequestHeader("X-CSRFToken",sessionStorage["csrf_token"]); petition.send() I already have stored the CSRF cookie in the session storage with this function. function storeCSRFToken(){ var token; $.ajax({ url : 'http://localhost:8000/token', type: "GET", dataType : "json", success: function( data ){ token = data.csrf_token; sessionStorage['csrf_token'] = token; } }); } Any clue of what is going wrong? -
How to update multiple objects in django rest framework?
I am trying to update multiple objects using IDs which i am passing in every objects that need to be updated but can't find any way to do it successfully. Here is my code models.py class EventTicket(models.Model): id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False) name = models.CharField(max_length=250) description = models.TextField(max_length=1000) views.py ``` class EventTicketView(APIView, PaginationHandlerMixin): permission_classes = (AllowAny,) def get_object(self, ticket_id): try: return EventTicket.objects.get(id=ticket_id) except EventTicket.DoesNotExist(): raise status.HTTP_400_BAD_REQUEST def patch(self, request, *args, **kwargs): for each_ticket in request.data: ticket_id = self.get_object(each_ticket['ticket_id']) serializer = EventTicketSerializer(instance=ticket_id,data=request.data,partial=True) if serializer.is_valid(): serializer.save() result = { 'message': "updated sucessfully" } return Response(result, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ``` ``` serializers.py ``` ``` class EventTicketSerializer(serializers.ModelSerializer): class Meta: model = EventTicket fields = ['name', 'description'] ``` I have to send data like list of multiple objects ::: [ { "ticket_id": "054665ea-4fde-11ea-94b2-9f415c43ba4c", "name": "chris", "description":"The golden ticket for day only", }, { "ticket_id": "054656ea-4fde-11ea-94b2-9f415c43ba4c", "name": "daut", "description":"The premium ticket for day only", } ] -
Django smtp gmail not working in production
I'm using django to send email through gmail smtp. It only works, however, before deployment. In production or deployment whatever you call, when I try to send email it keep being loaded forever and only says 'Server Error 500'. Below is part of my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config['EMAIL_USER'] EMAIL_HOST_PASSWORD = config['EMAIL_PASS'] Below is .../django_project/users/views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) What's confusing is my tutorial videos didn't put any from django.core.mail import send_mail or something. So I'm not sure whether the view.py above is the one that … -
'int' object has no attribute 'disabled' Django
I am trying to pass a specific value to a field in django form but keep getting this error: 'int' object has no attribute 'disabled' Forms.py class AllotmentDocketForm(forms.ModelForm): class Meta: model = AllotmentDocket fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['sales_order'].queryset = MaterialRequest.objects.filter(is_allocated=False) self.fields['transaction_no'].disabled = True max_quant = AllotmentDocket.objects.filter(transaction_no__isnull=False).aggregate(Max('transaction_no')) max_quantity = max_quant.get('transaction_no__max') print("max transaction_no", max_quantity) self.fields['transaction_no'] = max_quantity + 1 Why is it not allowing me set transaction_no to a value ? -
NameError: name 'Model' is not defined after importing models in a newly created file
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this. Here is a screenshot showing where the file is located. How I'm importing the models in the utilities.py file from .models import * Error -
Create json file for many to many fields in django
model.py class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Question(models.Model): name = models.CharField(max_length=255) Tag_name = models.ManyToManyField(Tag) I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it. Tag json look like: [ { "name": "a" }, { "name": "b" } ] Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ? -
RelatedObjectDoesNotExist. User has no profile
I've read some other answers for this (almost) question but they didn't help. I have the following 2 files mixed for user and profile apps(?). In other answers they said this happens if you don't use >objects.get_or_create or not making signals.py file you'll get this error but I've gone through both of those ways and no results. This is the traceback I get: Environment: Request Method: GET Request URL: http://127.0.0.1:3000/profile/ Django Version: 3.0.3 Python Version: 3.7.3 Installed Applications: ['blog', 'users', 'crispy_forms', 'django_cleanup', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/wss/Desktop/projects/python/django/mahour_sanat/mahoursanat/users/views.py", line 38, in profile p_form = ProfileUpdateForm(instance=request.user.profile) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 225, in inner return func(self._wrapped, *args) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 423, in __get__ self.related.get_accessor_name() Exception Type: RelatedObjectDoesNotExist at /profile/ Exception Value: User has no profile. forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() … -
Python or django product management framework
I need product management system for django or python. For example Facebook have html pages for adding new products with graphAPI; Example html for facebook products <!DOCTYPE html><html> <head prefix= "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# product: http://ogp.me/ns/product#"> <meta property="og:type" content="og:product" /> <meta property="og:title" content="Friend Smash Coin" /> <meta property="og:image" content="http://www.friendsmash.com/images/coin_600.png" /> <meta property="og:description" content="Friend Smash Coins to purchase upgrades and items!" /> <meta property="og:url" content="http://www.friendsmash.com/og/coins.html" /> <meta property="product:plural_title" content="Friend Smash Coins" /> <meta property="product:price:amount" content="0.30"/> <meta property="product:price:currency" content="USD"/> <meta property="product:price:amount" content="0.20"/> <meta property="product:price:currency" content="GBP"/> </head> </html> I need to manage three store, "Facebook Store", "Google Play Store", "Apple Store products with my django application, So searched github etc. For any open-source project for managing that store products. I couldnt find it. -
Get maximum value of a field in django
I have a model Foo in my models.py like this: class Foo(models.Model): transaction_no = models.IntegerField(default=0, blank=True, null=True) transaction_date = models.DateField(default=datetime.now) quantity = models.IntegerField(default=0, blank=True, null=True) I want to get the max quantity from the table. How can I get that? -
UnicodeDecodeError python django framework
im a bit new with python and django framework. I already setup the project in my virtual env. It was working fine before i update my windows 10. as of now, i'm running into an error related to the this UnidecodeError In my virtual environment, i have already install these libraries. python 3.8.1 (32-bit) - installed locally. asgiref==3.2.3 certifi==2019.11.28 cffi==1.14.0 chardet==3.0.4 cryptography==2.8 Django==3.0.3 django-appconf==1.0.3 django-crispy-forms==1.8.1 django-cryptography==1.0 django-mssql-backend==2.7.0 idna==2.8 pycparser==2.19 -pyodbc==4.0.28 pytz==2019.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 urllib3==1.25.8 django-adminlte3==0.1.2 The error started when i updated windows. Any idea how to solve this? Things that i've tried update using 64-bit python version update my system locale -
How to use FilerImageField in html template?
I want to know how to use FilerImageField in html tag. i tried <image src={{ instance.team_background_image_1.file.url }}> it display full image. but i want to use FilerImageField in many resolutions such as 300x300, 250x300 -
Render template by django templatetags
This is my .html file {% for date in field %} <div class="col-md-6"> <span class="input-group date datetimepicker" data-min-view="2" data-date-format="yyyy/mm/dd"> <span class="input-group-append"> <button class="btn btn-secondary"><i class="icon-th mdi mdi-calendar"></i></button> </span> {{ date }} </span> </div> {% endfor %} and print(field) is <input type="text" name="date_after" class="form-control" id="id_date_0" /> <input type="text" name="date_before" class="form-control" id="id_date_1" /> show in the template like https://imgur.com/1GQuCgj Can I render this two input tags separately? hope someone can help this, thx! -
Saving Nested Django Serializer
I have 3 models. Question, Choice, and Cover. Question can have many choices and each choice can have only 1 cover. I implemented the Question and Choice as serializers and it worked successfully, now i'm trying to add on the Cover. Here's what I have: class CreateQuestionSerializer(serializers.ModelSerializer): choice_set = ChoiceSerializer(many=True) class Meta: model = Question fields = ('user', 'status', 'choice_set') def create(self, validated_data): choices_validated_data = validated_data.pop('choice_set') question = Question.objects.create(**validated_data) choices_serializer = self.fields['choice_set'] for choice in choices_validated_data: choice['question'] = question choices_serializer.create(choices_validated_data) return question class ChoiceSerializer(serializers.ModelSerializer): choice_cover = ChoiceCoverSerializer(many=False) class Meta: model = Choice fields = ('choice', 'choice_cover') class ChoiceCoverSerializer(serializers.ModelSerializer): class Meta: model = ChoiceCover fields = ('cover',) When I try to save data like so: { "user": 179, "question": "Who will win the election?", "choice_set": [ { "choice": "Lorem", "choice_cover": "C4FF33" }, { "choice": "Ipsum", "choice_cover": "FF5733" } ] } I get the following error: { "choice_set": [ { "choice_cover": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } }, { "choice_cover": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } } ] } How can I fix this? -
Override Bootstrap Admin templates in Django
I'm using the Bootstrap admin library in order to use Bootstrap templates in admin. Now I want to override the Bootstrap admin templates. I followed the instructions given in their documentation: https://github.com/douglasmiranda/django-admin-bootstrap#branding---overriding-logo But it's not working. Here is my templates variable: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'vspmschool/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django RF - How to insert into pivot table using name instead of id without querying the id?
For example I have the ff: models: class Store(models.Model): name = models.CharField(max_length = 20) class Product(models.Model): name = models.CharField(max_length = 20) class StoreProducts(models.Model): store = models.ForeignKey(Store) product = models.ForeignKey(Product) qty = models.IntegerField() serializer: class StoreProductsSerializer(serializers.ModelSerializer): class Meta: model = StoreProducts fields = ('store', 'product', 'qty') And defined values: Store (id, name): 1, store_1 2, store_2 Product (id, name): 1, product_1 2, product_2 Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this: data = { 'store': 'store_1', 'product': 'product_1', 'qty': 1 } serializer = RobotSerializer(data=data) if serializer.is_valid(): serializer.save() Is this possible and how? Thanks -
How to use Django url template tag with variable as url path
I encountered a No Reverse Match Error in trying to render a template. Can you explain what this No Reverse Match Error mean for easier understanding and how to solve the error? from django.contrib.sites.models import Site from django.contrib.gis.db import models from django.utils.crypto import get_random_string from django.contrib.gis.geos import GEOSGeometry,Point from django.contrib.auth.models import AbstractUser from django.shortcuts import render # Create your models here. class User(AbstractUser): pass geos_pnt=Point(4314498.56, 1003834.600,srid=3857) #pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt class Apartment(models.Model): SUBCITY_CHOICES = ( ('ADK', 'Addis Ketema'), ('AKLTY', 'Akaki-Kality'), ('ARD', 'Arada'), ('BL', 'Bole'), ('GL', 'Gulele'), ('KLF', 'Kolfe-Keranio'), ('LDTA', 'Ledeta'), ('NFS', 'Nefas Silk'), ('YK', 'Yeka')) apt_id = models.CharField(str(SUBCITY_CHOICES)+"-"+get_random_string(length=4), max_length=8,primary_key=True) location = models.PointField(default=geos_pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31), blank=True, null=True, srid=3857, help_text="Point(longitude latitude)") no_bedrooms= models.IntegerField(null=True) apt_area = models.IntegerField(default=0, null=True) apt_cost = models.IntegerField(default=0, null=True) apt_subcity = models.CharField(default='Nefas Silk',max_length=100, choices=SUBCITY_CHOICES,null=True) register_date = models.DateTimeField('Register Date',auto_now_add=True,null=True) slug = models.SlugField(unique=True) objects = models.Manager() sites =models.ManyToManyField(Site) #change points from apt_rent_db to kml def pointkml(self): points = Apartment.objects.kml() return render("placemarks.kml", {'places': points}) def get_absolute_url(self): return reverse('apartment_create', kwargs={'pk': self.pk, 'apt_id': self.apt_id.pk}) def save(self, *args, **kwargs): #self.Latitude = self..y #self.Longitude = self.location.x self.slug = slugify(self.apt_id) super(Apartment, self).save(*args, **kwargs) class Meta: # order of drop-down list items verbose_name = ("Apartment") verbose_name_plural = ("Apartments") ordering = ('apt_cost',) app_label = 'rent_app' def __unicode__(self): return self.apt_id the html: <html> <head> {% …