Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Abstract Models support to django-rest-framework-mongoengine
In a Django project I am using mongoengine that provides Django style models to MongoDB collections. I am also using django-rest-framework-mongoengine witch extends DRF to support Documents, EmbeddedDocuments, DynamicDocuments and DynamicEmbeddedDocuments the MongoEngine model representation of MongoDB. While Django and DRF allow for using abstract classes in the Models. This is now supported by DRF-mongoengine. However i believe it is possible to add support for abstract Models by writing custom Serializers. So far I was unable to succeed and I would appreciate your help in getting this to work. class Entry(Document) meta = { 'abstract': True, 'allow_inheritance': True, } text = StringField() class Post(Entry) meta = { 'allow_inheritance': True, } class comment(Entry) meta = { 'allow_inheritance': True, } post = ReferenceField(Post) # No Problem serializing this # for the sake of Demonstration, related is a list of posts and comments related = ListField(ReferenceField(Entry)) # This is not supported by DRF-mongoengine class PostSerializer(DocumentSerializer) # Works class Meta: model = Post fields = '__all__' class PostsViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentSerializer(DocumentSerializer) # Fails class Meta: model = Comment fields = '__all__' class CommentsViewSet(ModelViewSet): serializer_class = CommentSerializer queryset = Comment.objects.all() What I am currently trying to do is to write … -
SonarScanner Error "Line is out of range in the file"
So I'm doing my django project normally, then, out of nowhere I got this error from my SonarScanner when I refactored the function names in formulas.py (and only that, I didn't tweak my sonar.properties nor my ci.yml file): java.lang.IllegalStateException: Line 308 is out of range in the file dietela_quiz/formulas.py (lines: 306) then I decided to add more whitespaces so it reaches 308 lines but ever since then, the error persists, and as I add more whitespaces or even created a dummy function (to increase the length of file legitimately), an error pattern was established like this: java.lang.IllegalStateException: Line n+1 is out of range in the file dietela_quiz/formulas.py (lines: n) where n is the actual number of lines in formulas.py this is my yml file: stages: - test - sonar-scanner - deploy UnitTest: image: python:3.6.5 stage: test before_script: - pip install -r requirements.txt - python manage.py makemigrations - python manage.py migrate - python manage.py collectstatic --no-input - python manage.py runserver 8000 & when: on_success script: - echo "Starting linter..." - sh linter.sh - echo "Starting tests..." - coverage erase - DATABASE_URL=$TEST_DATABASE_URL coverage run --include="./dietela_quiz/*","./nutritionists/*","./dietela_program/*" manage.py test --keepdb - coverage xml -i - coverage report -m artifacts: paths: - coverage.xml SonarScanner: image: … -
Django: Allow data entry into only one of multiple fields of a model
I have a model that needs to be able to store some data. The trouble is, that data may be a number, string, choice or textfield. My models.py looks something like this: class Period(models.Model): """The quarter and the year. May be visualized as the X axis.""" pass class FSLI(models.Model): """Financial statement line items. May be visualized as the Y axis.""" data_type = models.CharField(max_length=20, choices=DATA_TYPE, default='number') class Company(models.Model): """The company to which the data relates. May be visualized as the Z axis.""" pass class FSType(models.Model): """Consolidated or standalone. May be visualized as the report filter.""" pass class Datapoint(models.Model): """A single cell in the above table that points to some data.""" period = models.ForeignKey("Period", on_delete=models.CASCADE, related_name="period_dps") fsli = models.ForeignKey("FSLI", on_delete=models.CASCADE, related_name="fsli_dps") company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="company_dps") fstype = models.ForeignKey("FSType", on_delete=models.CASCADE, related_name="fstype_dps") number = models.FloatField(null=True, blank=True) text = models.CharField(max_length=255, blank=True) choice = models.CharField(max_length=20, choices=DP_CHOICES, blank=True) # Another model will store choices bigtext = models.TextField(max_length=4000) Each Datapoint may contain value only for ONE of number, text, choice or bigtext. The type of data will be determined by the data_type field of the FSLI object. Is there some simple way to ENFORCE this? Maybe by splitting up the Datapoint model into multiple models? -
Django Template Syntax Error - Django Webpack
I'm working on a django webpack bundle. I got a ready template on github. I made a few changes on it. I prepare for future use according to my own file hierarchy. But I am having a problem with template synxtax. First, there is base.html in my project. Thanks to this page, the background of the pages that I will create in the future is formed. Some files were imported in base.html. These are implemented using render_bundle and static tags. I created a new page to be rendered in django. Likewise, I want to import assets/js/table.js and assets/scss/table.scss files on this page separately from other pages. but I am getting a template syntax error. Where do you think I'm making a mistake? i got this error base.html {% load render_bundle from webpack_loader %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block meta %} {% endblock meta %} <title> {% block title %} {% endblock %} </title> <!-- You should added this tags for production files !!! --> {% render_bundle 'app' 'css' %} {% render_bundle 'myapp' 'css' %} <link href="/media/favicon.png" rel=icon> {% block head %} {% endblock %} </head> <body> {% include "navbar.html" %} <!-- Content … -
Django ORM calling the stored procedure in postgresql
I am building a project using Django, I'm thinking What is the best practice on calling the stored procedures in Postgresql using Django ORM? -
Two foreign key fields to one model as an inline in the Admin
I have an artist which has a primary and a secondary contact. I would like to add these two contacts from the Artist admin. But right now both fields are clashing. Any ideas? Thanx in advance. class Contact(models.Model): full_name = models.CharField('Full name', max_length=255) email = models.EmailField() phone = models.CharField('Phonenumber', max_length=255) class Artist(models.Model): name = models.CharField('Name', max_length=255) country = models.CharField(choices=COUNTRIES, max_length=32) contact_1 = models.ForeignKey(Contact, related_name = '+', on_delete=models.CASCADE) contact_2 = models.ForeignKey(Contact, related_name = '+', on_delete=models.CASCADE) class Contactline(admin.TabularInline): model = Contact class ArtistAdmin(admin.ModelAdmin): inlines = [ContactInline] -
hello guys, i have been trying to activate my folder for django but it only kept showing this, can anybody help me
PS C:\users\honnu\onedrive\desktop\yusuf\python\py4e\trydjango> Scripts\activate.ps1 **Scripts\activate.ps1 : The module 'Scripts' could not be loaded. For more information, run 'Import-Module Scripts'. At line:1 char:1 + Scripts\activate.ps1 + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Scripts\activate.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoLoadModule** -
"<CustomerOrder: admin>" needs to have a value for field "id" before this many-to-many relationship can be used
I want to owerride for my order. But I get an error because it is "ManytoMany" field. views.py: orderform = OrderForm() if request.method == 'POST': orderform = OrderForm(request.POST) if orderform.is_valid() and int(orderform["customer"].value()) == customer[0].id: test = orderform.save(commit=False) orderitems = OrderItem.objects.filter(customer_id=customer[0].id) test.orderitem.add(orderitems ) orderform.save() return redirect('home') models.py class CustomerOrder(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) orderitem = models.ManyToManyField(OrderItem, related_name="orderitem") dealer = models.ForeignKey(Dealer, default=1, on_delete=models.CASCADE) status = models.CharField( max_length=200, choices=WORK_STATUS, default="Waiting", ) pay_method = models.CharField( max_length=2, choices=PAY_METHOD, default=1, ) -
Django - Many to One relationship not working
i am trying to create a relationship between my user model and my article model. Each user can have many articles but each article belongs to one user. When i go to my rest framework and create a user and an article they are not linked together. I think i am missing something in the relationship since when i enter my Article Details i am not entering anything related to the user. MyApp>models.py from django.db import models class User(models.Model): firstname = models.CharField(max_length=255, null=True, blank=False) lastname = models.CharField(max_length=255, null=True, blank=False) email = models.EmailField(null=True, blank=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Article(models.Model): user: models.ForeignKey(User, null=True, blank=False, on_delete=models.SET_NULL) title = models.CharField(max_length=255, null=True, blank=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title MyApp>serializer.py from rest_framework import serializers from .models import User, Article class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id','firstname', 'lastname', 'email'] class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title'] MyApp>views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer -
retrieving a value from nested dictionary API
Im trying to ovveride a POST request from API View and i requested a form like that: { "chp_reference":"522", "income_period":"Weekly", "property_market_rent":"400", "number_of_family_group":"3", "rent_effective_date":"2020-12-4", "state":"NSW", "family_group": [ { "name":"FG_1" }, { "name": "FG_2" } ], "family_member":[ { "name":"FG_1" } ] } FamilyGroup is a child model to Transaction , FamilyMember is also a child for Transaction and FamilyGroup im trying to make a POST request that Include FamilyGroup and Familymember inside Transaction like that: @api_view(['POST', ]) def post_api(request): transaction_data = request.data serializer = TransactionSerializer(data=transaction_data) family_groups = transaction_data["family_group"] family_members = transaction_data["family_group"] fg_ids = [] new_transaction = Transaction.objects.create(chp_reference=transaction_data['chp_reference'], income_period=transaction_data['income_period'], property_market_rent=transaction_data['property_market_rent'], number_of_family_group=transaction_data['number_of_family_group'], rent_effective_date=transaction_data['rent_effective_date'], state=transaction_data['state']) new_transaction.save() for fg in family_groups: c = FamilyGroup(name=fg["name"], transaction=new_transaction ) c.save() for fm in family_members: b = FamilyMember( transaction=new_transaction, family_group=c, name=fm["name"] ) b.save() return Response('Added') but when doing so , im only getting FG_2 , basically it returns me the last name of FamilyGroup and FamilyMember... I would like to return the whole list of names.. would appreciate any suggestion -
Django: template extends. Child template don't find the static image
I'm learning django for a personal project. In this project i create at the first time two app "API" and "Search". Later during the develop i decide to combine search inside API and update the views of "API" with the function that was in the "Search". I create later a base template that render to two different html exstend from the base template.In the first templates (wind_index.html) all the element of the page are perfectly loaded, carousel navbar image etc. when i load in the browser the other templates (search.html), also exstend with the base.html, everything is loaded beside the images of the carousel. Structure of the project: WindPortal API static templates API base.html wind_index.html wind_search.html (here where was my old APP "Search") WindPortal rest of the file setting,urls This is my Setting.py: i set up in APP_DIRS= False for try to don't load anymore file from the old directory but seems not working. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'API', 'templates')], 'APP_DIRS': False, '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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( 'WindPortal/API/static', 'static/img', ) terminal error: 29/Mar/2021 13:10:17] "GET / HTTP/1.1" 200 3754 [29/Mar/2021 13:10:17] "GET /static/API/style.css … -
How to add bootstrap img-fluid class to images using django-quill-editor
I am working on a blog project with Django using the django-quill-editor. Like the documentation says, I have imported QuillField and added it to my model as shown below. I have also added it to my admin. Now the problem is that whenever i insert an image into the content field of the editor, The image is displayed fully on the details page of the blog. the image is not contained in any div, making it look out of proportion. I realize this is happening because the bootstrap class 'img-fluid' is not applied to the image. I want the image to fit into the text area. So I want know how to customize django quill editor to do this. I can't seem to find it in any documentation for django. models.py from django_quill.fields import QuillField # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts') content = QuillField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) banner = models.ImageField(upload_to='banners/', blank=True, null=True, default='/banners/blog-1.jpg') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post, Comment … -
How to pass the correct information to Django modal in templates
So I am able to create a list of all the senders who sent a message to a particular user in Django templates but what I would like to do is that when a user clicks on the view button, A modal should pop up and show what the message is. So for example. If I click on "XYZ sent you a message", I should be able to see what the message is in a pop-up modal. The HTML code I have written sho far: {%for elements in messages %} <ul class="list-group shadow p-3"> <li class="list-group-item"> <img src="{{elements.sender.userprofile.profile_pic.url}}" width="40px" height="40px"> {{elements.sender}} sent you a message </li> <button data-toggle="modal" data-id="{{ elements.pk }}" data-target="#myModal1" class="open-my-modal"> View </button> </ul> {%endfor%} The Modal that should show the message. <div class="modal" id="myModal1"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Ending Survey</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> {{elements.message1}} <h5>here mate</h5> </div> </div> </div> </div> I have tried countless ways. Thank you and Regards -
partial sync of model in django-elasticsearch-dsl
I'd like to do a "partial sync" of model between django and elasticsearch using this library (or any other module for that matter - please suggest). What I mean by "partial sync" is: on the elasticsearch side I have an index with fields _id, FIELD0, field1, field2... on the django side I have a model with fields id(primary key), FIELD0, fieldA, fieldB... I would like to have field0 changes pushed to elasticsearch side whenever it changes on django side. With what I have currently: # in documents.py from django_elasticsearch_dsl import Document as elastic_Doc from django_elasticsearch_dsl import fields from django_elasticsearch_dsl.registries import registry @registry.register_document class elastic_Document(elastic_Doc): class Index: name = 'some_index' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = SomeModel # just one field to the elastic index # this unfortunately removes other fields... fields = ['FIELD0'] the fields that I don't specify to be synced get wiped out on the elasticsearch side. Any suggestion of how this could be achieved would be very appreciated. -
Django JsonField filter by two fields
class Blog: values = JSONField( blank=True, default=list) [ { "id": 1, "value": "31" }, { "id": 2, "value": "Hello" }, ... ] I need to get all objects where the id is 1 and value of that field is greater than 31. I have tried q = queryset.filter(values__0__id=1, values__0__value_gte=31) but it works only for objects if an object that I need located only in first element. -
How to filter REST API using django
i have a program to filter REST API using django , but whenever i try to filter it is showing all the response data again , no idea why . so can anyone help me ... posting the rest api response { "output": "success", "data": [ { "IPadd": "17629082", "Mobiles": { "output": "success", "data": [ { "Name": "samsung js", "price": "100", "count": "1" }, { "Name": "Samsung j13", "price": "100", "count": "3" } ] } } ] } and the method i used to get it . response = requests.get('http://abcd/users/?Name="samsung js"') details = json.loads(response.text) print(details) but it returns everything , once again .... Can anyone help me sort it out . -
Django REST Framework filter by Foreign key
First of all, please consider that I'm very new in Django so I'm not really sure about what I'm looking for. I have a model called Product: class Product(models.Model): name = models.CharField('Name', max_length=100) ... One Product can have several variants so I created another model called ProductVariant which has a ForeignKey to Product. class ProductVariant(models.Model): name = models.CharField('Name', max_length=100) product = models.ForeignKey(Product, verbose_name='Produkt', related_name='productvariants', on_delete=models.CASCADE) ... I want to return only the Products that have Variants but I don't know how to access that information from the Product Filter or Product Serializer, since the ForeignKey is on the ProductVariant model. Any ideas? I know this is basic Django but I'm completely new, any help would be really appreciated. This is my Product Filter: class ProductFilter(filters.FilterSet): class Meta: model = Product fields = ['id', 'name'] The Product Serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name') The Product ViewSet: class ProductViewSet(ModelViewSet): queryset = Product.objects.all() filterset_class = ProductFilter serializer_class = ProductSerializer permission_classes = [IsAuthenticated] -
Using ModelFormMixin (base class of PostDetailView) without the 'fields' attribute is prohibited
Form button does not work. After adding ModelFormMixin, the error "Using ModelFormMixin (base class of PostDetailView) without the 'fields' attribute is prohibited" appears. This is my #views.py code class PostDetailView(ModelFormMixin, DetailView): model = Post template_name = 'articles/article_details.html' context_object_name = 'post' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) stuff = get_object_or_404(Post, slug=self.kwargs['slug']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked self.object.views = F('views') + 1 post = get_object_or_404(Post, slug=self.kwargs['slug']) if self.request.method == 'POST': form = CommentForm(data=self.request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = self.request.user comment.save() return context else: form = CommentForm() context["form"] = form self.object.save() self.object.refresh_from_db() return context This is my #forms.py code class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) widgets = { # 'author': forms.Select(attrs={'class': 'form-control'}), # 'author': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } This is my #models.py code class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", verbose_name='Публикация', on_delete=models.CASCADE) author = models.CharField(max_length=255, verbose_name='Автор') # author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(verbose_name='Комментарий') is_active = models.BooleanField(default=True, verbose_name='Опубликовано', db_index=True) comment_date = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return '%s - %s' % (self.post.title, self.author) class Meta: ordering = ['comment_date'] This is my #article_details.html code <div class="form-group"> <form method="POST"> {% csrf_token %} … -
Django Rest Framework - Making efficient APIs
How can we make APIs efficient in terms of responding time and processing time? What are they ways, would you please clarify? Can we use caching for the APIs? -
Decorator that includes celery task with attributes
I'm working on a Django project with several apps, each of them have their set of tasks and it works pretty fine. But, in general, the set of tasks of each app use the same attributes for rate limiting, retry, etc. I was trying to create a decorator that would have all those common attributes and set the target function as a task. So, I have this in my example/tasks.py: from celery import current_app @current_app.task( queue='example_queue', max_retries=3, rate_limit='10/s') def example_task_1(): ... @current_app.task( queue='example_queue', max_retries=3, rate_limit='10/s') def example_task_2(): ... I'm trying something like: from celery import current_app, Task class ExampleTask(Task): def __init__(self, task, *args, **kwargs): super().__init__(self, *args, **kwargs) self.task = task def run(self): self.task.delay( queue='example_queue', max_retries=3, rate_limit='10/s') def example_decorator_task(func): @wraps(func) def wrapped(self, *args, **kwargs): return ExampleTask(func) @example_decorator_task def example_task_1(): ... @example_decorator_task def example_task_2(): ... This code does not work and I'm sure it is not that hard to do this, but I'm not getting it. Any ideas? -
pass data from db to template without a view
I am trying to display a placeholderfield in my template but it's not showing anything. I think it's because I am passing data from db to my template using a plugin class ElmentsList(CMSPlugin): Elements = Element.objects.all() Composition_1 = Composition_1.objects.all() then in my template {% if instance.Composition_1 %} {% for Composition in instance.Composition_1 %} {% if forloop.counter == 1 %} {% render_model_add Composition %} {% endif %} <h5 class="card-title"> {% render_model Composition "title" %}</h5> {% render_placeholder Composition.credit language 'en' %} {% placeholder Composition.image language 'en' %} <p></p> {% endfor %} {% else %} <p>There are no Compositions in the database.</p> {% endif %} -
django model formset factory how to write {{ form.field }}
So for forms, if you have quantity = IntegerField() in forms.py, then in the html file you can write {{ form.quantity }} to get the input for the quantity. How can do you the samething for modelformset_factory? I've created a formset to ask the user for the item name and quantity. The item name is given by the loop. I need to move the modelformset factory inside the loop for each iteration, but I don't know how #views.py form_extras = Items.objects.filter(show=True).count() formset = modelformset_factory(Cart, form=CustomerOrderForm,extra=form_extras) form = formset(queryset=Items.objects.none()) if request.method == 'POST': form = formset(request.POST) #work on this if form.is_valid(): print("is valid") form = formset(request.POST) instances = form.save(commit=False) for instance in instances: #item previously in cart if (Cart.objects.filter(username=request.user, item_name=form.cleaned_data.get('item_name')).exists()): cart_instance = Cart.objects.get(username=request.user, item_name=form.cleaned_data.get('item_name')) cart_instance.quantity = cart_instance.quantity + form.cleaned_data.get('quantity') cart_instance.save() else: #item never in cart, create new instance item_instance = Items.objects.get(item_name=form.cleaned_data.get('item_name')) Cart.objects.create(username=request.user, item_name=form.cleaned_data.get('item_name'), weight=item_instance.weight, quantity=form.cleaned_data.get('quantity'), description=item_instance.description, image=item_instance.image, price=item_instance.price, storage_type=item_instance.storage_type, item_category=item_instance.item_category, limit=item_instance.limit,) timestamp = datetime.date.today() messages.success(request,"Sucessfully added your items to your cart! " + str(timestamp)) return redirect('/') else: print("form not valid for cart") form = formset() Home.html: #home.html <form method="POST"> {% csrf_token %} {{ form.management_form }} {{form.as_p}} <div class="row"> {% for item in produce %} <div class="card" style="width: 18rem;"> <img src="/media/{{ item.image … -
Can we use django builtin function of password reset for all users?(not for admin)
I am new to Django and I have started developing a website, where I provide the functionality of user login, logout and password reset. But I am not able to use Django default password reset as I am only getting email verification link to the superuser only. I need the password resetting for all users rather than superuser. Kindly help me .. -
How to break if statement's condition in jinja
I am trying to divide media files based on their file type. I have one big if statement's condition do this task. But when I am trying to break if statement's condition into multiple lines like below it causing an error. My Code: <div> {% for post in posts %} <h3>{{ post.title }}</h3> {% if ( (".jpg" in post.media_file.url) or (".png" in post.media_file.url) ) %} <img width="500" height="400" src={{ post.media_file.url }}></img> {% else %} <video width="500" height="400" controls controlsList="nodownload" src={{ post.media_file.url }}> </video> {% endif %} {% endfor %} </div> Error: Django Version: 3.0.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 16: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? It is working fine if I convert if statement condition like below, {% if ".jpg" in post.media_file.url or ".png" in post.media_file.url %} So, is there any way or how to break if condition properly in jinja2? -
How to programatically create a database view in Django?
I have following query that I ran to create a database view inside my SQLite database: CREATE VIEW customerview AS SELECT a.id , name , email , vat , street , number , postal , city , country , geo_lat , geo_lon , customer_id , is_primary FROM customerbin_address a , customerbin_customer b WHERE b.id = a.customer_id AND a.is_primary = 1 In models.py I added the model: class Customerview(models.Model): name = models.CharField(max_length=100, db_column='name') email = models.EmailField(unique=True, db_column='email') vat = VATNumberField(countries=['NL', 'BE', 'FR', 'DE', 'UK'], blank=True, null=True, db_column='vat') street = models.CharField(max_length=100, db_column='street') number = models.IntegerField(null=True, db_column='number') postal = models.IntegerField(null=True, db_column='postal') city = models.CharField(max_length=100, db_column='city') country = CountryField(db_column='country') is_primary = models.BooleanField(null=False, db_column='is_primary') geo_lat = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lat') geo_lon = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lon') class Meta: managed = False db_table = 'customerview' and in admin.py I altered the list: @admin.register(models.Customerview) class CustomerviewAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon') readonly_fields = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon',) How do I programatically add the database view with the query above in my application?