Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Appear data in URL form bu using Django
I want to create a record and want to appear data in the form fields. How can I do that ? Do I need to write javascript for it. If you help me, really apprepriate it. Thanks for now. Here is models.py; class hesaplarim(models.Model): hesap_id = models.AutoField(primary_key=True) tc_no = models.IntegerField(unique=True) name = models.CharField(max_length=55) surname = models.CharField(max_length=55) phone_number = models.IntegerField() gender = models.CharField(max_length=5) Here is views.py; def home(request): form = HesapForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: form = HesapForm() return render(request, 'home.html', {'form': form}) Here is forms.py; class HesapForm(forms.ModelForm): ERKEK = 'ERKEK' KADIN = 'KADIN' gender_choices = ( (ERKEK, 'ERKEK'), (KADIN, 'KADIN') ) tc_no = forms.IntegerField(widget=forms.NumberInput) name = forms.CharField(widget=forms.TextInput) surname = forms.CharField(widget=forms.TextInput) phone_number = forms.IntegerField(widget=forms.NumberInput) gender = forms.ChoiceField(choices=gender_choices) class Meta: model = hesaplarim fields = ('tc_no', 'name', 'surname', 'phone_number', 'gender') Here is html file; <form method="post" class="form-horizontal" novalidate> {% csrf_token %} <div class="form-group"> <label for="id_tc_no">TC No:</label> {{ form.tc_no }} </div> <div class="form-group"> <label for="id_name">Ad:</label> {{ form.name }} </div> <div class="form-group"> <label for="id_surname">Soyad:</label> {{ form.surname }} </div> <div class="form-group"> <label for="id_phone">Cep Telefonu:</label> {{ form.phone_number }} </div> <div class="form-group"> <label for="id_gender">Cinsiyet:</label> {{ form.gender }} </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Kaydet"> </div> </form> -
Python convert python-amazon-simple-product-api results to json using Django
I am writing an API in Python Django and rest framework. I am using a python packaged called python-amazon-simple-product-api to access amazon advertising API. I am trying to feed the results into the rest framework and return the results as JSON Here is my code so far. class AmazonProductsViewSet(viewsets.ViewSet): def list(self, request, format=None): products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations") products = list(products) With this code I get the following error; TypeError: Object of type 'AmazonProduct' is not JSON serializable So I am trying to find a way of making the AmazonProduct object serializable or a better solution. -
Sending Ajax request but not able to receive at the receiver's end
I am using XMLHTTPRequest object to send some data from one of the templates in Django to another function in view.py This is a part of my template: function fun_submit() { var var_theme = document.getElementById("theme").value; var var_author = document.getElementById("author").value; var var_entry = document.getElementById("entry").value; var xmlhttp = new XMLHttpRequest(); xmlhttp.open('GET',"http://127.0.0.1:8000/first_page/something/",true); var data_upload = var_theme; xmlhttp.send('w='+encodeURI(var_theme)); window.location.href = 'http://127.0.0.1:8000/first_page/something/'; xmlhttp.close(); } and my view function is: def something(request): py_data = request.GET.get('w') return HttpResponse(py_data) when I return py_data, the page says None. I suspect the data is not getting transmitted. Any help or suggestion is really welcome. Thanks. -
Django rest framework bind decimal values from Brazilian currency format
I have to serialize data for a django rest framework application, some of values will be on Brazilian currency format like 1.234,45. How can I bind those number to work with django rest serializer and django models My model: class Produto(models.Model): prod_codigo = models.AutoField(db_column='prod_codigo', primary_key=True) prod_alias = models.CharField(db_column='prod_alias', max_length=50, null=False) prod_descricao = models.CharField(db_column='prod_descricao', max_length=255, null=False) prod_valor_venda = models.DecimalField(db_column='prod_valor_venda', max_digits=13, decimal_places=2) prod_valor_compra = models.DecimalField(db_column='prod_valor_compra', max_digits=13, decimal_places=2) prod_peso_b = models.DecimalField(db_column='prod_peso_b', max_digits=13, decimal_places=2) prod_peso_l = models.DecimalField(db_column='prod_peso_l', max_digits=13, decimal_places=2) My serializer: class ProdutoSerializer(serializers.Serializer): prod_codigo = serializers.IntegerField(read_only=True) prod_alias = serializers.CharField(required=False, allow_blank=True) prod_descricao = serializers.CharField(required=True, allow_blank=True) prod_valor_venda = serializers.DecimalField(max_digits=13, decimal_places=2) prod_valor_compra = serializers.DecimalField(max_digits=13, decimal_places=2) prod_peso_b = serializers.DecimalField(max_digits=13, decimal_places=2) prod_peso_l = serializers.DecimalField(max_digits=13, decimal_places=2) class Meta: model = Produto def create(self, validated_data): return Produto.objects.create(**validated_data) def update(self, instance, validated_data): instance.prod_codigo = validated_data.get('prod_codigo', instance.prod_codigo) instance.prod_alias = validated_data.get('prod_alias', instance.prod_alias) instance.prod_descricao = validated_data.get('prod_descricao', instance.prod_descricao) instance.prod_valor_venda = validated_data.get('prod_valor_venda', instance.prod_valor_venda) instance.prod_valor_compra = validated_data.get('prod_valor_compra', instance.prod_valor_compra) instance.prod_peso_b = validated_data.get('prod_peso_b', instance.prod_peso_b) instance.prod_peso_l = validated_data.get('prod_peso_l', instance.prod_peso_l) instance.prod_peso_q = validated_data.get('prod_peso_q', instance.prod_peso_q) instance.save() return instance -
How to correctly implement save() input data method from a contact form to Django SQLITe DB?
How to correctly implement save() to Django SQLITe DB method when taking data from a contact form input ? Last method tries to save input but it is not working. I have used codes from tutorial on Django contact form sending email. Need to add saving to database functionality. # view from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm from .models import SendEmail def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['bioinformatics_bel@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def success(request): return HttpResponse('All right! Thank you for your message.') def savedata(request): # want to save data input into the SQLIte database!! here is something wrong if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] message_object = SendEmail(from_email = from_email, subject = subject, message = message) message_object.save() return HttpResponseRedirect('success') #else: form = ContactForm() # unbound form return render(request, "email.html", {'form': form}) # template <h1>Submit identifier for the data processing</h1> <form method="post"> … -
How to insert a button in a dropdown selected option in Django?
I would like to insert a dropdown in Django that will return me to a page, and I am inserting a button that will lead to that page, but when I do this I return to the page I am currently in. index.html {% if lista_de_provas %} <form method='post' action=''> {% csrf_token %} <select class="form-control" name="prova_selecionada" id="prova_selecionada"> {% for prova in lista_de_provas %} <option id="{{prova.idProva}}" name="listaProvas" value='{{prova.idProva}}' desabled>{{prova.tipoProva}} {{prova.anoProva}}</option>Mdjss.199 {% endfor %} </select> <input id="selProva" type="button" value="Confirma" onclick = "location.href ='{{prova.idProva}}';" /> </form> {% endif %} views.py def index(request): lista_de_provas = Prova.objects.all() cprova = request.POST.get('idProva') if request.method == 'POST': sprova = Prova.objects.get(cprova = cprova) sprova.select() return redirect('polls/detalhes.html') else: form = ProvaForm() return render(request, 'polls/index.html',{'form':form,'lista_de_provas': lista_de_provas}) -
Django how to time user actions
I code something like www game and I have a problem. How can I time user actions? For example - User do action A. And he can't do this action again for one hour. After that he can again. -
django not able to load static file
I am trying to go though Django tutorial which explains about static files but when I am trying implement that I am getting following error: [08/Oct/2017 23:08:27] "GET / HTTP/1.1" 200 365 [08/Oct/2017 23:08:27] "GET /static/polls/sytle.css HTTP/1.1" 404 1658 My Django project structure: (removing irrelevant files and folders). rehman@linux-desktop ~/django_proj/my_site $ tree . ├── db.sqlite3 ├── manage.py ├── my_site │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── static │ │ └── polls │ │ ├── images │ │ │ └── background.jpg │ │ └── style.css │ ├── templates │ │ └── polls │ │ ├── details.html │ │ ├── index.html │ │ └── result.html │ ├── tests.py │ ├── urls.py │ └── views.py └── templates settigs.py (partial contents): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' url.py: urlpatterns = [ url(r'^', include('polls.urls')), url(r'^admin/', admin.site.urls), ] index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Polls</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static … -
How to setup Django silk profiler
I am completely new to Django and profiling. I have completed all the steps mentioned in the document for setting up the silk profiler. https://github.com/jazzband/silk I did not find any error when I ran the manage.py run server command But when I open the browser and call the necessary api, I don't find anything related to silk. I have no idea where to find the results. Any help is greatly appreciated -
Django form doesn't show up
I'm working on some project and ended up with some issues. So my form doesn't display itself at all in my template. But I've created another form before and it works as it should! So my code: models.py class Project(models.Model): class Meta: db_table = "project" COLORS = ( ('R', 'Red'), ('B', 'Blue'), ('G', 'Green'), ('Y', 'Yellow') ) project_title = models.CharField(max_length=200) project_color = models.CharField(max_length=1, choices=COLORS) def __str__(self): return self.project_title forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ['project_title', 'project_color'] views.py def addproject(request): if request.POST: form_p = ProjectForm(request.POST) if form_p.is_valid(): form_p.save(commit=False) return HttpResponseRedirect('/') else: form_p = ProjectForm() context = { 'projects': Project.objects.all(), "form": form_p, 'username': auth.get_user(request).username, } context.update(csrf(request)) return render(request, 'index.html', context) urls.py urlpatterns = [ url(r'^addproject/$', views.addproject, name='addproject'),] index.html <form action="/addproject/" method="post"> {% csrf_token %} {{ form_p.as_table }} <button type="submit" class="btn btn-primary">Add Project</button> </form> -
Passing a Primary Key to a form template
This is an update from this questions, which I will amend if I find a complete answer for this issue - How do I 'Autofill' a CreateView field I have a Artist model, and I'm now trying to add a comment feature to the DisplayView using an ArtistComment modal and a CreateView form on a modal div. I think I'm really close to getting this to work, but I'm having a little issue passing the primary key from my artistdetail.html page to my artistcomment_form.html template. Any help with this, or tips for documentation pages to read would be greatly appreciated. urls.py: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artist-(?P<pk>[0-9]+)/artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), views.py: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['message',] def get_success_url(self): return reverse('events:artistdetail', kwargs={'pk': self.object.artist_id}) def form_valid(self, form, *args, **kwargs): form.instance.author = self.request.user form.instance.artist = get_object_or_404(Artist, id=self.kwargs.get('pk')) return super(ArtistCommentCreate, self).form_valid(form) artistdetail.html: <p id="commentfooter"><a href="{% url 'events:artistcomment-add' artist.id %}">Add A New Comment</a></p> artistcomment_from.html: {% block body %} <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="{% url 'events:artistcomment-add' pk %}" method="post" enctype="multipart/form-data" onSubmit="CloseModal();"> {% csrf_token %} {% include "events/form-template.html" %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> As far as I can tell, where I've entered … -
Django on apache io error
My day-old django project is already running on Apache 2. This is the general structure: root/apps/django/django_projects/Project ├── autocache │ ├── cache.py │ └── cache.txt ├── conf ├── manage.py ├── Project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ └── ... ├── myapp │ ├── __init__.py │ ├── apps.py │ ├── views.py │ ├── urls.py │ └── ... When myapp is shown, I simply show the contents of cache.txt. This is what I have to do that: from django.shortcuts import render from django.http import HttpResponse from django.conf import settings import os def index(request): cache_path = os.path.join(settings.CACHE_DIR, 'cache.txt') with open(cache_path, 'r') as cache: return HttpResponse(cache.read()) return "Could not open file" The problem is that an exception is being thrown: Request Method: GET Request URL: http://myip/Project/subwayapp/ Django Version: 1.11.5 Exception Type: IOError Exception Value: [Errno 13] Permission denied: '/root/apps/django/django_projects/Project/autocache/cache.txt' Exception Location: /opt/bitnami/apps/django/django_projects/Project/myapp/views.py in index, line 8 Python Executable: /opt/bitnami/python/bin/python Python Version: 2.7.13 However, this is the output of ls -l for cache.txt: -rwxrwxr-- 1 root root 17 Oct 8 16:06 cache.txt As I understand it, this means that It is a file The owner can read, write, and execute it The group can read, write, and execute it … -
Django Rest Framework - Get details from another model with Reverse Lookup
I have 3 models book, language, book_language. when i try to get list of books i am unable to get associated languages with django_rest_framework models.py class Book(models.Model): title = models.CharField(max_length=200) year = models.IntegerField() class Language(models.Model): language_name = models.CharField(max_length=100) class Book_language(models.Model): book = models.ForeignKey(Book) language = models.ForeignKey(Language) serializers.py class BookLanguageSerializer(serializers.ModelSerializer): class Meta: model = Book_language fields = ('id', 'language',) class BookSerializer(serializers.ModelSerializer): languages = BookLanguageSerializer(source='language_set') class Meta: model = Book fields = ('id', 'title', 'languages') desired ouput: [{ id: 1, title: 'some book 1', languages: [ { id: 1, language: 'english' }, { id: 2, language: 'chinese' } ] }, { id: 2, title: 'some book 2', languages: [ { id: 1, language: 'english' }, { id: 2, language: 'chinese' } ] }] Instead of above output, i am only getting list of books without languages array like below. [{ id: 1, title: 'some book 1', }, { id: 2, title: 'some book 2', }] Also guide where can i find better examples, I tried to read the DRF doc but its not beginner friendly. -
Django: Query involving Foreign Key
I have models.py class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc=models.CharField(max_length=5,choices=LOCATION) manager_id=models.ForeignKey('self',null=True,blank=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P') ltype=models.CharField(max_length=2,choices=LEAVE_TYPE) class notify(models.Model): sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') date_time=models.DateTimeField(auto_now_add=True) viewed=models.CharField(max_length=2) I want the employee id of receiver_id as receiver_id is a foreign key... When I query notify.objects.filter(receiver_id__employee__emp_id=1) I am getting empty queryset but I want the tuples with emp_id=1. -
Pass request as a parameter to Model class
[1] I am trying to implement credentials authentication by storing it in the session request. Is there any way I can get it to my model Class? [2] I am also trying to get dropdown from Courses class but I am getting it as a box to enter text. What am I doing wrong? urls.py from django.conf.urls import url import views urlpatterns = [ url(r'^$', views.auth, name='Authenticate'), url(r'^courses', views.showCourseList.as_view(), name='GetCourses'), url(r'^assignments/', views.showAssignmentsList, name='GetAssignments'), ] models.py def getCourses(): http = credentials.authorize(httplib2.Http()) service = discovery.build('classroom', 'v1', http=http) results = service.courses().list().execute() return map(lambda x: (str(x['name']), str(x['name'])), results.get('courses', [])) class Courses(models.Model): List_Of_Courses = models.CharField(choices=getCourses(), max_length=10) views.py class showCourseList(CreateView): http_method_names = ['get', 'post', 'head', 'options', 'trace'] def get(self, request, *args, **kwargs): pass model = Courses fields = ['List_Of_Courses'] template_name = 'CourseList.html' CourseList.html <form action="/assignments/" method="get"> {{ form.as_p }} <input type="submit" value="Select Course" /> </form> -
How to set a variable (using set tag) in django template?
I want something like this inside django template. I want to use these variables in javascript file or another template file. {% set titles = { 'table': form._meta.model._meta.verbose_name_plural.title(), 'form': form._meta.model._meta.verbose_name.title() } %} {% set dtable = "dt_" + page %} How can I get set tag? Your answer would be helpful for me. -
adding to a query set from another queryset django
I have a query set that looks like this. <QuerySet [<Room: localhost>, <Room: chat>]> which is inside room <QuerySet [<RoomShare: Shared room u'208349023840928', for company 2>]> which is stored inside roomshare If I print the second query to get the name of the room i just use. for x in roomshare: print(x.room.room_name) which gives me `Room Fun` I would like to add this Room_Fun to the first query set. And it should look like this <QuerySet [<Room: localhost>, <Room: chat>, <Room: Room_Fun]> I tried different method's but couldn't achieve the result I want. Also the second query set can have more than 1 roomShare, so I might have to use a forloop to add multiple of times to the first query set. -
Django 1.11 PostgreSQL multiprocess fail to work
Here's a website I've beening working on. It scrapes data from certain urls. I use multiprocessing module to make it faster, but the data cannot be saved. I tried put this under the worker function, but it still can't work.connection.close() Seems like the database just gets stuck in: data = Data(url=url, title=tile) ps: I'm using PostgreSQL 10, and Django 1.11.5, Python 3.5. def getSoup(url): # get beautifulsoup object from the url def getData(soup, url): title = getTitle(soup) # read title from the soup data = Data(url=url, title=title) data.save() print(url, 'Data saved!') def task(url): # connection.close() # I tried put this here, but it's not working soup = getSoup(url) # try for the first time while soup == 1: try: soup = getSoup(url) # if it failed to get soup, it'll return 1 and try again except TimeoutError: pass getData(soup, url) def scrape(): pool = multiprocessing.Pool(processes=10) pool.map(task, get_urls()) # get_urls is a urls generator pool.close() scrape() -
Django: can database migrations be reverse engineered?
I've been trying to wrap my head around how to avoid creating a mess with Django migrations. I tried "don't delete migrations" and for the most part that worked, but when I wanted to delete an app off my codebase, I struggled and fell back into a mess. I was thinking, it would be far easier to untangle these issue if one could: 1- delete all current migrations 2- create a migration from an existing database schema (rather than from Django models) <- this is the missing step 3- run migrate --fake to synch DB with migrations 4- run makemigrations to add any non-applied changes to the migration chain (this time from Django models) 5- run migrate to synch the DB with the new changes The only step that I don't know how to do is step 2. Is this doable? I don't know of any built in module or tool that does this so I'm wondering why not. Some research showed python manage.py inspectDB gets me partially through step 2. -
Django model foreign key filter
The problem: I have two django models: class Driver(models.Model): event = models.ForeignKey('Event') last_event = ???? ... ... class Event(models.Model): date = models.IntegerField() Now i need only LAST event for each driver PREFETCHED and CACHED d = Driver.objects.prefetch_related('last_event???') How do i achieve it? Is there any way to limit relation as something like: last_event = models.ForeaignKey('Event', filter = ...??? ) -
Django use templatetag API Wrapper
I'm writing a custom API wrapper for automating stuff on multiple devices having a REST API. Authentication to these devices is via csrf token. I'm struggling making a connection via form input using the devices API as custom tag. In addition im not really sure if this is the right approach to start a project like this. app/views.py def index(request): context = {} template = loader.get_template('app/index.html') return HttpResponse(template.render(context, request)) def webbase_html(request): context = {} load_template = request.path.split('/')[-1] template = loader.get_template('app/' + load_template) return HttpResponse(template.render(context, request))` templatetags/device_handler.py from django import template register = template.Library() from app.templatetags.device_api import DeviceAPI from requests.exceptions import ConnectTimeout @register.simple_tag def login_device(host, username, password): dev = DeviceAPI() try: dev.login(host, username, password) hname = dev.get_host_name() return hname except ConnectTimeout as error: return error templatetags/device_api.py Looks like this: (Snippet) class DeviceAPI(object): def __init__(self): self._https = True self._version = "Version is set when logged" self._session = requests.session() # use single session self._session.verify = False def formatresponse(self, res): resp = json.loads(res.content.decode('utf-8') return resp def update_cookie(self): for cookie in self._session.cookies: if cookie.name == 'ccsrftoken': csrftoken = cookie.value[1:-1] # token stored as a list self._session.headers.update({'X-CSRFTOKEN': csrftoken}) def login(self, host, username, password): self.host = host if self._https is True: self.url_prefix = 'https://' + self.host else: … -
javascript: Uncaught SyntaxError: Invalid or unexpected token
I have a dictionary data I add a key and value like so: data['business-details'] = "{{ service.business_details }}"; this is from django and the content has a comma , which I believe is causing the code to crash. Getting this error on the console: Uncaught SyntaxError: Invalid or unexpected token which goes to this line data['business-details'] = "I can design both front and back (Django) end for a site, preferably interesting projects."; -
Read user uploaded csv file and store data in Django modele live on heroku
This is my firts question here. so I would like to thank you for your help. I have a Django School management app. and i would like the user to be able to read csv file and store in database with specific header. My code runs locally very well. but I recently push it on heroku so that I can test it. I may note that all static assets are stored on Amazon s3. and it works. but when I try to read a csv file, I get an Internal server error. here is my code to store Pupils. def convert_header(csvHeader): cols = [ x.replace(' ', '_').lower() for x in csvHeader ] return cols def import_data(request): if request.method == 'GET': return render(request, 'school/import.html') if request.method == 'POST' and request.FILES['myfile']: if request.POST.get("object") == '': message = 'You may chose an object' return render(request, 'school/import.html', {'message': message }) if request.POST.get("object") == 'Pupil': myfile = request.FILES['myfile'] fs = FileSystemStorage(location='eSchool/media/documents') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.path(filename) data = csv.reader(open(uploaded_file_url), delimiter=',') header = next(data) header_cols = convert_header(header) i = 0 k = 0 for row in data: pupil = Pupil() for k in range(len(header_cols)): row_item = row[k].split(',') for item in row_item: key = header_cols[k] … -
How to get information of foreign key when selected to another table when selected specific key
I have three tables, one is mandal, village and Property, in the property table i have linked mandal and village with foreign key, now when i select mandal, only that particular village results should have to shown in property form in django admin. I have also linked mandal with village. #models.py from django.db import models from django.utils import timezone class Mandal(models.Model): id = models.AutoField( primary_key=True, db_column="Mandal_id", verbose_name="Mandal Id", ) name = models.CharField( max_length=200, db_column="Mandal_Name", verbose_name="Mandal Name", null=False, blank=False, help_text="Enter Mandal names only", default=None, ) class Meta: db_table = "Mandal" verbose_name_plural = "Mandal" def __str__(self): return self.name class Village(models.Model): id = models.AutoField( primary_key=True, db_column="Village_id", verbose_name="Village Id", ) name = models.CharField( max_length=200, db_column="Village_Name", verbose_name="Village Name", null=False, blank=False, help_text="Enter village names only", default=None, ) mandal_id = models.ForeignKey( Mandal, db_column="Mandal_id", verbose_name="Mandal Name", ) class Meta: db_table = "Village" verbose_name_plural="Village" def __str__(self): return self.name class Properties(models.Model): id = models.BigAutoField( primary_key=True, db_column="Property_id", verbose_name="Property Id" ) created_on = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now(), ) area = models.BigIntegerField( default=0, db_column="Property_Area", verbose_name="Property Area", help_text="Please enter area in square feet", validators=[], ) mandal_location = models.ForeignKey( Mandal, db_column="Mandal_id", verbose_name="Mandal Name", default=None, ) village_location = models.ForeignKey( Village, db_column="Village_id", verbose_name="Village Name", default=None, ) description = models.TextField( default=None, db_column="Property_description", verbose_name="Property Description", ) features = models.CharField( … -
Django query api: complex subquery
I wasted lots of time trying to compose such query. Here my models: class User(Dealer): pass class Post(models.Model): text = models.CharField(max_length=500, default='') date = models.DateTimeField(default=timezone.now) interactions = models.ManyToManyField(User, through='UserPostInteraction', related_name='post_interaction') class UserPostInteraction(models.Model): post = models.ForeignKey(Post, related_name='pppost') user = models.ForeignKey(User, related_name='uuuuser') status = models.SmallIntegerField() DISCARD = -1 VIEWED = 0 LIKED = 1 DISLIKED = 2 And what i need: Subquery is: (UserPostInteractions where status = LIKED) - (UserPostInteractions where status = DISLIKED) of Post(OuterRef('pk')) Query is : Select all posts order by value of subquery. I'm stuck at error Subquery returned multiple rows Elp!!))