Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to know how to change html table block color through jinga and django views?
i want to change the color of every block of table according to fee status of student. i.e if fee is not submitted then it should be red, after submission it should be green. I have tried if loop in template but the problem is i am not getting method to compare each class fee with present class fee. <table class="table datatable-key-basic"> <thead> <tr> <th>Student ID</th> <th>Student Name</th> <th>Class</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> <th>January</th> <th>February</th> <th>March</th> <th>Save</th> </tr> </thead> <tbody> {% for info in fee_record %} <tr> {% csrf_token %} <td>{{info.auto_increment_id}} <br /><a href="{% url "updatefeerecord" id=info.auto_increment_id %}">Edit fee</a></td> <td>{{info.first_name}} {{info.last_name}}</td> <td>{{info.selectclass}}</td> <td><div >{{info.april}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.may}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.june}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.july}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.august}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.september}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.october}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.november}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; … -
Problem converting from standard django form select to select2
I am trying to convert django form from using standard select to select2. I have followed instruction and installed django-select-forms, added select2 to INSTALLED_APPS, and include select2 links and scripts in the header block Here is my original code Model.py class Photographer(models.Model): author_id = models.CharField(max_length=50, primary_key=True) displayname = models.CharField(max_length=50) forms.py class UploadFileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.fields['author'].required = True self.fields['author'].queryset = Photographer.objects.all().order_by('displayname') Is ther anyway I can do this without changing my model? -
How to send alert or message from view.py to template?
I am uploading a .xls file from frontend template to Django. In views.py I'm validating the fields of the .xls file, if all is fine I save the file. If there is a problem I wish to send a message or alert back to the template with the alert message which specifies what went wrong. I would prefer if the error msg is shown below the file upload field, however, any js alert or any other way is fine too. Please help. Thanks Extra: If possible I would like to change a span element in my template. Is it possible to do it from views.py? (I'm uploading the file using AJAX request.) I tried using messages but nothing is happening. In views.py: if request.method == 'POST' and request.FILES: . --code to verify and save the file or generate error msg-- . if error != 'false': messages.info(request, 'The file you uploaded has the following problem: '+error+'. Please fix it and upload the file again') In template: {% block content %} --lot of html-- . --file upload field-- . {% if messages %} <ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} . … -
Django Management Command does not import correctly
I am trying the execute a management command in Django that doesn't quite correctly import the modules. My project structure is as follows: myproject/ |-- appname/ | |-- __init__.py | |-- management/ | | |-- commands/ | | | |-- __init__.py | | | |-- somefile.py | | |--__init__.py | |-- migrations/ | |-- admin.py | |-- apps.py | |-- views.py | |-- models.py | |-- urls.py |-- myproject/ | |-- __init__.py | |-- settings.py | |-- urls.py | |-- wsgi.py |-- manage.py ` myapp/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' myapp/init.py default_app_config = 'myapp.apps.MyAppConfig' myapp/management/commands/somefile.py from django.core.management import BaseCommand from django.utils.datetime_safe import datetime from myproject.myapp.models import Car class Command(BaseCommand): help = "Create initial data" def handle(self, *args, **options): cars = Car.objects.all() print(cars) self.stdout. write('Command successfully executed!') Traceback (most recent call last): File "myapp/management/commands/somefile.py", line 4, in from myproject.myapp.models import Car ModuleNotFoundError: No module named 'myproject' How do I configure the app to have the management command address the correct dir? -
command not found: django-admin when using django-admin startproject prj in mac
I'm trying to start a new project using django usign the command django-admin startproject prj1 in Mac, but it shows command not found:django-admin. -
'User' object has no attribute 'get' when trying to get user data in update profile form
im new in django. i'm trying to get user data in the update form. here is my code: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) image = models.ImageField(upload_to='profile_images', default='default.jpg') def __str__(self): return f'{self.user}' forms.py class UpdateUserForm(forms.ModelForm): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) class Meta: model = User fields = ['first_name', 'last_name'] class UpdateProfileForm(forms.ModelForm): image = forms.ImageField(widget=forms.FileInput(attrs={'class': 'uk-button uk-button-default uk-button-medium uk-width-1-1', 'type': 'file'})) class Meta: model = Profile fields = ['image'] views.py @verified_email_required def profile_view(request): u_form = UpdateUserForm(request.user) p_form = UpdateProfileForm(request.user.profile) title = 'Profile Page' template_name = 'profile.html' context = { 'title': title, 'u_form': u_form, 'p_form': p_form } return render(request, template_name, context) and i get this error: 'User' object has no attribute 'get' -
How to modify data of auth_user column using django in postgresql
I want to modify column for auth_user through Django project. I have created an HTML page to allow the user to change their info in auth_user column. I have tried many things but none worked. Please help -
How to use ModelChoiceField with ModelForm and AbstractUser DJANGO
I want to create a dropdown button on an invoice page for the manager to select the appropriate customer to send to and save it. My current issue is to set up the forms.py and views.py correctly I believe. In regards to the forms.py I have tried using forms.Form without the class Meta and when i press 'SAVE' button on the HTML page ,the terminal return: 'UserDropDownForm' object has no attribute 'save' USERAPP - models.py User = settings.AUTH_USER_MODEL class User(AbstractUser): is_customer = models.BooleanField(default=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) phone_number = models.CharField(max_length=10) city = models.CharField(max_length=30) state = models.CharField(max_length=30) postal_code = models.CharField(max_length=30) active = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50) company_name = models.CharField(max_length=30) active = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username INVOICEAPP - models.py class Invoice(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_invoices') number = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Service, on_delete=models.CASCADE, related_name='invoice_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) INVOICEAPP - forms.py class UserDropDownForm(forms.ModelForm): user_form = forms.ModelChoiceField(queryset=User.objects.order_by('id').filter(is_customer='True')) # class Meta: (DO I NEED CLASS META????) # model … -
Django + tox: Apps aren't loaded yet
I'm migrating a Django project to use Tox and pytest. I'm getting the following when running tox. _________________________________________ ERROR collecting fixtureless/tests/test_django_project/test_app/tests/test_factory.py _________________________________________ fixtureless/tests/test_django_project/test_app/tests/test_factory.py:10: in <module> from test_app.models import ModelOne, ModelTwo fixtureless/tests/test_django_project/test_app/models.py:11: in <module> class ModelOne(models.Model): .tox/py36-django21/lib/python3.6/site-packages/django/db/models/base.py:87: in __new__ app_config = apps.get_containing_app_config(module) .tox/py36-django21/lib/python3.6/site-packages/django/apps/registry.py:249: in get_containing_app_config self.check_apps_ready() .tox/py36-django21/lib/python3.6/site-packages/django/apps/registry.py:132: in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is my tox file. [tox] skipsdist = true envlist = py{36,37}-django21, py{36,37}-django22, # Add environment to use the default python3 installation [testenv] setenv = PYTHONDONTWRITEBYTECODE=1 PYTHONPATH = {toxinidir}:{toxinidir}/fixtureless/tests/test_django_project DJANGO_SETTINGS_MODULE = settings.postgres deps = pillow psycopg2 pytest django21: Django>=2.1,<2.2 django22: Django>=2.2,<2.3 commands = pytest It's like django.setup() isn't being invoked or something. I'm fairly new to tox still. Any help would be greatly appreciated. This is an open source project (django-fixtureless) and I have been successfully running the Django test suite using the instructions outlined here. -
My css and images arent showing in django
I'm very new to using Django and am having issues with my css and images appearing in my home.html. I added a STATICFILES_DIR after looking it up, however it's still no appearing. I also tried adding path('', include('template/pesq.css')) to urlpatterns but that just caused some errors so I took it out. home.html <html> <head> <title>homepage</title> {% load static %} <link href="{% static 'pesq.css' %}" rel="stylesheet"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> ... urls.py from django.urls import path from . import views from django.conf.urls import url, include app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("", views.register, name='register'), path('tinymce/', include('tinymce.urls')), #path('', include('template/pesq.css')) ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Context, loader from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from .models import info # Create your views here. def homepage(request): return render(request=request, template_name="template/home.html", context={"info": info.objects.all})#context_instance=RequestContext(request), def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') login(request, user) return redirect("main:homepage") else: for msg in form.error_messages: print(form.error_messages[msg]) return render(request = request, template_name = "main/register.html", context={"form":form}) form = UserCreationForm return render(request = request, template_name = "main/register.html", context={"form":form}) setting.py ... DEBUG = True ... INSTALLED_APPS … -
How to validate a single field in a django form after an ajax request
I'm trying to validate a single field in a django form, after an ajax request - which I would prefer to validate on the backend rather than the frontend due to the detailed validation required. However using ajax means I can give earlier feedback to the user if the validation fails, before having to validate the full form. So instead of checking if form.is_valid() I could just check the field instead? def some_ajax_view(request): form = Form(request.POST): if form.is_valid(): .... -
how to correct binascii.Error: Incorrect padding?
i was writing a view in view.py and i tried to get the username (b2b_pan) that already loged in from the Header. then i figured out that i can get it by using request.META, but i got some problem and i don't know why here is the Code: class InventoryListView(generics.ListAPIView): permission_classes=[IsAuthenticated,] pan = "" b2b_pan = "" # def header_auth_view(request): def get (self,request, *args, **kwargs): the_serializer = InventorySerializer(data = request.data) auth_header = request.META['HTTP_AUTHORIZATION'] encoded_credentials = auth_header.split(' ')[1] #remove basic to isolate credentials (basic username:password) decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':') b2b_pan = decoded_credentials[0] if the_serializer.is_valid(): pan = request.data['pan'] the error is : File "/home/.venv/lib/python3.7/base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding -
Django admin form override stop required validation
I have a Django model with the following two fields. period_from = models.DateField(verbose_name='From') period_to = models.DateField(verbose_name='To') I created a model form to do a custom validation as follows. class AdminBillForm(ModelForm): class Meta: model = Bill exclude = () def clean_period_from(self): period_from = self.cleaned_data.get('period_from') if (period_from >= timezone.now().date()): raise ValidationError("'From' date cannot be a future date.") return period_from def clean_period_to(self): period_to = self.cleaned_data.get('period_to') if (period_to > timezone.now().date()): raise ValidationError("'To' date cannot be a future date.") return period_to def clean(self): cleaned_data = super(AdminBillForm, self).clean() period_from = cleaned_data.get('period_from') period_to = cleaned_data.get('period_to') if (period_from >= period_to): raise ValidationError("'From' date should not be beyond 'To' date.") Then I registered this form in the admin. @admin.register(Bill) class BillAdmin(admin.ModelAdmin): form = AdminBillForm However if I left the period_from field empty it gives me following error. '>=' not supported between instances of 'NoneType' and 'datetime.date' When I remove the custom form it works perfectly saying that the period_from is a required field. -
Trying to get log_error decorator to work in Django, but getting tuple error
Trying to mimic the first answer in this post and create a log_error decorator: Log all errors to console or file on Django site Here is the error that I get: raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). Maybe I'm not supposed to put this function in views.py or maybe this doesn't work in Django 2.2.3? def log_error(func): def _call_func(*args, **argd): try: func(*args, **argd) except: print("error") #substitute your own error handling return _call_func -
How to filter Django model Multipoint objects which are located in an envelop?
I have following model: from django.contrib.gis.db import models class Foo(models.Model): # some other fields multipoint = models.MultiPointField() I am going to filter Foo instances based on the multipoint field and get all the instances that their line is located inside an envelop. I am aware that PostGIS has some functions to do so (right now, I get the answer using the following query) but I am looking for a Django ORM query. select name, ST_AsText(multipoint) AS text_multipoint from core_foo where ST_Contains(ST_MakeEnvelope(30, 30, 50, 50, 4326), multipoint); I am looking for the equivalent of the above SQL query. -
dynamic fields in django with javascript
I created a small javascript to add fields dynamically inside a form. However I'm encountering the following problem: Say I create a form and save it with two fields dynamically created. I then edit that form and delete one of the fields. If press submit, the form shows me an error saying that the field I deleted is required. it also creates two additional fields. What am I doing wrong? Javascript snippet: $( document ).ready(function() { $('textarea').autogrow({onInitialize: true}); $(".circle--clone--list").on("click", ".circle--clone--add", function () { var parent = $(this).parent("li"); var copy = parent.clone(); parent.after(copy); copy.find("input[type='text'], textarea, select").val(""); copy.find("*:first-child").focus(); updatePositions(); }); $(".circle--clone--list").on("click", "li:not(:only-child) .circle--clone--remove", function () { var parent = $(this).parent("li"); parent.remove(); updatePositions(); }); function updatePositions() { var listPositions = $("ul.circle--clone--list li"); listPositions.each(function (i) { var position_TOTAL_FORMS = $(this).find('#id_position-TOTAL_FORMS'); position_TOTAL_FORMS.val(listPositions.length); var title = $(this).find("input[id*='-title']"); title.attr("name", "position-" + i + "-title"); title.attr("id", "id_position-" + i + "-title"); var information = $(this).find("input[id*='-information']"); information.attr("name", "position-" + i + "-information"); information.attr("id", "id_position-" + i + "-information"); }); } }); Template snippet: <ul class="circle--group--list circle--clone--list"> <h3>Position Title</h3> {% for form in position_formset %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {{ form.errors }} <li> {{ position_formset.management_form }} {{ form.title }} <h5>Position Information</h5> {{ … -
how can we add a username field in registration form using Django oscar
I'm trying to add username field in registration form in django oscar. Please can any one help and tell me how to add this field in the form. -
Outputing a created object in javascript to a server side JSON file
I want to create a JSON file filled with an object that the client requests by "post" method. I've tried to assign value to an HTML tag, and access it from my views.py function. HTML file code: var myobj = {}; {% for f in foos %} {% for g in goos %} myobj["{{ g }}_{{ f }}"] = "{{ g.name }} {{ f.name }}" {% endfor %} {% endfor %} document.getElementById('myobj').value = myobj; views.py file code: def out_to_json(request): f = open(r"\main\jsons\first.json",'w+') _obj = request.POST['myobj'] f.write(str(_obj)) f.close() The result in my JSON file is [object Object]. Is running through all keys of my obj is necessary to access each value separately? I except the output of the full object as it is in the console. -
What is the issue that is causing Payload Error in JWT using Django
I want to authorise an API using login token using JWT but when i run the code it gives me invalid payload error.I have already added necessary modules that needed to be added. This is for a project that i am doing for a college purposes my idea is for a social site def post(self, request): token = request.headers['authorization'] data = {'token': token} payload_decoded = jwt.decode(token, settings.SECRET_KEY) try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user_id = valid_data['user'] except ValidationError as v: print("validation error", v) serializer = InstructorDetailsSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i am receiving payload error and want to actually resolve the issue. -
invalid literal for int() with base 10: - django
I am new to Django and trying to pass an author's name to a view and filter out quote objects based on the author's name. here are the codes: models.py class Program(models.Model): class Meta: verbose_name_plural = 'Program' program_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) program_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' program = models.ManyToManyField(Program, blank=False) course_code = models.CharField(max_length=10, default='', unique=True, validators=[MinLengthValidator(1)]) course_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) urls.py: urlpatterns = [ path('',views.programs,name='programs'), path('<slug:program_code_no>/',views.courses,name='courses'), ] views.py def programs(request): obj = Program.objects.all() paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/programs/index.html',context=all_details) def courses(request,program_code_no): obj = Courses.objects.filter(program=program_code_no) paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/courses/index.html',context=all_details) However, I get this error when I try to get http://127.0.0.1:8000/programs/P132/ ('P132' is a program_code object, already created) ValueError at /programs/P132/ invalid literal for int() with base 10: 'P132' Request Method: GET Request URL: http://127.0.0.1:8000/programs/P132/ Django Version: 2.2.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'P132' Exception Location: C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 966 Python Executable: C:\Users\Prabu\Anaconda3\envs\codeforcoder\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Prabu\\Desktop\\Django codeforcoder\\codeforcoder ' 'v1.0.1\\codeforcoder', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\python37.zip', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\DLLs', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\lib', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder', 'C:\\Users\\Prabu\\Anaconda3\\envs\\codeforcoder\\lib\\site-packages'] -
How do i use Vue templates in Django?
This is my index page in django {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/3.8.95/css/materialdesignicons.css"> <meta charset="UTF-8"> <title>My test</title> </head> <body> <div id="app"> <h1>TEST</h1> </div> {% render_bundle 'main' %} </body> </html> And this is a standard Vue navbar. <template> <v-app id="sandbox"> <v-navigation-drawer v-model="primaryDrawer.model" :clipped="primaryDrawer.clipped" :floating="primaryDrawer.floating" :mini-variant="primaryDrawer.mini" :permanent="primaryDrawer.type === 'permanent'" :temporary="primaryDrawer.type === 'temporary'" app overflow ><v-switch v-model="$vuetify.theme.dark" primary label="Dark" ></v-switch></v-navigation-drawer> <v-app-bar :clipped-left="primaryDrawer.clipped" app > <v-app-bar-nav-icon v-if="primaryDrawer.type !== 'permanent'" @click.stop="primaryDrawer.model = !primaryDrawer.model" ></v-app-bar-nav-icon> <v-toolbar-title>Vuetify</v-toolbar-title> </v-app-bar> </v-app> </template> The code is working, and i can see Vue being loaded when i open my Django site. The problem with this is that i don't know how to get them along. For example, i added a <h1>TEST</h1> but it does not appear when i load Vue, since the Vue part covers it. I also don't understand, if i have a conditional on my Django template, such as {% if user.is_authenticated %} i can't use it on Vue, because it won't be loaded by it. For example, i have a navbar. Instead of that navbar i want to use the below Vue navbar but i can't, because the current navbar has some links to parts of my site, and since … -
Open the xx.html file based on drop down menu from Navigation bar, code is written in Django-Python
The code is written in Django-Python. The project is created using the models in Django and shown in navigation as dropdown menu. The drop-down menu is shown using the Django-HTML as shown in following way: This code works well for dropdown menu. but I want to open the different project url based on click. I am not sure exactly how to assign id and use javascript to code do onclick bsed html loading !! I have tried some javascript code, but I am novice.. so If I put here.. it would be more confusing. <div class="dropdown-menu" id="navbarDropdown"> {% if project_records %} {% for p in project_records %} <a href="#" class="dropdown-item"> {{ p.pName }} </a> {% endfor %} {% endif %} </div> I expect that projectB.html will be loaded if click projectB in dropdown menu in navigation bar. -
How to redirect to a newly created object in Django?
I'm trying to redirect to the created object by filling the form below. I've tried the solutions that I found on these posts: How to redirect to a newly created object in Django without a Generic View's post_save_redirect argument and here: Redirection after creating an object, Django Sometimes it just don't redirect and some other times it says property was not initiated. What am I doing wrong here? # views.py def add_property(request): if request.method == 'POST': property_add_form = PropertyAddForm(request.POST, request.FILES) if property_add_form.is_valid(): property = property_add_form.save() # formset = ImageFormset(request.POST or None, request.FILES or None, instance=property) # if formset.is_valid(): print("Sucesso") return HttpResponseRedirect(reverse('property:property_detail', kwargs={'property':property.id})) else: property_add_form = PropertyAddForm() print("Error") context = { 'property_form':property_add_form, 'title':"Add Property", } return render(request, 'properties/add-property.html', context) . #urls.py url(r'^add-property/', views.add_property, name='add_property'), -
uWSGI server sometimes hung up for unknown reasons
Problem I've operated Django + uWSGI apps for a year on AWS, and it was working well until two weeks ago, but I run into the problem that the specific uWSGI process sometimes hung up and rarely recover automatically. Strangely enough, I'm always running three uWSGI servers on the same EC2 instance, but only the specific (most accessed) process always hung up, and the rest two uWSGI processes never hung up and continue to respond to HTTP requests even during the error. Even though they work on the same hardware and network, and are connected to same MySQL/Redis server. uWSGI dumped the following "OSError: write error" message during it was stuck, (but I think the message doesn't seem the useful information...) Sat Aug 17 15:44:30 2019 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during POST /XXXX(172.XXX.XXX) OSError: write error [pid: 2131|app: 0|req: 921/7007] 172.XXX.XXX.XXX () {62 vars in 1416 bytes} [Sat Aug 17 15:44:30 2019] POST /XXXX => generated 0 bytes in 28 msecs (HTTP/1.1 200) 5 headers in 0 bytes (0 switches on core 0) and the Django dumped the following 500 error message. 2019/08/17 15:43:32 [error] 2265#0: *13198 upstream timed out (110: Connection timed out) while reading response … -
Django: QuerySet with ExpressionWrapper
I currently try to get max_total_grossfrom all tickets within an event. That's how far I came but it doesn't work yet. tickets = event.tickets.all().annotate( max_total_gross=Sum(ExpressionWrapper( F('quantity') * F('price_gross'), output_field=IntegerField(), )) ).values( 'max_total_gross' ) Goal: Sum( price_gross_x_quantity_ticket_1 + price_gross_x_quantity_ticket_2 + price_gross_x_quantity_ticket_3 + [...] ) Here my ticket model: class Ticket(TimeStampedModel): event = models.ForeignKey( 'events.Event', on_delete=models.CASCADE, related_name='tickets' ) # CASCADE = delete the ticket if the event is deleted price_gross = models.PositiveIntegerField( verbose_name=_("Price gross"), help_text=_("Includes tax if you set any.") ) quantity = models.PositiveIntegerField( verbose_name=_("Quantity"), validators=[MinValueValidator(1), MaxValueValidator(100_000)], ) # [...]