Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom datepicker function only fills in the field of the first django form of multiple forms with same fields
I have three django forms that have two fields that are both multifields. All of these fields have two inputs. I made it so that these fields would be connected to datepickers and would give the date range. The first input would get the start date, and the second input would get end date. Below is the relevant code: forms.py class FirstDateRangeWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(attrs={'class': 'form-control first-from', 'placeholder': 'From'}), forms.TextInput(attrs={'class': 'form-control first-to', 'placeholder': 'To'}) ) super(FirstDateRangeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value return [None, None] class FirstDateRangeField(forms.MultiValueField): widget = FirstDateRangeWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(), forms.CharField(), ) super(FirstDateRangeField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return data_list class SecondDateRangeWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(attrs={'class': 'form-control second-from', 'placeholder': 'From'}), forms.TextInput(attrs={'class': 'form-control second-to', 'placeholder': 'To'}) ) super(SecondDateRangeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value return [None, None] class SecondDateRangeField(forms.MultiValueField): widget = SecondDateRangeWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(), forms.CharField(), ) super(SecondDateRangeField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return data_list class FirstForm(forms.Form): first_field = FirstDateRangeField() second_field = SecondDateRangeField() class SecondForm(forms.Form): first_field = FirstDateRangeField() second_field = SecondDateRangeField() class ThirdForm(forms.Form): first_field = FirstDateRangeField() second_field = SecondDateRangeField() template.html {% block main_content … -
Django not applying css files or displaying image
I am figuring out how to use django, and this is my first project (other than the tutorial). I am trying to apply some css to my html using static files, but I see no change in the html. I tried displaying an image just to see if there was something wrong with my css, but that didn't work either. When I run python manage.py collectstatic it is collecting my files so I know that it can find them. What am I doing wrong? Here is the head of my html file: <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'mainpage/mainpage.css' %}"> </head> And here is where I try to load the image: <img src="{% static 'mainpage/example.jpg' %}" alt="Example Image"> The css file (this is just the mainpage one, but the others are similar): h1 { color: green; } li a { color: green; } header { background-color: black; } And my file structure: abstract | |---mainpage | | | |--- static | | | | | |---mainpage | | | | | | | |---mainpage.css | | | | | | | |---example.jpg Again, it can find the files, so that is not the problem. Any help would … -
how to setup django timezone in pythonanywhere
I have just deployed my django website to pythonanywhere and I have noticed that it uses a different timezone than the one which my local server is using. I have an article model which contains a datetime field class Article(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=100,null=False,blank=False) category=models.ForeignKey(Category,null=False,blank=False) date=models.DateTimeField(auto_now_add=True) content = models.TextField(null=False, blank=False) resume=models.CharField(null=False,blank=False,max_length=400) image = models.FileField(blank=True) I tried adding an article which was supposed to be saved at 13/07/2018 22:20, but is was saved at 13/07/2018 16:20 It seems that my website is hosted in another country which uses a different timezone, as my current timezone is GMT+1 Any help would be appreciated -
Is there a file size limit or extension limit in wagtail?
I have a very simple model (Product) which is used as an InlinePanel in a page. Product has a FileField which works fine as long as I upload small files, but as soon as I upload a large file (>5MB), I somehow get an CSRF error. Both on local and on production. It is not an issue with nginx max upload size. Is there a file size limit or extension limit in wagtail? -
How to use django-haystack with django-machina and SQLite?
I'm using django-machina as forum app and it has django-haystack integration in the box which is great, but I don't need to setup Sorl or Whoosh yet, the client asked to use SQLite for beginning. However when I'm trying to search ANYTHING in search form, I receive such SQL query: SELECT forum_conversation_post.id, forum_conversation_post.created, forum_conversation_post.updated, forum_conversation_post.topic_id, forum_conversation_post.poster_id, forum_conversation_post.poster_ip, forum_conversation_post.anonymous_key, forum_conversation_post.subject, forum_conversation_post.content, forum_conversation_post.username, forum_conversation_post.approved, forum_conversation_post.enable_signature, forum_conversation_post.update_reason, forum_conversation_post.updated_by_id, forum_conversation_post.updates_count, forum_conversation_post._content_rendered FROM forum_conversation_post WHERE (forum_conversation_post.anonymous_key LIKE '%[1]>%' ESCAPE '\' OR forum_conversation_post.subject LIKE '%[1]>%' ESCAPE '\' OR forum_conversation_post.content LIKE '%[1]>%' ESCAPE '\' OR forum_conversation_post.username LIKE '%[1]>%' ESCAPE '\' OR forum_conversation_post.update_reason LIKE '%[1]>%' ESCAPE '\' OR forum_conversation_post._content_rendered LIKE '%[1]>%' ESCAPE '\') ORDER BY forum_conversation_post.created ASC In short, it just changes any search phrase to "[1]>" string on the SQL level. I've spent many hours tying to figure out what's wrong with it, but can't understand why does it happen and how to solve the issue. -
Where to store auth token (frontend) and how to put it in http headers of multiple endpoints?
I wanted to write auth backend for both mobile and webapp, so I decided to go with the DRF (Django Rest Framework) token authentication. I pretty much figured out backend via DRF documentation but regarding frontend implementation it just says "include token in the header of every http request to the API." So my question is When I retrieve token in AJAX call where should I store it so that upon browser refresh it doesn't disappear? (Apparently I'm not using cookies, because phones have restriction on cookie uses ) How to insert the auth token in the http headers of multiple API endpoints? With the help of Stackoverflow I figured out how to insert auth token in a single http header. $.ajax({ url: "https://www.something.com/random", type: 'get', headers: { token: "t&jdd9HJKHdss7hkjjkhdshgs", } }); I was wondering If I have to write this piece of code for every endpoints or is there a way cover all the endpoints without being redundant? -
Django Parse CSV and then Upload. ('Error: can't; concat bytes to inmemoryuploadedfile')
I'm trying to parse a CSV, check for errors and then save it if there are no errors. However - after parsing, I get the error 'TypeError: can't concat bytes to InMemoryUploadedFile'. I feel like this could be because I don't actually close the file. upload_obj = UploadField(csv=True) csv_upload = request.FILES.get('uploads', None) csv_parsed = csv.reader(codecs.iterdecode(csv_upload, 'utf-8'), delimiter=',') parsing stuff... try: upload_obj.save(request=request, content_list=csv_upload) except Exception as e: print('Error:', e) I get the error when attempting to save. Is there a way to get CSV Reader to close the file so I may save it? -
Custom field / force password change
I need to force a user to change password in a Django application, and specifically a rest-based application. Django is using rest_framework and simplejwt. I was able to implement a custom claim view as specified Here My plan was to add a custom user model with a flag, and if the user did not change the password after its first access, the app would return 'must_change_password':true However I get no added field. Any ideas or experiences around this concept would be greatly appreciated. -
adding a ListView and a DetailView in the same page Django Order history Page
Hi Djangonauts! Supposing I was making a restaurant app clone. I want the order history page to look like this image I have function based views similar to ListView and DetailView. The Grey part is the OrderList View and below that is the OrderDetailView (a small summary atleast). Below are my views.py @login_required() def orderHistory(request): if request.user.is_authenticated: email = str(request.user.email) order_details = Order.objects.filter(emailAddress=email) return render(request, 'order/orders_list.html', {'order_details': order_details}) @login_required() #This part is for a different(View Detail) view I just added it anyway def viewOrder(request, order_id): if request.user.is_authenticated: email = str(request.user.email) order = Order.objects.get(id=order_id, emailAddress=email) order_items = OrderItem.objects.filter(order=order) return render(request, 'order/order_detail.html', {'order': order, 'order_items': order_items}) below are my models.py class Order(models.Model): token = models.CharField(max_length=250, blank=True) total = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='USD Order Total') emailAddress = models.EmailField(max_length=100, blank=True, verbose_name='Email Address') created = models.DateTimeField(auto_now_add=True) billingName = models.CharField(max_length=350, blank=True) billingAddress1 = models.CharField(max_length=350, blank=True) billingCity = models.CharField(max_length=100, blank=True) billingZipcode = models.CharField(max_length=10, blank=True) billingCountry = models.CharField(max_length=50, blank=True) class OrderItem(models.Model): product = models.CharField(max_length=250) quantity = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='USD Price') order = models.ForeignKey(Order, on_delete=models.CASCADE) How do I add the detail context(viewOrder) in my (orderHistory) I tried the below but it is not working. Any advise on how I can change the below code @login_required() def orderHistory(request, … -
Django: formset with javascript and initial not working
I have modelform and formset: class GuestForm(ModelForm): car_brand = forms.CharField(label='Марка авто', required=False) car_number = forms.CharField(label='Гос.номер', required=False) class Meta: model = Guests fields = ('guest_organisation', 'guest_last_name', 'guest_first_name', 'guest_patronymic', 'guest_position', 'guest_hosts') GuestsFormSet = formset_factory(GuestForm, extra=1, can_delete=True, formset=MyWithDeleteFormSet, max_num=20) And I have JS in template {% extends "base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} {% block title %}{% endblock %} {% block content %} <h2>Заявка на пропуск</h2> <hr> <div class="col-md-4"> <form action="" method="post" target="_blank"> {% csrf_token %} {{ application_f.as_p }} <h3>Список гостей</h3> <table class="table" id="guests"> {{ guests_fs.management_form }} {% for form in guests_fs.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tbody> <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> <input type="submit" value="Сохранить и сформировать заявку"/> <a href="{% url 'applications-main' %}">Назад</a> </form> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static … -
How to ignore error instead of returning 400 Bad Request?- Django Rest Framework
I have a model named Cart. Cart has an Foreign Key to Coupon. When I POST to create a new Cart, it runs some validations to find if Coupon exists. If not, it return Error 400 saying that the object does not exist. I dont want an 400 Error, I need it to continue the processes returning Coupon as Null. serializers.py class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(format='hex', read_only=True) delivery = DeliverySerializer(required=False, write_only=True) customer = CustomerSerializer(required=False, write_only=True) coupon = CouponSerializer( required=False, ) totals = serializers.SerializerMethodField() class CouponSerializer(serializers.Serializer): code = serializers.SlugRelatedField( slug_field='code', required=False, source='coupon', queryset=Coupon.objects.only_valid(), ) def to_representation(self, coupon): return { 'code': coupon.code, 'discount_amount': coupon.discount_amount, 'discount_percentage': coupon.discount_percentage, 'only_first_order': coupon.only_first_order, } views.py class CartViewset(CreateModelMixin, GenericViewSet): queryset = Cart.objects.all() serializer_class = CartSerializer permission_classes = (AllowAny,) -
Django collect static and requirements
Is there a way to collect static files without installing all requirements? I don't see a point to do pip install -r requirements.txt in order to be able to collect static files. I find this problematic when one wants to collect static files during "build stage" in CI. -
GeoDjango - database no syncing with AWS RDS
I'm deploying a GeoDjango app with AWS EB. I've also set up a PostgreSQL db and installed all the requirements on EC2 instance. In my settings.py file: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } If it is set like this, my config file for eb has the following error: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' My config file is as follow: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true If I set my settings.py file as this: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } there wouldn't be no error but the database won't migrate on RDS as I cannot query data on my Django app. What should I fix? -
django apache application just keep on loading forever
I have configured my django application with apache. If I am running my app using runserver its working fine but when I am trying to run it using apache it just keeps on loading. Here is my apache 000-default.conf file- WSGIPythonPath /usr/local/lib/python3.5/site-packages:/var/www/html/caremeasurement #WSGIApplicationGroup %{GLOBAL} Timeout 30 <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/caremeasurement Alias /favicon.ico /var/www/html/caremeasurement_static/images/favicon.ico Alias /assets /var/www/html/caremeasurement_static <Directory /var/www/html/caremeasurement_static> Require all granted #Options FollowSymLinks </Directory> Alias /media /var/www/html/caremeasurement_media <Directory /var/www/html/caremeasurement_media> Require all granted #Options FollowSymLinks </Directory> <Directory "/var/www/html/caremeasurement/app"> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess mydemo user=webapp group=webapps python-path=/var/www/html/caremeasurement python-home=/usr/local/lib/python3.5/site-packages #WSGIProcessGroup mydemo WSGIScriptAlias / /var/www/html/caremeasurement/app/wsgi.py # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, … -
How can I test a process_exception function of a custom Django Middleware Class?
I have written a custom Django MiddleWare class to do some additionaly handling of exception information using process_exception. This seems to be working well when I run my server, but when I go to write my test I cannot figure out how to trigger that function. According to the docs for process_exception: Django calls process_exception() when a view raises an exception. I want to write a test to ensure this is happening so I know my middleware is actually active and working. After mocking out various view functions to trigger exceptions without getting the desired behavior, I finally just tried sticking a 1/0 in one of the view functions. When I did so my test failed because of an ZeroDivisionError. This would be expected, except Django is supposed to catch those exceptions and trigger my process_exception function. My actual question has two parts: Does Django middleware behave differently during tests? Is there something I can do differently to be able to test that my middleware is configured properly to get triggered by exceptions? -
error when running manage.py migrate
I got an errors that I can't fix when I'm trying to run Scirius project on my Ubuntu 16.04 LTS and I'm newbie in this field. can someone help me out, I need to run this project that I cloned from https://github.com/StamusNetworks/scirius python manage.py migrate > Traceback (most recent call last): File "manage.py", line 10, in > <module> > execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", > line 353, in execute_from_command_line > utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", > line 345, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", > line 348, in run_from_argv > self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", > line 398, in execute > self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", > line 426, in check > include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", > line 75, in run_checks > new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", > line 13, in check_url_config > return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", > line 23, in check_resolver > for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", > line 33, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", > line 417, in url_patterns > patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File > "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", > line 33, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", > line 410, in urlconf_module > return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module > __import__(name) File "/home/nasser/majed/scirius/scirius/urls.py", line … -
Change loaded file Django
I'm trying to figure out Django. I had such a task: the user loads an xml file, and I have to process it and return certain data. I already have a desktop script for this using xlrd and openpyexel. The question is: how to immediately process the resulting file and immediately output the data to the user? forms.py from django import forms from .models import files class DocumentForm(forms.ModelForm): class Meta: model = files fields = ('File',) models.py from django.db import models class files(models.Model): File = models.FileField(upload_to='files', null=True,) views.py from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect from .forms import DocumentForm def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('portfolio:index') else: form = DocumentForm() return render(request, 'templates/upload/upload.html', { 'form': form }) upload.html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'portfolio:index' %}">Return to home</a></p> {% endblock %} -
Django UpdateView allow only if object fields meet certain conditions
I want that an Invoice may only be changed if it falls between certain dates; these two dates are stored in the DB and indicate the currently open month (to prevent users from changing old invoices). Where would be the best place to enforce this restriction in my InvoiceUpdateView? A simple solution: add form validation (method InvoiceForm.clean_date()). That works, but ideally, I want the InvoiceUpdateView to not even show the form if the Invoice date is outside of the established range, it should just redirect back to the InvoiceDetailView. The following code works, but it calls .get_object() twice: I have to call it once to get the objects date, and later this method is called again in the parents .get() or .post(). class Invoice(models.Model): date = models.DateField() ... more fields ... class InvoiceUpdateView(PermissionRequiredMixin, UpdateView): permission_required = ... template_name = ... model = Invoice fields = ... def can_be_modified(self): # fetch from DB start_date = ... end_date = ... if start_date <= self.object.date <= end_date: return True return False def get(self, request, *args, **kwargs): self.object = self.get_object() if not self.can_be_modified(): return redirect('invoice-detail') return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() if not self.can_be_modified(): return redirect('invoice-detail') return super().post(request, … -
Twilio: Create two outgoing calls and join the conference using Python
I am trying to create a conferencing app with max 2 speakers using Twilio using Python/Django. However, in the docs I found out that you can do this by having inbound calls. but, my business model doesnt work like that. Is there a way for this to work like: My Twilio number calls number 1 My Twilio number calls number 2 Twilio brings two channels to a new conference I've tried this solution: Twilio how to make two outbound calls and join(conference) them using node js but it didn't help me much.. Here's my code: @csrf_exempt def conference(request): print("success") response = VoiceResponse() dial = Dial() dial.conference('Rooxm 1234') response.append(dial) print(response) return HttpResponse('') def call(number): client = Client(TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN) call = client.calls.create( url='https://<blahblah_removed_purposefully>.ngrok.io/conf/', to='+' + str(number), from_='<removed_my_twilio_num>' ) print(call.sid) def index(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = CallForm(request.POST) # check whether it's valid: if form.is_valid(): #print(dir(form.data.values)) call(form.cleaned_data['inline']) call(form.cleaned_data['outline']) return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = CallForm() return render(request, 'CallForm.html', {'form': form}) This gave me an error message during the call which is: "An application error has occurred. Goodbye" And … -
Auto-fill Django models
My model contains 3 classes. class Student(models.Model): name = models.CharField(...) class Subject(models.Model): subject = models.CharField(...) class Attendance(Student, Subject): att = model.IntegerField() Now, I want to create an attendance table for each Subject of each Student. Therefore I don't want to fill Subject and Student details for every subject and student again. Please tell me an optimal way of doing this so that at the admin panel I just want to add each subject and student only once. There may be multiple students studying a subject and there may also be multiple subjects for a student. (You may tell me another way of doing this instead of inheriting Student and Subject). -
Django Rest Framework function view post not working
So I am trying to serve a static file through a simple Django Rest framework function view. It gives me 200 code but doesn't download the file. Here is the code : @api_view(['POST']) def download_file(request): if request.method == 'POST': serializer = MySerializer(data=request.data) filename = 'file.xlsx' file_full_path = "src/{0}".format(filename) with open(file_full_path, 'rb') as f: file = f.read() response = HttpResponse(file, content_type="application/xls") response['Content-Disposition'] = "attachment; filename={0}".format(filename) response['Content-Length'] = os.path.getsize(file_full_path) return response return Response(status=status.HTTP_400_BAD_REQUEST) What am I doing wrong here? -
Django - How do I create a model that contains a collection of its own type?
One of the fields in a model I'm creating is for a list of instances of its own type. How do I do this in django? I couldn't find any documentation on how to do this.. This is something like what I am talking about, but doesn't work because the Component class isn't defined yet (and probably for other reasons too). class Component(models.Model): name = models.CharField() description = models.CharField() status_ok = models.BooleanField() subcomponents = models.ForeignKey(Component) A regular class that briefly demonstrates the concept: class Component: def __init__(self, name, description, status_ok, *subcomponents): self.name = name self.description = description self.status_ok = status_ok self.subcomponents = [] for subcomponent in subcomponents: if isinstance(subcomponent, Component): self.subcomponents.append(subcomponent) else: raise TypeError(subcomponent) -
Rename field name in django-filters for display
Is there any way to rename the field name while displaying on django app in django-filters? filters.py import django_filters as df from .models import Books class BooksListFilter(df.FilterSet): class Meta: model = Books fields = ['name'] my field name in database is 'name' but i want it to display as 'BookName' in Django app. How can i achieve this? -
Function is updating every item in my Database Django
I made this function to be able to be usable multiple times using different urlsConf and now every element in my Item model is updating with the same data. I made a few changes from when it last worked properly. Major change 1: changed my Items model from abstract table to multi-table-inheritance. Major change 2: I refactored the function to be usable multiple times(prior to this i was rewriting the same function on multiple places. the function in views.py: #=========================================================================== # # REUSABLE FUNTIONS TO GET CUANTITIES AND TOTALS # =========================================================================== # # Recibe un el nombre del link en formato x-incremento o x-decremento # y lo parte y guarda en una lista como incremento o decremento def split_s(get_link): l = get_link.split('-') strlist = [] for i in l: strlist.append(i) return strlist[1] # Actualiza el valor cantidad existente def calcular_nueva_cantidad(ce, up, strlist): if strlist == 'incremento': total = ce + up elif strlist == 'decremento': total = -(ce - up) else: print(F'========> {strlist} no es valido <=========') return total # Calcula el nuevo valor de cantidad existente def calcular_nuevo_total(nce, pu): return nce * pu # crea el formulario para la actualizacion de cantidad existente class updateForm(forms.Form): update = forms.IntegerField() def … -
What exactly is Django's FileField doing when one clicks the "Browse" button and selects a file? Can I replicate this behavior with Javascript?
When rendered, a Django form with a FileField will have a "Browse" button. When clicked, this allows a user to browse through their system, select a file, and hit OK, presumably giving some reference to the file's location, its contents, etc. This is before the "Submit" button is hit, so nothing is sent to the server—and there are no network requests made, thus there is no actual Python running anywhere. I assume Javascript is doing something because the name of the file pops up, and, somewhere, a reference to the file is stored (and sent to the server when the user clicks "Submit"). The FileField is populated somehow, but I'm not sure how. What exactly is going on here? I ask because I'd like to replicate this behavior with some AJAX/Javascript alterations. My intended process is this: User makes recording (I use WebAudioTrack) User clicks "Save," this sends a Blob from the AudioBuffer to some view via AJAX That blob is processed into a WAV file and saved as a temporary file (or something like this). Via some other script, that file is used to populate the form's FileField as if the user had clicked "Browse" and selected a file …