Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test for Django Create and Update View
To simplify, I cannot get the test to create or update the model that I have. I have written an UpdateView and a CreateViewbut I cannot get the test to work. Here are the views: class InventoryCreateView(CreateView): model = BaseInventory context_object_name = 'item' fields = [ 'product_id', 'name', 'color_primary', 'color_secondary', 'category', 'description', 'gender', ] template_name = 'inventory_list/product_detail.html' class InventoryUpdateView(UpdateView): model = BaseInventory context_object_name = 'item' pk_url_kwarg = 'product_id' fields = [ 'product_id', 'name', 'color_primary', 'color_secondary', 'category', 'description', 'gender', ] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['colors'] = Color.objects.all() return context template_name = 'inventory_list/product_detail.html' Here is the test that I have tried to create: def test_create_inventory_view(self): """Test to see if inventory can be created""" form = { 'product_id': 'vp12312', 'name': 'Not a panda', 'color_primary': self.color, 'color_secondary': self.color, 'category': BaseInventory.SHOES, 'description': "Yellow panda", 'gender': BaseInventory.MALE, } request = self.factory.post(InventoryCreateView, data=form) response = InventoryCreateView.as_view()(request) print(request) assert BaseInventory.objects.count() == 1 assert 'inventory_list/product_detail.html' in response.template_name assert response.status_code == 302 def test_inventory_update_view(self): """Test for updating object""" item = BaseInventoryFactory(description='And everything you do') data = { 'product_id': item.product_id, 'name': item.name, 'color_primary': item.color_primary, 'color_secondary': item.color_secondary, 'category': item.category, 'description': 'Yeah they were all yellow', 'gender': item.gender } request = self.factory.post('inventory_list:product-update',data, kwargs={'product_id': item.product_id}, ) response = InventoryUpdateView.as_view()(request, product_id=item.product_id) assert response.status_code … -
Django Auth with LDAP and Local Accounts
I currently have Django and LDAP working. However, I want to limit LDAP authentication to only the accounts within the local account DB. i.e if no local account is present deny access/ldap auth occurring. From looking at the options from LDAPSearch I'm unable to find a direct option to provide this. Any ideas on how to achieve this? Limiting based on LDAP OU is not an option based on the LDAP address structure in place. Thanks, -
business generated has to come based on dcr(daily call report)
I have DCR & SalesMIS model. I want to get the business generated count.and if count is it should return the business_genrated else saleMIS.amount I wrote a method in DCR model i.e. get_business_generated(self) and apply filter on SaleMIS model. Then trying to get the count of business_generated ERROR:D:\Projects\Python\Django\kingllp\venv\lib\site-packages\django\db\models\base.py", line 95, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class builtins.DCR doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This is DCR model class DCR(models.Model): STATUSES = ( ('1N', 'Need Analysis'), ('2P', 'Proposal Stage'), ('3C', 'Competitive Selling'), ('4D', 'Decision Stage'), ) prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE, related_name='dcrs') date = models.DateField(blank=True) status = models.CharField(choices=STATUSES, max_length=2, default='1N') discussion_points = models.CharField(max_length=2047, blank=True) business_generated = models.IntegerField(default=0) is_new_business = models.BooleanField(default=False) def get_business_generated(self): date = self.date client = self.prospect sale = SalesMIS.objects.filter(date=date,client = Prospect) salecount = sale.count() if salecount==0: return DCR.business_generated else: return SalesMIS.amount This is SaleMIS model class SalesMIS(models.Model): class Meta: verbose_name_plural = _("Sale MIS") date = models.DateField() fls = models.ForeignKey(Employee, blank=True, null=True, on_delete=models.SET_NULL, related_name='sales') amount = models.DecimalField(max_digits=20, decimal_places=2) po_number = models.CharField(max_length=255, null=True, blank=True) products = models.CharField(max_length=255, null=True, blank=True) client = models.ForeignKey(Client, blank=True, null=True, on_delete=models.SET_NULL, related_name='client_mis') def __str__(self): return str(self.date) + ":" + self.fls.full_name() Business share has to come based on DCR/MIS -
How can I create a related object in Django 2.0+, simply and effectively
I'd like to find a simple and robust way to create a child object. I think it is a simple problem, probably solved using Django RelationshipManager or Related objects reference. I've gotten it to work in the past (by paying someone on fiver to help me solve this), but I feel that there is a much simpler method that escapes me. This worked on my views.py class MainVisitForm(SingleObjectMixin, FormView): template_name = "clincher/visit_form.html" form_class = VisitForm model = Main def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form=self.get_form() form.fk_visit_user = self.request.user form.fk_visit_main = Main.objects.get(id=self.kwargs['pk']) #added this to save form as we are mixxing the two forms and Models # as the approch of singleObjectMixin is we should get object from DB as per request url as a primary key #and we have defined model as a Main but taking the form view of VistForm as the probem occures # as i think if form.is_valid(): instance = Main() instance.firstname = form.cleaned_data['firstname'] instance.middelname = form.cleaned_data['middlename'] instance.lastname = form.cleaned_data['lastname'] instance.date_of_birth = form.cleaned_data['date_of_birth'] instance.sex = form.cleaned_data['sex'] instance.address = form.cleaned_data['address'] instance.save() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('clincher:main_detail', kwargs={'pk': self.object.pk}) Basically, while the user is in the details page of … -
ModuleNotFoundError: No module named 'django.db.models.functions.base'
when I'm trying to makemigrations, this error is shown: ModuleNotFoundError: No module named 'django.db.models.functions.base' what shall I do? I'm using django v.2.2 -
Two post methods in one class based view
Is there possibility to have 2 post methods in one class based view? I tried to do something like this but of course it doesn't work My custom view: class UserExamDetail(APIView): def get_queryset(self, pk): return Exam.objects.get(pk=pk) def get(self, request, pk): exam = self.get_queryset(pk=pk) if exam: exam_closed = 0 exam_opened = 0 c_questions = ClosedQuestion.objects.filter(exam=exam) o_questions = OpenedQuestion.objects.filter(exam=exam) for question in c_questions: points = int(question.points) exam_closed += points for question in o_questions: points = int(question.points) exam_opened += points exam.score = exam_closed + exam_opened exam.save() serializer = ExamCreatorSerializer(exam) return Response(serializer.data) def post(self, request, pk): serializer = ClosedQuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save(exam=pk) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) def post(self, request, pk): serializer = OpenedQuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save(exam=pk) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) Only first post works and when i try to change function name on for example: post1 and post 2 then Django won't recognize this method as post. If there is possibility to do this, then I'm also curious if I should do this kind of view or maybe Post methods should be separate views? -
Extending admin inteface in django
Below illustrated path didn't helped to customize admin interface STATICFILES_DIRS = [ os.path.join(BASE_DIR, "templates"), ] IN root templates is a folder name there i created a directory admin and inside it base.html {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} So can anyone suggest. what to do now -
how to use both AND or OR conditions in django while filtering
i want to make filter system where if the user selects both year and month then students belonging only to this year's month should be displayed and if the user selects only year then all the students belonging to that year should be displayed.This code works if i select both year and month but doesnot work as OR condition.How can i solve this views.py def serachstudent(request): year = request.GET['year'] month = request.GET['month'] if year or month: students = Student.objects.filter(Q(joined_date__year=year) | Q(joined_date__month=month)) return render(request, "students/view_students.html", {'students': students}) elif year and month: students = Student.objects.filter(Q(joined_date__year=year) & Q(joined_date__month=month)) return render(request, "students/view_students.html", {'students': students}) template <form action="{% url 'students:search_student' %}" class='form-inline'> <!--<label for="month"></label>--> <select name="year"> <option disabled selected>Select Year</option> <option value="2018">2018</option> <option value="2017">2017</option> <option value="2019">2019</option> </select> <!--<label for="month"></label>--> <select name="month"> <option disabled selected>Select month</option> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">Decembery</option> </select> &nbsp; &nbsp; <div> <button type="submit" >Find Students</button> </div> </form> -
Whats the correct format for django dateTime in models?
I am new to django and i am creating my first project. I created one app in which model i define one postgres datatime field but i always get error for this field when run migrate command. I used below value for datetime field in models.py but nothing happened created=models.DateTimeField(default=timezone.now) created=models.DateTimeField(default='', blank=True, null=True) created=models.DateTimeField(blank=True, null=True) created=models.DateTimeField(default='0000-00-00 00:00:00', blank=True, null=True) in my settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True my models.py from django.db import models from django.utils import timezone # from django.contrib.auth.models import User # Create your models here. class Operator(models.Model): operator_code=models.CharField(unique=True, max_length=20) operator_name=models.CharField(max_length=60) operator_type=models.CharField(max_length=60) short_code=models.CharField(max_length=60) apiworld_code=models.CharField(max_length=20) apiworld_operatortype=models.CharField(max_length=20) active_api_id=models.IntegerField(default=1) ospl_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2) apiworld_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2) image=models.CharField(max_length=100) status=models.SmallIntegerField(default=1) updated=models.DateTimeField(default=timezone.now) created=models.DateTimeField(default=timezone.now) def __str__(self): return self.operator_code when i run 'python manage.py migrate' i got below error how to remove this 'django.core.exceptions.ValidationError: ["'0000-00-00 00:00:00' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."]' -
Simulate an OTP verified user for Django testing
I am using django-otp. Here is the .html here is my urls.py path('user_login/', LoginView.as_view(template_name="user_login.html", authentication_form=SimpleOTPAuthenticationForm, redirect_authenticated_user=True), name='user_login') Here is my .html <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Login</button> {% endbuttons %} </form> Here is my forms.py from django_otp.forms import OTPAuthenticationForm from django import forms class SimpleOTPAuthenticationForm(OTPAuthenticationForm): otp_device = forms.CharField(required=False, widget=forms.HiddenInput) otp_challenge = forms.CharField(required=False, widget=forms.HiddenInput) Here is the current test I have for username and password class FormTest(TestCase): def setUp(self): self.credentials = { 'username': 'testuser', 'password': 'secret'} ProjectUser.objects.create_user(**self.credentials) def test_user_password_otp_true(self): response = self.client.post('/user_login/', self.credentials, follow=True) self.assertTrue(response.context['user'].is_active) How can I change the test to include the correct OTP ? -
Django API response to exclude data from serializer
I have an API endpoint that returns data like this: { "customer_device_uuid": "a83e895d-d3b6-4816-b9f9-ee80feb22b36", "device_group": { "group_uuid": "ebd0990b-aeb5-46a4-9fad-82237a5a5118", "device_group_name": "Default", "color": "4286f4", "is_default": true }, "status": [ { "disk_space": 8, "battery_level": 8, "battery_health": "GOOD", "battery_cycles": 99 } ] } I want the response to exclude the status. I have tried to use write_only fields suggested in this question but that did not exclude the status in the response. My serializers.py: class DeviceStatusSerializer(serializers.ModelSerializer): class Meta: model = DeviceStatus fields = ('disk_space', 'battery_level', 'battery_health', 'battery_cycles') class CheckinSerializer(serializers.ModelSerializer): device_group = DeviceGroupSerializer(many=False, read_only=True, source='group_uuid') status = DeviceStatusSerializer(source='customer_device', many=True, read_only=True) class Meta: model = CustomerDevice fields = ('customer_device_uuid', 'customer_uuid', 'device_id_android', 'device_group', 'status') extra_kwargs = { 'customer_uuid': {'write_only': True}, 'device_id_android': {'write_only': True}, 'status': {'write_only': True} } How would I exclude status from the response? -
Django / FactoryBoy - Equal queries not equal?
I am writing tests for a Django application and one of my tests is failing with a strange bug where a assertEqual comparison is failing, even though the objects in both querysets match. The test is quite big, so I've written a small test to recreate the error: class StrangeBehaviorTest(TestCase): def test_init(self): purchase = ArrangementPurchaseFactory() self.assertTrue(purchase) self.assertTrue(purchase.arrangement_period) self.assertEqual(ArrangementPurchase.objects.count(), 1) fetched = ArrangementPurchase.objects.filter( id=1) self.assertEqual(fetched.first().id, purchase.id) self.assertEqual(fetched.first(), purchase) self.assertEqual(fetched, ArrangementPurchase.objects.filter( id=1 )) When I run this test the very last assert fails with the following error: AssertionError: <QuerySet [<ArrangementPurchase: 1 : user_0 - Profound bandwidth-monitored pricing structure (vanaf 2019-04-24)>]> != <QuerySet [<ArrangementPurchase: 1 : user_0 - Profound bandwidth-monitored pricing structure (vanaf 2019-04-24)>]> I've verified that my ArrangementPurchaseFactory is subclassing the DjangoModelFactory (as can be seen below) class ArrangementPurchaseFactory(factory.django.DjangoModelFactory): class Meta: model = arrangement_models.ArrangementPurchase user = factory.SubFactory(UserFactory) arrangement_period = factory.SubFactory(ArrangementPeriodFactory) purchase_date = factory.LazyFunction( lambda: timezone.now() - datetime.timedelta(days=10) ) expire_date = factory.LazyFunction( lambda: timezone.now() + datetime.timedelta(days=30) ) tenant_demo_purchase = False price_paid = factory.LazyFunction(lambda: Decimal(0)) linked_order_id = factory.Faker('sha1') rabo_purchase_pending = False As far as I can tell the object in both querysets exists in the database (the object has an id value), and the pk value of the fetched query matches the existing purchase.id … -
Django CRUD System without django.forms passing {{ id }} to view function
I'm programming a CRUD sysytem (without using django.forms or generic forms) I can't pass id value from toUpArti() to updateArti() can anyone tell me how or mention another way to solve this problem article/views.py: def toUpArti(request, arti_id): d = ArticleItem.objects.get(id=arti_id) return render(request, 'artiUp.html') def updateArti(request): u = ArticleItem.objects.filter(id=x).update(title=request.POST['title'], body=request.POST['body']) return HttpResponseRedirect('/article/') -
Django highcharts dynamic data
Im setting up a data visualization using Highcharts and Django for a school. I have a school which has 8 grades (std1, std2. std3,std4 etc etc....) and in a year there are 6 exams( tem1, tem2, term3.. etc etc) I want to calculate the data in the following format. data= queryset.filter(grade1 and term1) in format of average percentage. data1= queryset.filter(grade1 and term2) in format of average percentage. etc etc till (grade1 and term6). data2= queryset.filter(grade2 and term1) in format of average percentage. 6 exams and 8 grades = 48 different scores. I have tried basic python coding using filtering and loops and list manipulation. def get(self, request): queryset_list = Child.active.all() std1=[] total1=[] a = Child_reports.objects.filter(child__standard__exact='VII', term__exact='1') for x in a: std1.append(x.english) std1.append(x.tamil) std1.append(x.hindi) std1.append(x.maths) std1.append(x.science) std1.append(x.social_science) for integer in std1: if integer !=0: total1.append(integer) divide= len(total1)*100 std1_term1= sum(total1)*100/divide context={ 'std1_term1': std1_term1 } return render(request, self.template_name, context) I got a total score of only one grade and one exam by writing so much code, if I follow the same procedure I will have to write it 48 times . That's DRY Can you help me to simplify this code. -
If statement with cookiecutter has bad syntax
I'm trying to use cookiecutter as the first time in my django project in order to create project skeleton. In my cookiecutter.project_slug, I have a base.py settings file with this part at the end: import cookiecutter {% if cookiecutter.use_celery == 'y' %} CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_TASK_TRACK_STARTED = True # Add a one-minute timeout to all Celery tasks. CELERYD_TASK_SOFT_TIME_LIMIT = 60 {% endif %} But it appears that Django doesn't like the syntax from this part: invalid syntax error Do you know How I can write a good syntax for this part above ? Thank you ! -
How To Fetch all Selected Permissions of Group model in Django
I want to create a custom groups and permissions on django, but i got a problem how can i fetch all selected permissions on choosen group?? {{users_list.permissions}} -
How to config the heroku.yml to use the Heroku PostgreSQL addon?
What I currently I do is to deploy my Django application to Heroku through Building Docker Images with heroku.yml. The app is built well, but it cannot connect to the database, because of the host is not configured correctly. My heroku.yml config is setup: addons: - plan: heroku-postgresql as: DATABASE build: docker: web: Dockerfile config: DJANGO_SETTINGS_MODULE: Django-BaaS.settings_docker release: command: - python manage.py migrate image: web run: web: gunicorn Django-BaaS.wsgi My settings_docker is from .settings_base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'psql', 'HOST': 'DATABASE', 'PORT': '5432' } } My understanding is that heroku.yml is a file which is similar to docker-compose.yml so I tried to use DATABASE as the HOST name (and I tried to use localhost), but it looks like that both are not correct way to connect the database. I seek some help to correct my config or setting files and how to use the PostgreSQL addon on heroku's docker CD pipeline. I am stuck here for a while. Thanks in advance, -
Is it possible to merge django admin sites from different projects into a single django admin site?
I have different django projects as microservices, I want to have a single django admin site configured in one of the django project such that I would be able to manage all the CRUD operations from there only. -
Django: Is there a way to reaggregate the Sum after search?
Currently in my ListView there's a filtering that only shows the data of the current month and year and it aggregates the Sum. Now, in my filtering there are three problems. 1st problem; The filter can only show the current month and year, no way for the user to view the previous month and year. 2nd problem; The search filter for the date__icontains only accepts a numerical value of the months. 3rd problem; After I've added a search filter for a certain month the filter doesn't re-aggregate the Sum. This is my PayrollView class PayrollView(LoginRequiredMixin, ListView): template_name = 'payroll/payroll.html' def get(self, request, *args, **kwargs): search = request.GET.get('search') user = request.user.staffs.full_name current_month = datetime.date.today().month current_year = datetime.date.today().year payroll_list = VaPayroll.objects.all() payroll_data = payroll_list.filter(Q(virtual_assistant__name=user), Q(date__month=current_month)) total_salary = VaPayroll.objects.filter(Q(virtual_assistant__name=user), Q(date__month=current_month), Q(date__year=current_year)).aggregate(Sum('salary')) if search: payroll_data = payroll_list.filter(Q(virtual_assistant__name=user), Q(date__icontains=search)) payroll_data context = { 'total_salary': total_salary, 'payroll_data': payroll_data } return render(request, self.template_name, context) How can I achieve a result that will aggregate the sum after each search based on a certain month? -
How to fix MySQLdb._exceptions.ProgrammingError: wagtailcore_site doesn't exist?
Presently I am deploying my website to pythonanywhere everything is perfect exclude the front-side of my website. I got Internal server error for the front-site then I check out the log file and I noticed this MySQLdb._exceptions.ProgrammingError: (1146, "Table 'transonhoang$default.wagtailcore_site' doesn't exist") **NO MATCH** The above exception was the direct cause of the following exception: **NO MATCH** Traceback (most recent call last): File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/utils/deprecation.py", line 90, in __call__ response = self.process_request(request) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/wagtail/core/middleware.py", line 13, in process_request request.site = Site.find_for_request(request) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/wagtail/core/models.py", line 120, in find_for_request return get_site_for_hostname(hostname, port) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/wagtail/core/sites.py", line 35, in get_site_for_hostname 'root_page' File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/models/query.py", line 268, in __iter__ self._fetch_all() File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql cursor.execute(sql, params) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/transonhoang/.virtualenvs/my-blog/lib/python3.6/site-packages/MySQLdb/cursors.py", … -
How to limit the number of group in a user in Django-Admin
I've been searching for an answer to this all over and I can't seem to find it. I created a user in Django admin and I want to limit the number of group that can be added to it. What's the best way to do that? -
How to fix multiple annotate Sum give wrong answer
i want to annotate observation_taken count and observation_given count in that group. models : - class Observation(TimeStampedEnumeratedUUIDModel): rubric = models.ForeignKey('rubrics.Rubric', related_name='observations') gro`enter code here`up = models.ForeignKey( 'access.Group', related_name='group_observations') observer = models.ForeignKey( 'access.UserRoleAccount', related_name='user_observations_taken') observee = models.ForeignKey( 'access.UserRoleAccount', related_name='user_observations_given') is_published = models.BooleanField(default=False) class UserRoleAccount(TimeStampedUUIDModel): user = models.OneToOneField(User, related_name="user_role_account") role = models.ForeignKey(Role, related_name="user_role_account") account = models.ForeignKey(Account, related_name="user_role_account") multiple annotate Sum terms yields inflated answer UserRoleAccount.objects.filter(pk='24f4a032-3f83-4123-8330fa60fcbb880c').annotate(count=Sum(Case(When(user_observations_taken__group=grp,then=1)),default=0,output_field=IntegerField(),distinct=True)).annotate(count1=Sum(Case(When(user_observations_given__group=grp,then=1)),default=0,output_field=IntegerField(),distinct=True)) -
Django app + Amazon S3 generates RequestTimeTooSkewed when unit testing
I maintain a large Django website and decided to move storage to Amazon S3. We have a lot of unit tests that cover billing/invoicing code. All generated documents are automatically stored as files, and thanks to django-s3-storage they are transparently placed in S3. However, to simulate different scenarios properly, we use freezegun utility that fakes the system time in tests. Some of them change the time a year or more back, and when trying to push files to S3, we get a lot of failures of An error occurred (RequestTimeTooSkewed) when calling the ListObjectsV2 operation: The difference between the request time and the current time is too large. Does anyone have a good solution for such errors? My first ideas are: Move to local storage for tests — a bad idea, as we want tests to use an environment as closely resembling production as possible. Patch the storage code with mock and push the real datetime there — a kind of patch on a patch that adds a layer of complication. -
Django 2.1+ bulk update records with the count of their related records?
I'm trying to bulk update all of my records in table A with the count of their related records in table B. I'd like to do something like: from django.db.models import Subquery, OuterRef, Count table_b_subquery = TableB.objects.filter(a_id=OuterRef('id')) TableA.objects.all().update(table_b_count=Count(Subquery(table_b_subquery))) That would be the equivalent of this NON-BULK method: # Non-Bulk for record in TableA.objects.all(): record.table_b_count = record.table_b_set.count() The error I get trying the bulk method is: *** django.core.exceptions.FieldError: Aggregate functions are not allowed in this query How do I do a seemingly simply count of related records in a bulk update? Ideally I'd like to apply a simple field filter to the count of table B as well. -
IndexError at /password-reset/: string index out of range while resetting password
I am trying to create a password reset feature using django's class based views. I have implemented all the recommended things in django but something just doesn't fits. Whenever i try to click on the send password reset email link button. It throws an string index out of range error. Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/',User_views.register, name='register'), path('profile/',User_views.profile, name='profile'), path('login/' , auth_views.LoginView.as_view(template_name='Users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html' ), name='password_reset_complete'), path('', include ('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here is the settings.py file of my project - INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': …