Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Video Reading Problem from Google Cloud Bucket
I am trying to deploy my website to Google Cloud. However, I have a problem with video processing. My website takes video from the user and then it shows that video or previously updated videos to the user. I can show the video on the template page. And I also need to process that video in the background. So, I should read the corresponding video with OpenCV. My code works locally. However, in Google Cloud part, the video is stored as a URL and OpenCV cannot read using URL as expected. According to the sources, the solution is to download the video into local file system: from google.cloud import storage def download_blob(bucket_name, source_blob_name, destination_file_name): """Downloads a blob from the bucket.""" # bucket_name = "your-bucket-name" # source_blob_name = "storage-object-name" # destination_file_name = "local/path/to/file" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) print( "Blob {} downloaded to {}.".format( source_blob_name, destination_file_name ) ) https://cloud.google.com/storage/docs/downloading-objects#code-samples I have two problems with this code: 1-First, I do not want to download the video into my local computer. I need to keep the video in the Google Cloud and I have to read the video with OpenCV from there. 2-When I try to run the … -
Django printing dynamic field in template
I annotate a queryset using a dynamicaly chosen field as follows: ver_por_choices = "Some field name" ventas_producto = ventas.values(ver_por_choices).annotate( uds_totales=F("uds_totales"), share=F("uds_totales"), ).order_by('-uds_totales') Then in the template I want to print the values as {% for venta in ventas_producto %} <div>{{ venta.uds_totales}}</div> <div>{{ venta.share}}</div> {% endfor %} How can I print the dynamic field? -
Connecting to local docker-compose container Windows 10
Very similar to this question, I cannot connect to my local docker-compose container from my browser (Firefox) on Windows 10 and have been troubleshooting for some time, but I cannot seem to find the issue. Here is my docker-compose.yml: version: "3" services: frontend: container_name: frontend build: ./frontend ports: - "3000:3000" working_dir: /home/node/app/ environment: DEVELOPMENT: "yes" stdin_open: true volumes: - ./frontend:/home/node/app/ command: bash -c "npm start & npm run build" my_app_django: container_name: my_app_django build: ./backend/ environment: SECRET_KEY: "... not included ..." command: ["./rundjango.sh"] volumes: - ./backend:/code - media_volume:/code/media - static_volume:/code/static expose: - "443" my_app_nginx: container_name: my_app_nginx image: nginx:1.17.2-alpine volumes: - ./nginx/nginx.dev.conf:/etc/nginx/conf.d/default.conf - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles - ./frontend:/home/app/frontend/ ports: - "80:80" depends_on: - my_app_django volumes: static_volume: media_volume: I can start the containers with docker-compose -f docker-compose.yml up -d and there are no errors when I check the logs with docker logs my_app_django or docker logs my_app_nginx. Additionally, doing docker ps shows all the containers running as they should. The odd part about this issue is that on Linux, everything runs without issue and I can find my app on localhost at port 80. The only thing I do differently when I am on Windows is that I run a dos2unix on my … -
Django migration fails to remove field
I'm using Python 3.8.4, Django 2.2.3, SQLite 3.32.3. When I run python manage.py makemigrations, Django creates a migration file containing the following operation, among others which execute successfully). migrations.RemoveField( model_name='essayrequirement', name='program', ), The program field's declaration before it is removed is as follows: program = models.ForeignKey(UndergraduateProgram, on_delete=models.CASCADE, related_name="essay_set", null=True, blank=True) However, when I try to run the migration (python manage.py migrate), I get the error django.core.exceptions.FieldDoesNotExist: NewEssayRequirement has no field named 'program'. (It seems NewEssayRequirement is a temporary table created in the course of applying the migration, which should replace the EssayRequirement table before the migration is complete.) Poking around in the SQLite database itself before applying the migration confirms that the program field did in fact exist -- the column for it exists. In addition, I've tried removing this operation from the migration, and of course the next call to makemigrations brings it back. The same error occurs when migrateing in this case. Interestingly enough, there was another field called non_undergrad_program on the same model, differing only in where the ForeignKey points to. The migration in question also removes this field, but for some reason does so successfully: migrations.RemoveField( model_name='essayrequirement', name='non_undergrad_program', ), I've been stuck on this issue for … -
Group list of dicts by value, then group some nested dicts
I've got data like this: plans = [ {'code':1, 'name':'Station1', 'plan_type':2, 'layer':1, 'hour':1, 'val':23.34} {'code':1, 'name':'Station1', 'plan_type':2, 'layer':1, 'hour':2, 'val':33.34} {'code':2, 'name':'Station2', 'plan_type':2, 'layer':1, 'hour':1, 'val':23.34} {'code':2, 'name':'Station2', 'plan_type':2, 'layer':1, 'hour':1, 'val':23.34} .... {'code':2, 'name':'Station2', 'plan_type':2, 'layer':1, 'hour':1, 'val':23.34} ] It describes production plans. What I'm trying to get to display it on Django template is { <code>:{'name':<name>, <plan_type>:{<hour>:{'layer':<layer>,'val':<val>} ... } } } Which means group data by code, set group a name, then group by plan type, and for each plan use hours as keys to discribe layers and values in the layers. I tried list comprehension a = { plan['code']:{ 'name':plan['name'], p['plan_type']:None for p in plans if p['code'] == plans['code'] } for plan in plans } Can't get past this. There's syntax error. I can either get codes for plan types as keys for nested dict or set 'name' value. There are solution with defaultdict and itertools, but I have yet to figure out how to apply them. This works, but isn't exactly I try to achieve: a = { plan['code']:{ 'name':plan['name'], 'plan':{p['plan_type']:None} for p in plans if p['code'] == plans['code'] } for plan in plans } -
Django make dropdown options different, based off of another field value
I have a quick question in regards to a dropdown selection, on account signup. I have 2 fields, an Acccount type, and Business type. Account type is a dropdown with 2 options, "Vendor" and "Venue". Business type is a dropdown that has many options. I only want the dropdown selections accessible only, if "Vendor" is selected in the Account type dropdown. Is this something I can handle in the template, with an if else statement? I have a small snippet for reference. <div class="form-group"> <label for="account_type">Account Type<span>*</span></label> <div class="select-panel required"> <select required class="selectpicker" name="account" id="multi-category" title="Select a category"> <option>Vendor</option> <option>Venue</option> </select> <span id="span_account_type" class="error-msg"></span> </div> <!--<input type="text" name="business_type" class="form-control required" id="business_type" placeholder="Business Type" value="{{business}}" maxlength="20">--> {% if account_error %} <span class="error-msg"> {{account_error}} </span> {% endif %} </div> <div class="form-group"> <label for="business_type">Business Type<span>*</span></label> <div class="select-panel required"> <select class="selectpicker" name="business" multiple="multiple" id="multi-category" title="Select a category"> {% for business in business_types %} <option value="{{ business.id }}">{{ business.name }}</option> {% endfor %} {% endif %} </div> I tried adding something like this but no luck. {% if account == 'Venue' %} <option>-----</option> {% else %} {% for business in business_types %} <option value="{{ business.id }}">{{ business.name }}</option> {% endfor %} {% endif %} -
Django: Running different functions in ListView based on (multiple) button(s) clicked in template
I've just begun learning Django, so please do be easy on me! I will update the code and everything as per requests. I'm currently working on a system where students can join groups called Societies. Societies have leaders and regular members, which has been programmed with the use of "through" to build an intermediary model between Society and User, called SocietyMembership. I am building an admin page, designed specifically for leaders of specific societies, where leaders can promote general members, demote, and even kick them from the society. I have designed my template in a way where for every person in the society, it shows a Promote/Demote button (based on their current rank) and a Kick button. My goal is to run specific functions defined in my Society class when each of these buttons are pressed, without creating entirely new views to confirm promotion, demotion or removal of members. Is there a way that I can define my post() method in a way which allows me to do so, so that I can edit my database appropriately using POST requests? Below I will paste the code that I have developed so far, and any feedback is welcome! class SocietyMembership(models.Model): member … -
Excel File as Serializer Response in Django Rest Framwork
I am using ModelViewSet class to upload a of csv file, do some processing on it and save the output as an excel file in local directory. Now I want to send this excel file back as response for the same request. However I am not able to send back the excel file as response correctly. serializer.py class InputSerializer(serializers.ModelSerializer): class Meta: model = CsvUpload fields = ('datafile','created', 'owner', 'filename') read_only_fields = ('datafile','created', 'owner', 'filename') class OutputSerializer(serializers.Serializer): excelfile = serializers.FileField() views.py ... from .analyzers import MainAnalyser from xlrd import open_workbook class FileView(ModelViewSet): serializer_class = OutputSerializer parser_classes = (MultiPartParser, FormParser,) queryset = CsvUpload.objects.all() def create(self, request, *args, **kwargs): file_serializer = InputSerializer(data=self.request.data) file_serializer.is_valid(raise_exception=True) file_serializer.save() # Call Analyzer functions analyzer = MainAnalyzer(self.request.get('datafile')) analyzed_xls = analyzer.analyze_files() # returns path to the saved excel file # Send back response rb = open_workbook(analyzed_xls) fileobj = DjangoFile(rb, name='report.xlsx') output_serializer = OutputSerializer({'excelfile':fileobj}) return Response(output_serializer.data) Most of the approaches I found online used HTTPResponse, but none with ModelViewSet Response. The response with above code is get is {"excelfile":null} -
Django. Using variable in a Queryset
I have a query variable3 = "Field3" variable_gte = "flowrate__gte" x = mytable.objects.filter(Q((variable_gte, variable2))).order_by(variable3)[0:5] z = x[0].Field3 How can I call this last value z using variable3, something similar to z = x[0].variable3 If it is impossible, I will need to use if/else condition: if variable3 = "Field3": z = x[0].Field3 else: .... Thank you. -
Python Django save one file for multiple datasets mobile
I have the following method to save a file to a database: files = request.FILES['files'] user1 = Model( file = files ) user1.save() user2 = Model( file = files ) user2.save() When I submit the form in desktop it executes without problems, but if I do it in mobile I get the following error message: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmppwj89ru2.upload.jpg' The error marks the line where user2.save() is executed, my guess is that the temporary file gets deleted once it saves the first dataset, the input field has capture enabled. Is there a way to keep the request.FILES['files'] content to be persistent for multiple datasets? As I said, this error only comes out while submitting the form in mobile, in desktop it works as intended. -
How to add headers to Django test requests?
how to use headers with django test requests? I have requests like this: requests.get(url=MY_URL, headers={"key": MY_KEY}) requests.post(url=MY_URL, json=MY_DATA, headers={"key": MY_KEY}) and it's working. Right now I'm writing tests for some module and I have problem with key varialbe, because I've tried: self.client.get(MY_URL, **{"key": MY_KEY}) self.client.get(MY_URL, headers={"key": MY_KEY}) self.client.post(MY_URL, MY_DATA, **{"key": MY_KEY}) self.client.post(MY_URL, MY_DATA, headers={"key": MY_KEY}) and all this requests return response 400. My guess is that there is something wrong with header. Do you know how to write this correctly? -
unrecognized token: "@" in Django
I am trying to make a search through multiple fields in one model but I get this error all the time: unrecognized token: "@" However I think it is a database issue I couldn't find a solution for it. I am posting my views.py and the traceback and would be very happy if someone could take a look. views.py from django.shortcuts import render from django.views.generic import ListView from django.contrib.auth.models import User from django.contrib.postgres.search import SearchVector class SearchView(ListView): model=User template_name='search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = User.objects.annotate(search=SearchVector('username','last_name'),).filter(search=query) return object_list Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=ekrem Django Version: 3.0.8 Python Version: 3.8.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'account', 'dictionary', 'search'] Installed 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'] Template error: In template C:\Users\ekrem\Documents\Django\project\beehive\templates\base.html, error at line 5 unrecognized token: "@" 1 : <!DOCTYPE html> 2 : {%load static%} 3 : <html lang="en" dir="ltr"> 4 : <head> 5 : <link rel ="stylesheet" href="https://s tackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> 6 : <link rel="stylesheet" href="{% static "css/elegant.css" %}"> 7 : <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> 8 : <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> 9 : <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> 10 : <meta charset="utf-8"> 11 : <title></title> 12 : </head> 13 : <body> … -
Django Model Form responds 200, but fails
I have a Django ModelForm as below: class MeasurementForm(ModelForm): class Meta: model = Measurement fields = ['weight', 'height', 'back_length', 'side_length', 'girth', 'food_consumption', 'measurement_type'] I use the form in a create_measurement view as below: def create_measurement(request, pup_id): pup = Pup.objects.get(id=pup_id) if request.method == 'POST': form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measured_pup = pup measurement.save() return redirect('/pup/{{ pup.id }}') else: form = MeasurementForm() return render(request, 'create_measurement.html', {'form': form, 'pup_id': pup.id}) This goes with the html: <form action="/{{ pup_id }}/create-measurement/" method="POST"> {% csrf_token %} {% load widget_tweaks %} <small class="text-danger">{{ form.non_field_errors }}</small> <div class="row"> <div class="form-group col-md-6"> <small class="text-danger">{{ form.weight.errors }}</small> <label for="{{ form.weight.id_for_label }}">Weight:</label> {{ form.weight|add_class:"form-control" }} </div> <div class="form-group col-md-6"> <small class="text-danger">{{ form.height.errors }}</small> <label for="{{ form.height.id_for_label }}">Height:</label> {{ form.height|add_class:"form-control" }} </div> </div> <div class="row"> <div class="form-group col-md-6"> <small class="text-danger">{{ form.back_length.errors }}</small> <label for="{{ form.back_length.id_for_label }}">Back Length:</label> {{ form.back_length|add_class:"form-control" }} </div> <div class="form-group col-md-6"> <small class="text-danger">{{ form.side_length.errors }}</small> <label for="{{ form.side_length.id_for_label }}">Side Length:</label> {{ form.side_length|add_class:"form-control" }} </div> </div> <div class="row"> <div class="form-group col-md-6"> <small class="text-danger">{{ form.girth.errors }}</small> <label for="{{ form.girth.id_for_label }}">Girth:</label> {{ form.girth|add_class:"form-control" }} </div> <div class="form-group col-md-6"> <small class="text-danger">{{ form.measurement_type.errors }}</small> <label for="{{ form.measurement_type.id_for_label }}">Measurement Type:</label> {{ form.measurement_type|add_class:"form-control" }} </div> </div> <button type="submit" class="btn btn-primary">Add Measurement</button> </form> When … -
Django/Python - where to define a global immutable dictionary
Using Python with a Django framework, I need to define a dictionary of tuples. These need to be global and referenced across multiple python files within the application. They will be global across all the user threads and completely immutable ie. constants. These values will be displayed on the pages and printed in reports. I want to know where is the best place to define these dictionaries, eg. in the views.py file? Please let me know what is the best practice. Thanks so much! -
How to programmatically create django-imagekit based content instances?
I am attempting to create default thumbnails for a learning app by using django-imagekit. I'm using Python 3.7.4 and django 3.0.4. I want to create a script to pre-load content, but the ProcessedImageField in my instance is empty after I pass it a django ContentFile. How can I add a model instance from the shell and populate a ProcessedImageField? Here is my models.py: from imagekit.models import ProcessedImageField from imagekit.processors.resize import SmartResize class MediaThumbnail(models.Model): """ An image that is used to visually represent and distinguish media in the site. Implemented via django-imagekit: https://django-imagekit.readthedocs.io/en/latest/ Attributes: thumbnail: An image that uses imagekit processor to resize to a standard size. """ thumbnail = ProcessedImageField(upload_to='resource_thumbnails', processors=[SmartResize(185, 100)], format='JPEG', options={'quality': 80} ) Here is an example shell session: In [1]: from io import BytesIO In [2]: from PIL import Image as PILImage In [3]: path = "eduhwy/media/default_thumbnails/" In [4]: img = PILImage.open(path + "abc.jpg") In [5]: img Out[5]: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=910x607 at 0x7F49073CAC50> In [6]: rawfile = BytesIO() In [7]: img.save(rawfile, format='jpeg') In [8]: from django.core.files.base import ContentFile In [9]: django_file = ContentFile(rawfile.getvalue()) In [10]: mt = MediaThumbnail.objects.create(thumbnail=django_file) In [11]: mt Out[11]: <MediaThumbnail: MediaThumbnail object (724)> In [12]: mt.thumbnail Out[12]: <ProcessedImageFieldFile: None> As you can … -
Django APITestCase tests fail
i'm trying to test my project on Django & DRM but without success. I created serializers for Django's default User and my model called Agent. The logic is that everytime an Agent is created it should be linked with Django's user default attributes plus my model's attributes, a user_id connected to the default User instance, and a integer field for the phone number. In serializers i overrided create() and update() default methods, and this part is working like it should serializer.py class UserSerializer(ModelSerializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] class AgentSerializer(ModelSerializer): user = UserSerializer() class Meta: model = Agent fields = ['user', 'phone', 'company'] def create(self, validated_data): user = validated_data.pop('user') new_user = User.objects.create(**user) agent = Agent.objects.create(user=new_user, company=validated_data['company'], phone=validated_data['phone']) return agent def update(self, instance, validated_data): validated_user = validated_data.pop('user') user = instance.user user.username = validated_user['username'] user.first_name = validated_user['first_name'] user.last_name = validated_user['last_name'] user.email = validated_user['email'] user.password = validated_user['password'] user.save() validated_data['user'] = User.objects.get(id=user.id) return super(AgentSerializer, self).update(instance, validated_data) In views i went with generic views to keep the code simple, so i created two views, a ListCreateAPIView to get and post, and RetrieveUpdateDestroyAPIView for get, put/patch and delete. views.py class AgentListCreateView(ListCreateAPIView): queryset = Agent.objects.all() serializer_class = AgentSerializer permission_classes = … -
Trying to make comments editable in django
I have a blog app and the comments can be added on the detail page of the blog, im having trouble implementing a way for users to edit comments they have already made. I have it so a url shows up on comments where only the person signed in can click the link to edit their comments on the post however im getting this error when I try to load the detail page now. Any help would be appreciated thank you Reverse for 'update_comment' with arguments '(None,)' not found. 1 pattern(s) tried: ['posts(?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/(?P<comment_id>[0-9]+)/update$'] models.py from django.db.models.signals import pre_save from Date.utils import unique_slug_generator from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.conf import settings class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='cleared') class Post(models.Model): STATUS_CHOICES = ( ('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),) title = models.CharField(max_length = 300) slug = models.SlugField(max_length = 300, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared') objects = models.Manager() cleared = PublishedManager() class Meta: ordering =('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = … -
How to do Students can login into their particular classroom in django?
How to do Students can login into their particular classroom in django? Example:- let assume that there are 30 students, 10 students login only in their classroom 1, another 10 student login only in their classroom 2 and remaining 10 are login only in their classroom 3 -
How to Create ManyToMany Through Model without Keys in Django?
I have 3 tables: Table A Table B Table C Table A has a foreign key to Table B. Table C has a foreign key to Table B. So B acts as an intermediary through table, but it does not have any foreign keys to A or C itself, so I cannot declare a ManyToManyField from A to C in the conventional way, but I would like to do so in order to use prefetch_related when grabbing C records from A. Is there a way to do this? -
Weird behavior during deployment of Django application in Apache
I am trying to deploy django application on Windows Apache server and observed below weird behavior. Step - 1: My "wsgi.py" file contains below code import sys import os from django.core.wsgi import get_wsgi_application # Add the app's directory to the PYTHONPATH sys.path.append('D:/Workspace/APortal') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'APortal.settings') application = get_wsgi_application() When i start Apache server with above wsgi file code, page gets stuck in loading (page keeps on loading for infinite time until i stop the request) and I can see below error in 'access.log' of Apache ::1 - - [28/Jul/2020:00:41:25 +0530] "-" 408 - Step - 2: Now in my 'wsgi.py' file, i will comment my below line and start the Apache server. #sys.path.append('D:/Workspace/APortal') From Apache 'error.log' i can see below message, which is valid. ModuleNotFoundError: No module named 'APortal'\r, referer: http://localhost:8080/execution/login Step -3: Now in my 'wsgi.py' file, i will just comment out below line which i have commented before server start, sys.path.append('D:/Workspace/APortal') Now, when i reload my page, i can access the application and i am able to successfully navigate through my web application. Step - 4: Now if i restart my Apache server, again i face same issue where i explained in Step-1 and i have to repeat Step-2 … -
Django DateField - how to setup model and form
How should I set-up the model and form to be able to enter the date to the form with different input formats and, at the same time, save to database the date in python's datetime format? I was trying to find an answer here and in Django documentation, but I didn't manage to find out, what is proper way of doing this. I have a DateField field in my model. Date is to be provided by user via form. I want that the form accepts several input formats, especially European-style, but save to database date in python's format. (For the moment, I'm trying to set-up just one format, when I finally understand how does it work, I want to enlarge the allowed input formats list.) My model: class Foo(models.Model): date = models.DateField(null=True) My form: class FooForm(forms.Form): date = forms.DateField(required=False, widget=forms.DateInput(format='%d/%m/%Y', attrs={'placeholder': 'yyyy-mm-dd'})) My settings DATE_INPUT_FORMATS = ['%d/%m/%Y'] Placeholder in the form is just for me to remember the format, in which Django accepts the date. All other format - included the formats specified in settings.py and form's widget, result in non-validation of the form. With the code like above, it seems that Django is doing the opposite of what I … -
Django URLs doesn't support to have any patters. How to solve this error
My main folder URL has the following code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('quotes.urls')), ] And my website folder has this code: from django.urls import path from . import views urlpatters = [ path('',views.home, name="home") ] This is the error I am getting: C:\stock\stocks\quotes\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... return check_resolver(resolver) File "C:\stock\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\stock\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\stock\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\stock\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'quotes.urls' from 'C:\stock\stocks\quotes\urls.py'>' does not appear to have any patterns in it. If yo u see valid patterns in the file then the issue is probably caused by a circular import. Please let me know what do I need to change -
Django Decorator For Try Except
I am wondering if there is some existing (or one I could write) decorator that does a try except on the function, and if it fails, returns a 404/403/500 (not sure which is supposed to be shown) page. Thanks! -
Django Twilio - Not all unsubscribers are being captured in my app - why?
I've implemented a function to capture unsubscribers. However, only some of the unsubscribers are captured by my app. For example I am getting multiple 21610 - Attempt to send to unsubscribed recipient for customers that have replied stop and were not captured in my app as unsubscribers. Here is the part of phone number sms webhook that checks if user wants to unsubscribe: if umessage_body == 'STOP' or umessage_body == 'STOPALL' or umessage_body == 'UNSUBSCRIBE' or umessage_body == 'CANCEL' or umessage_body == 'END' or umessage_body == 'QUIT': place_num = request.POST['To'] Unsubscriber.objects.update_or_create( unsubscriber_number = request.POST['From'], place = place ) resp = MessagingResponse() return HttpResponse(str(resp)) For context my app sends text messages to thousands of users at once, maybe it is something about my webhook being overwhelmed. Any idea what is causing this, and how to ensure all unsubscribers are being captured in my app. -
Sending upgrade progress from S3 Boto3 to Angular Frontend
I am using Django to upload files to AWS S3 using Boto3. I have been successful in doing this, but I wonder how I can get the AWS S3 upload progress, provided by Boto3 via a callback, sent over to the frontend. I am using the code similar to the following to upload using Boto3: s3.upload_file("filename.txt", AWS_BUCKET_NAME, "key", Callback=ProgressPercentage("filename.txt")) And in turn using the callback example provided by the Boto3 docs: import os import sys import threading class ProgressPercentage(object): def __init__(self, filename): self._filename = filename self._size = float(os.path.getsize(filename)) self._seen_so_far = 0 self._lock = threading.Lock() def __call__(self, bytes_amount): # To simplify, assume this is hooked up to a single filename with self._lock: self._seen_so_far += bytes_amount percentage = (self._seen_so_far / self._size) * 100 sys.stdout.write( "\r%s %s / %s (%.2f%%)" % ( self._filename, self._seen_so_far, self._size, percentage)) sys.stdout.flush() But instead of passing the output to sys.stdout.write I want to somehow get it over to the frontend (specifically, to an Angular client). Any ideas on how I do this? If I do print the output of the above callback I get the following in the Django console: filename.txt 262144 / 3457480.0 (7.58%) filename.txt 524288 / 3457480.0 (15.16%) filename.txt 786432 / 3457480.0 (22.75%) ... This output …