Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest token authentication
If I want to use both TokenAuthentication and SessionAuthentication, I get a CSRF error if it checks the session before the Token. Is this an indicator that something is wrong with my setup, or is this a shortcomming of DRF? -
can't download a text file from a folder in django
I am having a folder named text_file and I am having all the text files in that folder only. Here, is the directory of my folders and files: So, what I want to do is download hello.txt by clicking on a download button in home.html after searching on google what I got: link in home.html: <a href="/download/" download> download here </a> which redirects me to views.py where the download function I wrote was: from django.http import HttpResponse from wsgiref.util import FileWrapper import os def download(request): file_path = '/djangowebproject1/text_file/hello.txt' try: wrapper = FileWrapper(open(file_path, 'rb')) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response except Exception as e: return None So, what I exactly wants is to download file like what we do in html by just redirecting at the file location Like: /text_file/hello.txt When I try with the above approach it shows : The view app.views.download didn't return an HttpResponse object. It returned None instead.. Please help me. I am just begineer in the Django. Thanks in advance. -
getting sum in django
I am trying to get the sum of posts and likes. But getting some errors.I am not sure whether to use aggregate or annotate. def count_posts_of(user): return Post.objects.filter(author=user).count() def total_likes_received(user): return user.posts.aggregate(total_likes=Count('likes'))['total_likes'] or 0 def get_queryset(self): return (Post.objects.filter(published_date__lte=timezone.now()) .order_by('date') .annotate(author_total_likes = (Count('author__posts__likes'), Post.count_posts_of)) ) -
Sending email with attached .ods File
send_mail('Subject here', 'Here is the message.', 'selva@gmail.com', ['stab@gmail.com'], fail_silently=False) mail = send_mail('Subject here', 'Here is the message.', 'selvakumaremmy@gmail.com', ['vsolvstab@gmail.com'], fail_silently=False) mail.attach('AP_MODULE_bugs.ods','AP_MODULE_bugs.ods','application/vnd.oasis.opendocument.spreadsheet') mail.send() I'm using Django send_mail class for sending mail. Here I want to send mail with attachment, my attachment File (.ods) is in local storage. -
How to save post into Django (2.0) like I bookmarked it
How to save a post into Django (2.0) like I bookmarked that post for later usage. I need to implement it into one of my project. -
Django Crispy forms hide fields conditional on other field value
How can I hide/show a form field in Django crispy forms based on the value of another field in the form. E.g. Field A has a dropdown with choices '1' and '2' Field B is show when Field A = '1' Field C is shown when Field A = '2' All other fields are shown in regular ways I've tried multiple query/javascript solutions from the forums, but they don't seem to work on crispy forms. jQuery/Javascript method to show/hide multiple fields upon selection with common fields to multiple selections Show and hide dynamically fields in Django form Django crispy form - use Radio button to hide/show other fields Maybe I'm misunderstanding these solutions or they just won't work on Crispy forms. My code Models.py class TestCondition(models.Model): some_name = models.ForeignKey(key_name, on_delete=models.CASCADE) A_type_choices = ( ('1','1'), ('2','2'), ) Field_A = models.CharField(max_length=20,choices= A_type_choices,default='1') B_field_choices = ( ('abc','ABC'), ('cba','CBA'), ) Field_B = models.CharField(max_length=20,choices= B_field_choices,default='abc',blank=True,) Field_C = models.CharField(max_length=40, blank=True, default='') views.py class ViewUpdateTestCondition(LoginRequiredMixin,UpdateView): model = TestCondition template_name = 'update.html' form_class = TestConditionForm class TestConditionForm(ModelForm): class Meta: model = TestCondition fields = ('some_name','Field_A','Field_B','Field_C') def __init__(self, *args, **kwargs): super(ModelconfigForm, self).__init__(*args, **kwargs) self.helper = FormHelper(form=self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.form_method = 'post' # … -
Django: can't display formset and form proper
Good day, I need a little help with a code or advice. I'm making site for applications. And have two models: Applications and Guests and they have manytomany connection, because application can have 2 or more guests and 1 guest may be in many applications. For making applications i use formset_factory with delete option. The problem is - I can't find any good examples with code for manytomanyfield and formset and I can't bound them in template. I can't display the table at all. Here's the code. p.s. don't pay attention to cyrillic symbols p.p.s i'm only studying models class Guests(models.Model): unique_number_guest = models.IntegerField(unique=True, primary_key=True, verbose_name='№') organisation = models.CharField(max_length=100, verbose_name='Организация', null=True) full_name = models.CharField(max_length=100, verbose_name='ФИО') position = models.CharField(max_length=100, verbose_name='Должность', blank=True, null=True) chosen = models.BooleanField(default=False, verbose_name='Выбран') class Applications(models.Model): ntc_cabins = ( ('2-5', '2-5'), ('2-10', '2-10'), ('2-12', '2-12'), ) ntc_blocks = ( ('ЦОК', 'ЦОК'), ('БМЗ', 'БМЗ') ) unique_number_app = models.IntegerField(unique=False, null=True) visit_date = models.DateField(default=date.today()+timedelta(days=1), verbose_name='Дата:') visit_time = models.TimeField(default='12:00', verbose_name='Время:') cabin = models.CharField(max_length=5, verbose_name='Кабинет:', choices=ntc_cabins, default='2-12') block = models.CharField(max_length=10, verbose_name='Корпус:', choices=ntc_blocks, default='ЦОК') author = models.CharField(max_length=100, verbose_name='Автор:') guests = models.ManyToManyField(Guests) views def ApplicationFormation(request): form = ApplicationsForm(request.POST) form.guest_instanses = GuestsFormSet(request.POST) if request.method == "POST": if form.is_valid(): applications = Applications() applications.cabin = form.cleaned_data['cabin'] applications.save() for person … -
Login cannot be done in my app
Login cannot be done in my app.I wrote in views.py from django.shortcuts import render,redirect from django.urls import reverse from app.forms import RegisterForm,LoginForm from app.models import Data from app.forms import DataForm from django.db.models import Q def index(request): data = Data.objects.order_by('-created_at') form = RegisterForm() loginform = LoginForm() dataform = DataForm() return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user}) in index.html <section id="top"> {% if user and not user.is_anonymous %} <p>Hello</p> <h3>{{ user.username }}</h3> {% else %} <form action="{% url 'app:index' %}" method="POST"> {{ loginform.non_field_errors }} {% for field in loginform %} {{ field }} {{ field.errors }} {% endfor %} <button type="submit">LOGIN</button> {% csrf_token %} </form> {% endif %} </section> in forms.py from django import forms from django.contrib.auth.forms import ( AuthenticationForm ) class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label in child's app's urls.py from django.urls import include, path from . import views from django.contrib.auth.views import login app_name = 'app' urlpatterns = [ path('index', views.index,name='index'), ] in parent's app's urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('app/',include('app.urls') ), ] When I login from loginform,if statement of {% if user and not user.is_anonymous %} did not become true.But when I … -
How to use Django Signals?
I'm practicing Signals, I have two models models.py class National_ID_Card(models.Model): name = ************* ID = ************* address = ************* state = ************* nation = ********** def __str__(self): return self.name class Driving_Licence(models.Model): name = ************* ID = ************* vehicle_type = ********** callahan = *********** def __str__(self): return self.name forms.py class NationalIDForm(forms.ModelForm): class Meta: model = National_ID_Card fields = ('__all__') class DrivingLicenceForm(forms.ModelForm): class Meta: model = Driving_Licence fields = ('__all__') I want when i will be saving instance of National_ID_Card it would populate the name and ID field of Driving_Licence from also. I can do so with overriding method of save but how to do so in django signals? I tried many examples but cannt able to figure it out. -
'adduser' object has no attribute 'get' error while using templates with django?
I am trying to use HTML templates with django but getting errors, please look into to it and tell me whats wrong with the code This is my views file from django.http import HttpResponse from django.shortcuts import render from django.template import loader from . models import adduser def add(request): all_users = adduser.objects.all() template = loader.get_template('p1/adduser.html') context = { 'all_users':all_users, } return HttpResponse(template.render(context, request)) This is my models file from django.db import models class adduser(models.Model): name = models.CharField(max_length=255) designation = models.CharField(max_length=255) email = models.CharField(max_length=255) password = models.CharField(max_length=255) confirmpassword = models.CharField(max_length=255) ContactNumber = models.IntegerField() This is my adduser.html template <!DOCTYPE html> <html> <body> <h2>Add User</h2> <form action="{%url:'p1:adduser'%}" method="post"> Name:<br> <input type="text" name="Name"><br> Designation:<br> <input type="text" name="Designation"><br> Email:<br> <input type="Email" name="Email"><br> Password:<br> <input type="password" name="Password"><br> Confirm Password:<br> <input type="password" name="Confirm Password"><br> Contact Number:<br> <input type="number" name="Number" ><br> <input type="submit" value="Add"> <button type="cancel" onclick="window.location='http://google.com';return false;">Cancel</button> </form> </body> </html> -
How to insert data into row using specific id - Django
I want to update same row in SQlite in Django . I have two app in which first one creates login and registration and other app is used for gathering the information it is form . I have used common models.py . following is my code for first app (login and registration) : from django.shortcuts import render, redirect, HttpResponseRedirect from .models import Member from django.shortcuts import redirect # Create your views here. def index_web(request): if request.method == 'POST': member = Member(username=request.POST['username'], password=request.POST['password'], firstname=request.POST['firstname'], lastname=request.POST['lastname']) member.save() return redirect('/') else: return render(request, 'web/index.html') def login(request): return render(request, 'web/login.html') def home(request): if request.method == 'POST': if Member.objects.filter(username=request.POST['username'], password=request.POST['password']).exists(): member = Member.objects.get(username=request.POST['username'], password=request.POST['password']) token = "white" request.session['token'] = token return redirect('/credentials/') else: context = {'msg': 'Invalid username or password'} return render(request, 'web/login.html', context) and this is my other app when i gather information : from django.shortcuts import render, redirect, HttpResponseRedirect from web.models import Member from django.shortcuts import redirect # Create your views here. def index(request): if request.method == 'POST': member = Member(access_token=request.POST['access_token'], access_token_secret=request.POST['access_token_secret'], consumer_key=request.POST['consumer_key'], consumer_secret=request.POST['consumer_secret']) member.save() return redirect('/analytics/') else: return render(request, 'credentials/index.html') now whenever i run the code two rows are created one for the first app and other for second app i want … -
About Smart contract , token sales
Anybody can help me to transfer token using smart contract? i tried it on local environment, it works! but for mainstream i need to add signed transaction, please explain? (using python,Django, web3 for development) Thanks in advance -
Creating dynamic FIlter classes of JSONField attributes for Django admin
Let's consider below model as an example. from django_mysql.models import JSONField class Student(models.Model): standard = models.CharField(_('Standard'), max_length=10, null=True, blank=True, choices=STANDARD_CHOICES) extra = JSONField() # example data in above field might be as below # {"name": "Bob", "buys": "tesla", "country": "India"} # {"name": "Sam", "buys": "lamborgini", "country": "England"} # {"name": "Izzy", "buys": "tesla", "country": "Egypt"} This is my JSONFieldFilter BaseClass for JSONField filter. Inspired from here class JSONFieldFilter(SimpleListFilter): def __init__(self, *args, **kwargs): super(JSONFieldFilter, self).__init__(*args, **kwargs) assert hasattr(self, 'title'), ( 'Class {} missing "title" attribute'.format(self.__class__.__name__) ) assert hasattr(self, 'parameter_name'), ( 'Class {} missing "parameter_name" attribute'.format(self.__class__.__name__) ) assert hasattr(self, 'json_field_name'), ( 'Class {} missing "json_field_name" attribute'.format(self.__class__.__name__) ) assert hasattr(self, 'json_field_property_name'), ( 'Class {} missing "json_field_property_name" attribute'.format(self.__class__.__name__) ) def lookups(self, request, model_admin): field_value_set = set() for data in Student.objects.values_list( self.json_field_name, flat=True): if self.json_field_property_name in data: field_value_set.add(data[self.json_field_property_name]) return [(v, v) for v in field_value_set] def queryset(self, request, queryset): if self.value(): json_field_query = {"{}__{}".format(self.json_field_name, self.json_field_property_name): self.value()} return queryset.filter(**json_field_query) else: return queryset And derived static filter class as below. class ExtraFilter(JSONFieldFilter): title = _('Car bought') parameter_name = 'CarBought' json_field_name = 'extra' json_field_property_name = 'buys' And then used above derived ExtraFilter class in the list_filter as below at the SchoolAdmin class. class StudentAdmin(admin.ModelAdmin): list_filter = ('standard', ExtraFilter) Now, … -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet with Dajngo mixer
I'm writing test for my Django 2.0 application. I am using mixer and the directory structure is like project |- src |- contact |- migrations |- tests |- __init__.py |- test_models.py |- __init__.py |- models.py |- apps.py |- koober <---- (main app) |- settings |- __init__.py |- local.py |- production.py |- test_settings.py |- urls.py |- wsgi.py |- .coveragerc |- manage.py |- pytest.ini |- other_files |- not_related_to_project |- Pipfile |- Pipfile.lock |- Procfile When I run from project directory project$ pipenv run py.test It gives error as ============================================================================= test session starts ============================================================================== platform linux -- Python 3.6.5, pytest-3.6.1, py-1.5.3, pluggy-0.6.0 rootdir: /home/anuj/code/python/koober, inifile: plugins: django-3.3.0, cov-2.5.1 collected 0 items / 1 errors ==================================================================================== ERRORS ==================================================================================== ______________________________________________________________ ERROR collecting src/contacts/tests/test_models.py ______________________________________________________________ src/contacts/tests/test_models.py:2: in <module> from mixer.backend.django import mixer ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/mixer/backend/django.py:11: in <module> from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation # noqa ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py:3: in <module> from django.contrib.contenttypes.models import ContentType ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/django/contrib/contenttypes/models.py:134: in <module> class ContentType(models.Model): ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/django/db/models/base.py:100: in __new__ app_config = apps.get_containing_app_config(module) ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/django/apps/registry.py:244: in get_containing_app_config self.check_apps_ready() ../../../.local/share/virtualenvs/koober-MOd9u5HA/lib/python3.6/site-packages/django/apps/registry.py:127: in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! =========================================================================== 1 error in 0.31 seconds ============================================================================ When I run the same command from project/src file, it gives error as ImportError: … -
Django ignores content in child template if I use {% extends %}
I am using a parent template called "base.html" placed in the directory myproject/myproject/templates. I render the child template, and everything goes well except when I write {% extends %} to show the parent template. Django behaves very strangely. After a long time trying to figure out the mistake, I've discovered that, even if I write the extends, block, endblock stuff related to the parent template inside a comment, Django still ignores the content in the child template and shows an empty screen. If I intentionally make a syntax error in the content of the template, Django throws an exception (so it really reads the content), but if there is no error, the browser only takes the code from the parent template (I've discovered this using Inspect). Django only shows the content in the child template if it stops having a relationship with the parent template (I can't even have the code extends, block, etc. inside a comment) Here's the code: child template: {% extends "education/base.html" %} {% block barraup %} {{block.super}} {%endblock%} {% block barradown %} {{block.super}} {%endblock%} {% load static %} <link rel="stylesheet" type="text/css" href = "{% static 'principal/principal.css' %}" /> <div id="presentacion"> ...content </div> The last div "presentacion" … -
Cannot execute virtualenv commands when using Python 2.7
I am trying to set up a virtual environment for a Django project, using Python 2.7. Both Python 2.7 and 3.6 are installed on my Mac. I run the command, specifying the path to Python 2.7 virtualenv --python=/usr/bin/python2.7 venv and everything seems to work fine. However, when I run venv source/bin/activate it tells me venv: command not found. Something is broken. I have read similar answers on Stack Overflow but nothing seems to be working. I have installed and uninstalled virtualenv with pip, tried running with superuser etc. -
How to save timestamp field in django rest framework
The serializer.py file class TabsionSerializer(serializers.ModelSerializer): class Meta: model = Tabsion fields = ('sen_id','det_id','latitude','longitude','start_or_end','user_id','username','type','timestamp') In the above the timestamp field is automatically set by database and type field is set by default to one. So these fields were not added to the database. View.py class StartReportSave(viewsets.ModelViewSet): def post(self,request,format=None): reqData = json.loads(request.body.decode("utf-8")) savData = {} savData['sen_d'] = reqData['data']['section']['id']; savData['det_id'] = reqData['data']['depot']['id']; savData['latitude'] = reqData['data']['locationData']['latitude']; savData['longitude'] = reqData['data']['locationData']['longitude']; savData['start_or_end'] = reqData['data']['start_or_end'] ; savData['username']= reqData['userData'][0]['username']; savData['user_id']= reqData['userData'][0]['id']; serializer = TabsionSerializer(data=savData) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201)) return JsonResponse(savData,safe=False) model.py class Tabsion(models.Model): sen_id = models.IntegerField() det_id = models.IntegerField() timestamp = models.DateTimeField() latitude = models.CharField(max_length=100) longitude = models.CharField(max_length=100) start_or_end = models.IntegerField() user_id = models.IntegerField() username = models.CharField(max_length=1000) type = models.IntegerField() class Meta: managed = False db_table = 'tab_reporting_session' When I try to add data the error shows up Timestamp , Type field are required How could I resolve this.? What will be correct way to fetch the id of this inserted record and also to add this to another log table? -
django shell_plus timeit call_command?
I've written a django command and want to see it's timing so inside django shell_plus I do this: import timeit from django.core.management import call_command timeit.timeit("""call_command('prova')""", number=3 ) The command should run 3 times and output its running time. If run directly 'call_command' it works, if called inside timeit it throw this error: /usr/lib/python3.5/timeit.py in timeit(self, number) 176 gc.disable() 177 try: --> 178 timing = self.inner(it, self.timer) 179 finally: 180 if gcold: /usr/lib/python3.5/timeit.py in inner(_it, _timer) NameError: name 'call_command' is not defined -
Django query not working in shell_plus but working in dbshell
I have a query that won't return me an expected value, but when I print the query itself, and run it in Dbshell, it does work. I am on Django 1.8.18 with SQLite version 3.11.0 My Recommendation has a Foreign Key on my Car, and I need to get all my Cars that do not have a Recommendation with is_active=True AND description=FOO. I know I could probably make it work in the other way, but it would be way easier for me to make it work this way. class Car(models.Model): kind = models.CharField(max_length=100) class Recommendation(models.Model): car = models.ForeignKey(Car) is_active = models.BooleanField(default=True) description = models.CharField(max_length=100) I have created a Recommendation linked to my Car id 100, with is_active set to False, and description to FOO Car.objects.exclude(recommendation__is_active=True, recommendation__description="FOO") This query returns me nothing, when I expected it to return Car 100. I decided to print the actual query and try it in dbshell SELECT "myapp_car"."id" FROM "myapp_car" WHERE NOT ("myapp_car"."id" IN (SELECT U1."car_id" AS Col1 FROM "myotherapp_recommendation" U1 WHERE U1."description" = 'FOO') AND "myapp_car"."id" IN (SELECT U1."car_id" AS Col1 FROM "myotherapp_recommendation" U1 WHERE U1."is_active" = 'True')) However, this properly works ! It returns me my Car 100 I have also tried with … -
Display message while looping an Ajax post using Django
How to display message from an ajax loop post while loop is still in progress? Below is an example of the process. Output should display individual string of car list. hmtl file: <div class="row"> {% if messages %} {% for message in messages %} {{ message|safe }} {% endfor %} {% endif %} </div> javascript: $('#btn_generate').submit(function () { var cars = ["Saab", "Volvo", "BMW"]; var index = 0; var result; while (index < cars.length) { var car= cars.slice(index, index + 1); $.ajax({ type: "POST", url: "{% url 'my_site:index' %}", data: { car: car, csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function(data) { result.push(data) } }); index += 1; } }); views.py from django.contrib import messages class IndexView(TemplateView): def post(self, request): car= request.POST['car'] messages.info(request, car) return HttpResponse(car, content_type="application/json") -
Django - fulltext search with postrges and elasticsearch
I have a Django and Django REST Framework powered RESTful API (talking to a PostgreSQL DB backend) which supports filtering on a specific model. Now I want to add a fulltext search functionality. Is it be possible to use Elasticsearch for fulltext search and then apply my existing API filters on top of these search results? -
Django Channels 2.0 and Daphne: serving static and media files
I've searched some time, but couldn't find any tutorial on how to serve static and user uploaded (/media/) files in conjunction with Daphne. I've read that Apache doesn't support ASGI, that it may be possible to use Nginx, but nothing specific. I've also tried whitenoise (which only supports static files) and dj-static (which only supports WSGI). I'd like not to use external CDNs, for privacy reasons. Can you provide any hints on possible setups? -
Not showing '/' at the end of folder name Django
The django project I was working on involves uploading a tar of a folder and analyzing it's contents. When I have asked it to print the contents of that tar file, it is not printing '/' at the end of folder names. Look at the code in forms.py corresponding to that class. (The uploaded tar contains assignment, so the class is named as AssignmentImportForm): class AssignmentImportForm(forms.Form): assignment_archive = forms.FileField( required=True, label="Assignment Archive", help_text="Please upload the assignment archive that follows the structure given in the above sample archive. Accepted archives are tar, tar.gz." ) def __init__(self, *args, **kwargs): kwargs['error_class']=DivErrorList super(AssignmentImportForm, self).__init__(*args, **kwargs) def check_bulk_add(self, data): """ Checks whether the uploaded folder for bulk files of assignment is in specified format Args: data: the archive corresponding to the folder to be uploaded Returns: true or false depending on whether the uploaded folder is in specified format """ #<----------------------------------------------------- with Archive(fileobj=data['assignment_archive']) as archive111: x = archive111.getall_members() print(x) ########################################### #HERE, I'VE ASKED TO PRINT ALL FILES AND FOLDERS INSIDE UPLOADED TAR #<----------------------------------------------------- if 'assignment_archive' in self.changed_data and data.get('assignment_archive', ''): err_message = bulk_import_check(data, self.this_course) if err_message != '': raise forms.ValidationError(err_message) else: if not hasattr(self, 'assignment_archive'): return I've asked it to print the contents of tar … -
not able to reverse redirect dashboard page after a user logs into the site in django
i am creating a credit score calculating website on django but i m facing difficulties in logging in users and then redirecting them to their respective dashboards i am not been able to reverse redirect to my dashboard page after a user login. it is showing this error NoReverseMatch at /personal/login/ Reverse for 'user_dashboard' not found. 'user_dashboard' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/personal/login/ Django Version: 2.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'user_dashboard' not found. 'user_dashboard' is not a valid view function or pattern name. Exception Location: C:\Users\anuj\Documents\djangoenv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636 Python Executable: C:\Users\anuj\Documents\djangoenv\Scripts\python.exe Python Version: 3.6.5 Python Path: ['C:\\Users\\anuj\\Documents\\djangoenv\\CreditSols', 'C:\\Users\\anuj\\Documents\\djangoenv\\Scripts\\python36.zip', 'C:\\Users\\anuj\\Documents\\djangoenv\\DLLs', 'C:\\Users\\anuj\\Documents\\djangoenv\\lib', 'C:\\Users\\anuj\\Documents\\djangoenv\\Scripts', 'c:\\python\\Lib', 'c:\\python\\DLLs', 'C:\\Users\\anuj\\Documents\\djangoenv', 'C:\\Users\\anuj\\Documents\\djangoenv\\lib\\site-packages'] my views.py def user_thanks(request): return render(request,'accounts/user_thanks.html') @login_required def user_dashboard(request): return render(request,'user_dashboard.html') @login_required def logout(request): ulogout(request) return HttpResponseRedirect('user_thanks') def signup(request): user_registered=False if request.method == 'POST': user_form = UserRegistrationForm(data=request.POST) if user_form.is_valid()and user_form.cleaned_data['password1'] == user_form.cleaned_data['password2']: user = user_form.save() user.set_password(user_form.cleaned_data['password1']) user.save() user_registered = True elif user_form.data['password1'] != user_form.data['password2']: user_form.add_error('password2', 'The passwords do not match') else: print(user_form.errors) else: user_form = UserRegistrationForm() return render(request,'accounts/user_registration.html', {'user_form':user_form, 'user_registered':user_registered,}) def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: ulogin(request,user) … -
Django aggregation issue
I have a little problem in connection with aggregation through Django's ORM. The sketch of my model is very simple with some custom field types (but those types are irrelevant in the problem): Fields types class MoneyField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True kwargs['max_digits'] = 15 kwargs['decimal_places'] = 2 super().__init__(*args, **kwargs) class RevenueField(MoneyField): def __init__(self, *args, **kwargs): kwargs['validators'] = [MinValueValidator(0)] kwargs['null'] = True kwargs['blank'] = True super().__init__(*args, **kwargs) class WeakTextField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 200 kwargs['null'] = True kwargs['blank'] = True super().__init__(*args, **kwargs) class NameField(WeakTextField): def __init__(self, *args, **kwargs): kwargs['unique'] = True super().__init__(*args, **kwargs) class YearField(models.PositiveIntegerField): def __init__(self, *args, **kwargs): kwargs['validators'] = [ MinValueValidator(1900), MaxValueValidator(2100), ] kwargs['null'] = True kwargs['blank'] = True super().__init__(*args, **kwargs) class WeakForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True kwargs['on_delete'] = models.SET_NULL super().__init__(*args, **kwargs) Model entities class Company(models.Model): registration_number = NameField(_('Registration number')) # custom field, defined above name = NameField(_('Name')) ... .. . class Financial(models.Model): financial_year = YearField(_('Financial year')) company = WeakForeignKey(to='Company', verbose_name=_('Company')) revenue = RevenueField(_('Revenue')) ... .. . class Meta: unique_together = (('financial_year', 'company'),) My goal is to compose a query with QuerySet like this: SELECT financial_year, SUM(revenue) FROM financial GROUP BY financial_year As far as …