Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with a list of primary key in detail view
In my program, the index page shows a list of products in a table with a checkbox in each rows, and a dropdown list of the price level (for example: Retail, Distributor) When the user selects the price level and multiple products by checking the checkboxes, they click process and the program with run a query based on the selected items and selected price levels So, it has 2 views: index view which lists everything and detail view which just lists whatever selected. The index view is the view that has the POST button and is where I capture the selected price level and selected items. These parameters will be passed over the detail view using the return redirect. The problem I have is the URLConfig url.py In the detail views, there are 2 parameters passing in: the selected price level and selected items. With the selected price level, I have no issue capturing it as it's a single value: either Retail or Distributor. The selected items is the problem: I don't know how to pass an array of selected items in the URL Config. The path should be like this /detail/Retail/{product A, product B, product C} Here is what … -
What type of instance can django.conf.urls.url() be counted as?
While reading the official Django documentation, specifically the chapter 'URL dispatcher' about how Django processes requests, I stumbled upon something which made me uncertain. The docs stated that the variable 'urlpatterns' is a list containing django.conf.urls.url() instances. This made me wonder, is django.conf.urls.url(), or url() as commonly written within the framework, a function or a class? I have understood that everything in Python can be considered a class, however is it syntactically speaking a function or a class? My first instinct was to research the django.conf.urls.url(), url(), within the Django documentation, but I was unable to find much to read. This same question has now become relevant for me regarding other functions/classes that Django provides. How can you be sure whether or not foo() is a function or a class? From my understanding, these are definitely functions, but I am having a hard time expressing why. Thank you in advance. -
Wagtail moving sqlite to postgres database
The issue I have an empty (migrated) postgres database to which I want to move the data from my sqlite database. What I've tried I export with ./manage.py dumpdata --exclude auth.permission --exclude contenttypes and consequtively load the data into the postgres db with ./manage.py loaddata. The problem here is that wagtail requires the contenttypes and I get a runtime error FooPage matching query does not exist. at /wagtail/wagtailcore/models.py:639 return content_type.get_object_for_this_type(id=self.id) Don't exclude contenttypes with dumpdata. Now the loaddata command fails with an IntegrityError: Key ... already exists. I have tried to remove all ContentType model objects before loading in the data so that it doesn't whine about duplicate keys. While that works when using the sqlite db, it fails on the postgres db with an IntegrityError Key (id)=(1) is still referenced from table "wagtailcore_page". Used versions django 1.11.9 wagtail 1.12.3 python 3.5 Related Problems with contenttypes when loading a fixture in Django -
No Module Name django right after installing
I'm trying to install django in a virtual environment on my Windows machine (I have python 3.6.4). I create the virtual environment and install django and get the success message. But when I try to see my django installation, I get the error below: I'm seeing several similar questions on Stackoverflow like this or this but they are either on a different OS or have used a different means of installation and I've tried some of the suggestions with no luck. Does anyone know what is causing this and how to resolve? -
how to make custom view in django template
I have to display currency values in a table and have problems seting it up. The currency values are stored against CHF (swissfrancs) in the db as exchange_rate_to_chf. This is my models.py: from django.db import models from decimal import Decimal import datetime class ExchangeRate_name(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class ExchangeRate_date(models.Model): date = models.DateField('%Y-%m-%d', unique_for_date=True) def __str__(self): return str(self.date) class ExchangeRate(models.Model): name = models.ForeignKey(ExchangeRate_name) date = models.ForeignKey(ExchangeRate_date) exchange_rate_to_chf = models.DecimalField(max_digits=12, decimal_places=5) def __str__(self): return str(self.name) I whant to get a template that shows currency ExchangeRates in a Table as one line per date. some like this: DATE | USD | EUR | JPY | GBP ------------------------------------------ 2018-01-01 | 0.9 | 1.15 | 115.2 | 0.7 2018-01-02 | 0.9 | 1.14 | 115.3 | 0.76 I easealy made a list out of the model with view.py currency_list = ExchangeRate.objects.all() return render(request, 'currencies/index.html', {'currency_list': currency_list} And a template index.html <!DOCTYPE html> <head> </head> <body> <div> <h1>Currencies in CHF</h1> <ul> {% for currency in currency_list %} <li> {{ currency.date.date }} : {{ currency.name.name }} : {{ currency.exchange_rate_to_chf }} </li> {% endfor %} </ul> </div> </body> </html> But im realy strugling to make a customized view because the date key is … -
Django-bleach import and deploy to heroku error
I am using Django 1.11. I'm using in my Django application the django-bleach that was installed with: pip install django-bleach So, when I would use it, I've gotten an import error that I fixed, the error occurs in Django version 1.6 or 1.8+, I guess. You can see here what I did. It worked and I continue the development. The problem is: now I am trying to deploy my application in Heroku, but the same error occurs and the import has to be fixed. So, I think that my repository should have the requirements.txt with the correct version of django-bleach (the one that have my commit), this way it would works properly, right? So, I forked the repository, commited the modification and created a requirements.txt with this text: -e git+https://breno_asrm@bitbucket.org/breno_asrm/django-bleach.git#egg=django-bleach Then I created a new virtual env and installed with pip install -r requirements.txt I thought it would install the same thing as before, just adding my modification, but it was not what happened. For instance, now my lib directory (env/lib/python3.5/site-packages/ ) doesn't have django_bleach folder. So, how could I fix it in a way that I don't have to modify the heroku virtualenv that is created automatically (if it's … -
Django Rest_Framework tutorial gives unexpected error
I have tried over and over again, but it still gives the same thing. Couldn't find out the cause -
Django form with different models
I have a question, how to make a form in Django using 3 different models. This is my models: class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=50) city = models.CharField(max_length=50) class Team(models.Model): team_name = models.CharField(max_length=250) city = models.CharField(max_length=50) class GameCategories(models.Model): CATEGORIES = ( ('Senior', 'Senior'), ('Middle', 'Middle'), ('Junior', 'Junior'), ) category = models.CharField(max_length=16, choices=CATEGORIES) I want to create a form using <select><option></option></select> with above models that would look like this: <select class="form-control"> <option value=""></option> <option value="user.id">user.first_name + user.last_name</option> <option value="user.id">user.first_name + user.last_name</option> <option value="user.id">user.first_name + user.last_name</option> </select> <select class="form-control"> <option value=""></option> <option value="gamecat.id">gamecat.category</option> <option value="gamecat.id">gamecat.category</option> <option value="gamecat.id">gamecat.category</option> </select> <select class="form-control"> <option value=""></option> <option value="team.id">team.team_name</option> <option value="team.id">team.team_name</option> <option value="team.id">team.team_name</option> </select> and after filling form when user click submit button I want to send to another view all values (user id, game category id, team id). Actually I don't have idea how to do this. I guess that I should create a ModelForm. Could you please help me? -
django 2.0 using MySQL database
I was curious about using MySQL instead of SQLite for my Django project. Firstly, I would like to ask: where can I find an explicite guide of how to install MySQL with Django on Windows and if I use MySQL, will I type the exact type of code I would usually type in SQLite ? For example: class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() When you type this in Django, it gets converted to: CREATE TABLE "books_publisher" ( "id" serial NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL ); So the same will be when using MySQL ? -
Django forms - set specific data to the form object before modelForm saving
I have two ModelForm objects in the same view - Person and Adress. After user has bounded , I'm saving Person object. After saving, I want to use that saved object to set the ForeignKey of AdressForm, validate that form, and save. How can I set this? I mean field in ModelForm()? I've searched everywhere, and ewerywhere is said I have to save(commit=False), but I can't save unvalidated form! When I valid(), there is blank ForeignKey field! Here's my code: (I try to avoid create method, rather save) views.py class KontrahentCreate(LoginRequiredMixin, generic.View): template = 'escrm/kontrahent_form.html' context = dict() message = "Utworzono pomyślnie nowego kontrahenta" def get(self, request): self.context['form_kontrahent'] = KontrahentForm(initial={'czy_aktywny': True}) self.context['form_kontrahent'].fields['czy_aktywny'].widget = HiddenInput() self.context['form_adres'] = AdresKontrahentForm(initial={'czy_domyslny': True}) self.context['form_adres'].fields['czy_domyslny'].widget = HiddenInput() self.context['title'] = 'Dodaj nowego kontrahenta' return render(request, self.template, self.context) def post(self, request): kontrahent_form = KontrahentForm(request.POST) adres_form = AdresKontrahentForm(request.POST) if kontrahent_form.is_valid(): kontrahent = kontrahent_form.save() else: self.context['form_kontrahent'] = kontrahent_form return render(request, self.template, self.context) adres_form['kontrahent'].data = kontrahent.pk #AttributeError can't set attribute if adres_form.is_valid(): adres_form.save() else: self.context['form_adres'] = adres_form return render(request, self.template, self.context) messages.success(self.request, self.message) return HttpResponseRedirect(reverse_lazy('escrm:kontarhent-detail', kwargs={'pk': kontrahent.pk})) forms.py class KontrahentForm(ModelForm): class Meta(ModelForm): model = Kontrahent fields = '__all__' class AdresKontrahentForm(ModelForm): class Meta(ModelForm): model = AdresKontrahent fields = '__all__' widgets = { … -
Django: How to submit a form to either create new object or get an existing one?
Using django1.11.4. I am trying to make a page for adding an item to the database, however, to do this, I need to create/get several different objects, (product, manufacturer, supplier), whose forms make up part of the whole form for adding an item. In most case, there will be existing product, manufacturer and suppliers. So I want to retrieve the existing object and use that as the foreign key to relevant form. e.g. manufacturer is a foreign key of product. However, for all forms when I try submitting details for the existing object. e.g supplier. The is_valid fails. The error is: <ul class="errorlist"><li>supplier_name<ul class="errorlist"><li>Supplier with this Supplier name already exists.</li></ul></li></ul> Is there a way of submitting a form with 'existing data' so that I can get to pass on as a foreign key. Thank you for your time. class SupplierTestCase(FormTestCase, BasicTests): @classmethod def setUpTestData(cls): super(SupplierTestCase, cls).setUpTestData() cls.form = SupplierForm def setUp(self): super(SupplierTestCase, self).setUp() self.data = {'supplier_name_text': self.supplier_name} self.blank_data = { 'supplier_name_text': ['This field is required.'] } def test_valid_data(self): form = self.form(self.data) self.assertTrue(form.is_valid()) commit = form.save() self.assertEqual(commit.supplier_name_text, self.supplier_name) def test_get_data(self): form = self.form(self.data) self.assertTrue(form.is_valid()) if form.is_valid(): commit = form.save() self.assertEqual(commit.supplier_name_text, self.supplier_name) form = self.form(self.data) #The problem is below vvvv self.assertTrue(form.is_valid()) if … -
Paypal integration error
I am using django rest framework to integrate paypal. But I am always getting "Return to merchant error". Please help me in solving this issue. Following is the screenshot of the error. Now I am Indian buyer and I want to accept international payment in USD. I have used django-paypal with following codes. def paypal_process(request): try: host = request.get_host() paypal_dict = { 'business': PAYPAL_RECEIVER_EMAIL , 'amount': '1', 'item_name': 'Item_Name_xyz', 'invoice': 'Test Payment Invoice', 'currency_code': 'USD', 'notify_url': 'http://localhost:8000/api/payment/payment_notify/', 'return_url': 'http://localhost:8000/api/payment/payment_done/', 'cancel_return': 'http://localhost:8000/api/payment/payment_canceled/', } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'paypal_process.html', {'form': form }) except Exception as e: return JsonResponse("Exception " + str(e), status = status.HTTP_406_NOT_ACCEPTABLE, safe=False) In settings.py I have following settings PAYPAL_RECEIVER_EMAIL = 'xyz@abc.com' PAYPAL_TEST = False The code works fine when PAYPAL_TEST = True. But it gives the above error when in production. -
Django, django-autocomplete-light does not work
I am trying django-autocomplete-light to make work on ZipCode model in admin, which should display list of boroughs it's related. Here are the models.py: class ZipCode(models.Model): code = models.CharField(max_length=24) borough = models.ForeignKey('Borough', on_delete=models.CASCADE) def __str__(self): return self.code class Borough(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name Creating a form from model ZipCode in forms.py: from dal import autocomplete from django import forms from .models import ZipCode class ZipForm(forms.ModelForm): class Meta: model = ZipCode fields = '__all__' widgets = { 'borough': autocomplete.ModelSelect2(url='borough_select') } In views.py query boroughs: from .models import Borough from dal import autocomplete class BoroughAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Borough.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs Registering in urls.py: from django.conf.urls import url from .views import BoroughAutocomplete urlpatterns = [ url( 'autocomplete/$', BoroughAutocomplete.as_view(), name='borough_select', ), ] and in admin.py: from .models import ZipCode from .forms import ZipForm class ZipAdmin(admin.ModelAdmin): form = ZipForm admin.site.register(ZipCode, ZipAdmin) The result is: I can query boroughs like http://localhost:8000/autocomplete/?q=Manhattan But in admin there are no choices to select (Boroughs already exist in db) Please, help to find out where the problem occurs -
django rest framework documentation
pls I need a link to django rest framework docs. the official site http://www.django-rest-framework.org is not going through. -
Django extended template is not loading base JS at time
I've in Django 1.11 a base.html which contains all the scripts references. Then, I've another page.html that extendes base.html with {% extends base.html %} and {% block content %} / {% endblock content %} tags. Well. In base.html I've a reference to Chartjs.js plugin. In page.html, if I try to call to Chart() function or just $ jquery, I get "function is not defined". If I open console debugger and try to call $ or just Chart(), it works. So I think that there's a problem with loading time. The page.html is rendered before the js are downloaded or requested! How can I solve it? I've done it before, I don't know what could be the problem. Thanks! -
How does the Django app registry work? [on hold]
I am working on my first larger Python project and I would like to store some instances globally. The problem is Python's import system, which is different to some languages I am used to work with (for example a static variable in Java only exists once during runtime). I found out that Django's app registry somehow always manages to give me the same instance of my AppConfig, even when importing it from different locations. This looks a bit strange to me, because it creates an empty registry in the end of the "registry.py": apps = Apps(installed_apps=None) So I couldn't find the answer in the code and the Debugger also isn't useful because it causes internal errors in Django. Could someone please explain how Django manages this? -
ImportError: No module named 'testApp123' django
I am trying a sample django app. I added some changes in view.py and am trying to run migrate but it is giving following error - athakur@athakur-Inspiron-7560:~/Documents/per_code/djangodemo$ python3 manage.py check Traceback (most recent call last): File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/config.py", line 143, in create app_module = import_module(app_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'testApp123' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/athakur/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/athakur/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/athakur/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/config.py", line 147, in create app_name, mod_path, cls_name, django.core.exceptions.ImproperlyConfigured: Cannot import 'testApp123'. Check that 'djangodemo.apps.testapp.apps.TestAppConfig.name' is correct. package is correct since if I change name in TestAppConfig class to testApp it says ImportError: No module named 'testApp'. Also following works - athakur@athakur-Inspiron-7560:~/Documents/per_code/djangodemo$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from djangodemo.apps.testapp.apps import … -
Get select="multiple" behaviour with groups of radio buttons in POST request
When we have some code like this in HTML: <form action="" method="post"> <select name="answers" multiple="multiple"> <option value="1" >Question 1, Answer 1</option> <option value="2">Question 1, Answer 2</option> <option value="3">Question 1, Answer 3</option> <option value="4">Question 2, Answer 1</option> <option value="5">Question 2, Answer 2</option> </select> <input type="submit"> </form> I can select one item manually from the question 1 group, and one item from the question 2 group. When this is sent in a POST request, I get a POST array containing answers = [1, 3] or similar. I want to get the same behavior from groups of radio buttons, as this is a problem better suited to radio buttons. For example, if I do the following: <form action="" method="post"> <fieldset> <legend>Question 1</legend> <input name="answers" id="id_1" value="1" type="radio"> <label for="id_1">Answer 1</label> <br> <input name="answers" id="id_2" value="2" type="radio"> <label for="id_2">Answer 2</label> <br> <input name="answers" id="id_3" value="3" type="radio"> <label for="id_3">Answer 3</label> <br> </fieldset> <fieldset> <legend>Question 2</legend> <input name="answers" id="id_4" value="4" type="radio"> <label for="id_4">Answer 1</label> <br> <input name="answers" id="id_5" value="5" type="radio"> <label for="id_5">Answer 2</label> <br> </fieldset> </form> It doesn't actually let the user select more than one radio button at once. On the other hand, if I name the radio buttons answers[0] and answers[1], in POST, it … -
ImproperlyConfigured at /app/category/Python/
I wanna make a page which shows POST's models' contents is shown each category.For example, when I put Python link in <a href="{% url 'category' category.name %}"> in detail.html,only POST's models' contents with Python's category is shown in category.html.When I put Python link in category.html,I got an error,ImproperlyConfigured at /app/category/Python/ CategoryView is missing a QuerySet. Define CategoryView.model, CategoryView.queryset, or override CategoryView.get_queryset(). I wrote codes in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] category_content = Category.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,'category_content':category_content,"page":page}) class CategoryView(BaseListView): template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(category=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['category'] = self.category return context in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('category/<str:category>/',views.CategoryView.as_view(), name='category'), ] in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class POST(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title in top.html <div class="list-group"> <a href="#"> Category </a> <div> {% for category in category_content %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in category.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Category</title> </head> <body> <div> {% for … -
Django 1.11.6 AttributeError: 'DealerForm' object has no attribute 'forms'
I want my form, DealerForm, to save its contents to the database. However, the following comes up: Internal Server Error: /finance/14/record_input/ Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\NEA Computer Science\mysite\finance\views.py", line 46, in record_input if form.is_valid(): # check whether it's valid File "C:\Python34\lib\site-packages\django\forms\forms.py", line 183, in is_valid return self.is_bound and not self.errors File "C:\Python34\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Python34\lib\site-packages\django\forms\forms.py", line 385, in full_clean self._clean_form() File "C:\Python34\lib\site-packages\django\forms\forms.py", line 412, in _clean_form cleaned_data = self.clean() File "F:\NEA Computer Science\mysite\finance\forms.py", line 16, in clean for form in self.forms: AttributeError: 'DealerForm' object has no attribute 'forms' [07/Jan/2018 14:56:09] "POST /finance/14/record_input/ HTTP/1.1" 500 87806 What does this mean, and how can I solve it? views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Customer, Dealer from .forms import DealerForm from django.db.models import Q, F from datetime import timedelta from django.utils import timezone # Lists all dealers and links them to their welcome page def index(request): dealer_list = Dealer.objects.order_by('name') html = "<ol>" for dealer in dealer_list: html = html + … -
Mocking an HTTP request and forms.Form
So this is a part of the code I'm supposed to make test for: if APPLY_ACTION in request.POST: form = form_type(request.POST) if form.is_valid(): cleaned_data = {} for key, value in form.cleaned_data.iteritems(): if value is None or value == '': continue cleaned_data[key] = value Where form_type inherit from forms.Form and request is an http request. Now, I'm not sure exactly how to mock these two. Is it possible to give a specific line a return value? like for "form_type(request.POST)" return a specified dictionary? -
save() prohibited to prevent data loss due to unsaved related object: How to save related models together?
I have a form and a formset. Formset contains a column foreign key to form. However my forms are not saving and save() prohibited to prevent data loss due to unsaved related object error is being thrown. How could I save both these data together? here's my view: def purchaseOrderView(request): if request.method == 'POST': formset = POFormSet(request.POST) form = POHeaderForm(request.POST) print("POSTED") if form.is_valid() and formset.is_valid(): form.save() formset.save() messages.success(request,"VALID SUBMISSION") return render(request,'purchase_order.html',{'formset':formset, 'form':form}) else: return render(request, 'purchase_order.html', {'formset': formset, 'form': form}) else: formset = POFormSet() form = POHeaderForm() return render(request,'purchase_order.html',{'formset':formset, 'form':form}) here's my model structure: class POHeaderModel(models.Model): date = models.DateTimeField(blank=False, default=timezone.now) reference = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) supplier = models.ForeignKey(SuppliersModel, on_delete=models.PROTECT) note = models.CharField(validators=[alphanumeric], max_length=300, blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(0)]) class POBodyModel(models.Model): PO = models.ForeignKey(POHeaderModel, on_delete=models.PROTECT) item_number = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) description = models.CharField(validators=[alphanumeric], max_length=100, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) rate = models.DecimalField(decimal_places=2, max_digits=10) discount = models.DecimalField(decimal_places=2, max_digits=10,blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, blank=False) There are a lot of examples out there in various blogs and in here in questions using with transaction.atomic():. But none works or may be doesn't suit my scenario. Any advise? -
Get The Data based on start date and date date
Guys I have two tables one is of order table which has Tickets table which has time field for ticket_date. Other Table is of Customer table which also has foreign key relationship with assignee (Manager)table like each customer has start date and end date for assignee to manager If I want to get Data using ORM in Django like How many ticket closed buy assignee(Manager) I just wanted to pick Start date end date of reporting date over the given date range Customer reporting from 1 to 10th of month with manganer M1 in this span he placed 2 order and after 10th of the month reporting manger changes to M2 and placed order 4 So how I can make sure it’s not counted for whole date range -
in Django Admin - save() prohibited to prevent data loss due to unsaved related object
I have 2 models, Company and CompanyLogo: class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to=file_upload_to) Instead of using an inlineformset I modified the form(used in Admin and outside DjangoAdmin) class CompanyModelForm(forms.ModelForm): logo = forms.ImageField(widget=CompanyLogoWidget, required=False) class Meta: model = Company def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check if is update/edit if self.instance.pk: logo = CompanyLogo.objects.get(company=self.instance) self.fields['logo'].widget = CompanyLogoWidget(logo=logo) def save(self, commit=True): company = super().save(commit=commit) CompanyLogo.objects.update_or_create(company=company, defaults={"logo": self.cleaned_data['logo']}) return company The error appears only in Django Admin, not outside Django Admin form. I checked the questions on the forum related to mine, but in none of them the error was in Admin, and I save the Company model first calling: super().save(commit=commit) -
Django nested queries
In Django I'm trying to achieve a nested SQL structure like this without using raw queries: SELECT id, session_hash, user_id, price_type_id, room_category_id, check_in_date, price, captured_date FROM (SELECT p.*, Row_number() OVER (partition BY check_in_date, price_type_id, room_category_id ORDER BY captured_date DESC) AS rn FROM dashboard_prices p WHERE room_category_id = 1 AND price_type_id = 1 AND check_in_date >= '2018-01-01 00:00:00' AND check_in_date <= '2018-01-02 00:00:00') p WHERE rn = 1 I couldn't figure out how to achieve that by using "normal" query expressions in Django. Model: class Prices(models.Model): session_hash = models.CharField(max_length=32, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False) price_type = models.ForeignKey(PriceTypes, on_delete=models.CASCADE, blank=False, null=False) room_category = models.ForeignKey(RoomCategories, on_delete=models.CASCADE, blank=False, null=False) check_in_date = models.DateTimeField(blank=False, null=False, db_index=True) price = models.IntegerField(blank=False, null=False) captured_date = models.DateTimeField(default=timezone.now, blank=True) row_number = 'row_number() OVER (PARTITION BY check_in_date, price_type_id, room_category_id ' \ 'ORDER BY captured_date DESC)' I achieved already to get the inner query running by: price = Prices.objects.annotate(rn=RawSQL(Prices.row_number[])) .filter(room_category_id=req['room_category_id'], price_type_id=req['price_type_id'], check_in_date__gte=check_in_date, check_in_date__lte=check_out_date) But filtering after this brings only errors: django.db.utils.DatabaseError: Window function is allowed only in SELECT list and ORDER BY clause when adding: .filter(rn=1) Is there a possibility to achieve that? Thanks!