Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: catch RequestDataTooBig exception
Is there a way to catch RequestDataTooBig in Django, break execution and return custom error? Where should I do it properly? I have a textarea, and user can type as much text as he wants, then he press send button and django fails with RequestDataTooBig exception (I test 5 MB of text). django.core.exceptions.RequestDataTooBig: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. I do not want to disable this setting, I want to catch this exception and return JSON with error. When I try to catch it in my view, like this: @require_http_methods([ "POST"]) def some_view(request): try: # some logic return JsonResponse({'key':'val'}) except RequestDataTooBig: return JsonResponse({'error':'too_big_data'}) I get this error repeatedly - there must be chunks. django.core.exceptions.RequestDataTooBig: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. During handling of the above exception, another exception occurred: Traceback (most recent call last): ... django.core.exceptions.RequestDataTooBig: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. I suspect that I should catch it somewhere earlier - but have no idea where. I use python3.4 and django 1.10.5 -
MismatchSenderId on Django-firebase cloud messaging
I would like to implement Django-fcm when I try to test it, I was able to install Django fcm everything went successfully here is the error that appears MismatchSenderId. Here are some illustration screenshots : The error on postman The headers on postaman Help me solve this problem? -
correct way for loading dynamically all imgs from server using javascript and django
I need to dynamically load all images in a given directory from the server using javascript. I don't know in advance the number of files in the directory, neither their names. What is the correct way for doing this. Should I first send a request with ajax to get their names ? or is there another way. By the way, I'm using Django, and the images are in my static directory, though I don't think this information makes a difference. -
How to iterate over queryobject in django?
I want to iterate over Query-object to process and send response accordingly. This is working JavaScript part var msg = $.ajax({type: "GET", url: "jsonview/", async: false}).responseText; document.write(msg); This is working django views.py from django.http import JsonResponse def jsonview(request): return JsonResponse({"foo":"bar", "spam" : "no"}) I get the result {"foo": "bar", "spam": "no"} but I want to do like this (Don't Ask why). var msg = $.ajax({ type: "GET", url: "jsonview/", data:{["foo","spam"]}, async: false }).responseText; document.write(msg); def jsonview(request): spam_dict = {"foo":"bar", "spam" : "no"} new_dict = {} for item in request.GET.get('data'): new_dict[item] = spam_dict[item] return JsonResponse(new_dict) desired -> {"foo":"bar", "spam" : "no"} I tried various methods like for item in request.GET: for item in request.GET.get('data') etc. -
Cursor to QuerySet
I have written the following operator, to return all documents where a value is < 100. class Tester(Operator): op = "test" def apply(self, queryset, field, value, negate=False): standard = MetaboliteFull.objects(accurate_mass__lt=100) m = MetaboliteFull._get_collection().find({"accurate_mass" : {"$lt" : 100}}) print "Standard", standard, type(standard) print "M:", m, type(m) return standard When I return the "standard" object, all of the documents are returned - as expected. However, when I return m (the cursor object), nothing is returned (the data array is empty). I've checked the length of standard against the count of m and they are equal. Upon further inspection it looks like I need to convert the pymongo Cursor object to a mongoengine QuerySet object. How can I achieve this? Regards, Keiron. -
ModelForm and Model validation playing together
I have the following Model : class Advertisement(models.Model): slug = models.UUIDField(default=uuid4, blank=True, editable=False) advertiser = models.ForeignKey(Advertiser) position = models.SmallIntegerField(choices=POSITION_CHOICES) share_type = models.CharField(max_length=80) country = CountryField(countries=MyCountries, default='DE') postal_code = models.CharField(max_length=8, null=True, blank=True) date_from = models.DateField() date_to = models.DateField() Based on Advertiser, position, type country and postal code this stores adverisements with range date_from and date_to. advertiser, position, share_type, country and postal_code are coming from the request and are fetched in class CreateAdvertisment(LoginRequiredMixin, CreateView): # Some usefull stuff def dispatch(self, request, *args, **kwargs): self.advertiser = Advertiser.objects.get(user=self.request.user) self.share_type = self.kwargs.get('share_type', None) self.country = self.kwargs.get('country', None) self.postal_code = self.kwargs.get('postal_code', None) self.position = int(self.kwargs.get('position', None)) self.position_verbose = verbose_position(self.position) ret = super(CreateAdvertisment, self).dispatch(request, *args, **kwargs) return ret Without any validation for checking date_from, date_to. I can simply do def form_valid(self, form): form.instance.advertiser = self.advertiser form.instance.share_type = self.share_type form.instance.country = self.country form.instance.postal_code = self.postal_code form.instance.position = self.position ret = super(CreateAdvertisment, self).form_valid(form) return ret and I am done. Unfortunatly I cannot do this as I do have to check for valid time Frames for the Advertisment to avoid Double Bookings of the same time. I do this in the model with the following : def clean(self): ret = super(Advertisement, self).clean() print ("country [%s] position [%s] share_type [%s] postal_code … -
Django: database 'postgres1' does not exist but it does actually
python manage.py migrate: django.db.utils.OperationalError: FATAL: database "postgres1" does not exist But I actually created the role and the database and granted, end everything is correct. ok, then checking createdb postgres1 createdb: database creation failed: ERROR: database "postgres1" already exists how should I understand that? Default postgres postgres configuration works, but no one of created databases work. -
Migration issues in python django?
i have MySQL db in backed but when i change any model i does not reflect in backed python manage.py makemigration app_name python manage.py migrate but it show no migrations applied does mysql does nor support migrations my model class blog(models.Model): name = models.CharField(max_length=10) -
error with queryset and TypeError: must be str, not int but it's realy integer, how to fix this?
I need to add, the data received from the query, but he writes that the error field types do not match, there must be str () though this number! It turns out that the number of products is working, but the price is not, it just adds, as if the line to the line is about 20 digits! new_product.product_allprice += int(product_allprice) TypeError: must be str, not int this is my views.py def basket_adding(request): return_dict = {} session_key = request.session.session_key data = request.POST product_id = data.get('product_id') quantity = data.get('product_quantity') product_name = data.get('product_name') product_price = data.get('product_price') product_allprice = data.get('product_allprice') product_newcount = data.get('product_newcount') print(data) new_product, created = ProducInBasket.objects.get_or_create(session_key=session_key, product_id=product_id, defaults={"product_price":product_price, "product_name":product_name, "product_allprice":product_allprice, "product_newcount":product_newcount, "quantity":quantity}) if not created: new_product.product_allprice += int(product_allprice) new_product.quantity += int(quantity) new_product.product_newcount += int(1) new_product.save(force_update=True) products_total_number = ProducInBasket.objects.filter(session_key=session_key, is_active=True).count() return_dict["products_total_number"] = products_total_number print(return_dict) return JsonResponse(return_dict) this is my models.py lass ProducInBasket(models.Model): session_key = models.CharField(max_length=128, default=None) order = models.ForeignKey(Order, blank=True, null=True, default=None) product = models.ForeignKey(Product, blank=True, null=True, default=None) quantity = models.PositiveIntegerField(default=1) product_name = models.CharField(max_length=60, default=None) product_price = models.DecimalField(max_digits=19, decimal_places=2, default=None) product_allprice = models.DecimalField(max_digits=19, decimal_places=2, default=None) product_newcount = models.PositiveIntegerField(default=1) is_active = models.BooleanField(default=True) publish = models.DateField(auto_now=False, auto_now_add=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return "{0}:|:{1}".format(self.product_name,self.product_allprice) class Meta: ordering = ["-timestamp"] verbose_name = 'Product in … -
Django conditional view processing decorator adds stale Etag
I have been trying to use the django conditional view processing feature. Basically I want to deny update operations on an entity if it has since been modified by another user, and that seems to work well with the @condition decorator provided by django. However there is one issue which I noticed while testing it and later I checked in the django sources and I found what I think could be a bug, but just wanted to confirm here first before submitting a bug report to Django and a fix. The decorator is called when a new request comes in, it first calculates the etag and last_modified timestamp based on the functions passed in to the decorator, then it passes control over to the get_conditional_response() function. Here the etag and last_modified verification would be performed and if they dont match to whats provided in the request, the request will be denied. so far so good. If the checks pass, the request is allowed and the view is called to process the request and generate the response. While processing the request, if it was an unsafe method e.g. PUT or PATCH, it would update the entity, which would most likely change … -
django-twitter-api error: No module named utils
I am working on an application that would take a tweet from user and then as a result, it will tell the sentiment of that tweet. For this, i installed django-twitter-api. It installed correctly but when i do: from twitter_api.utils import api it gives me: Traceback (most recent call last): File "(stdin)", line 1, in (module) Import Error: No module named utils. I followed all the instructions from https://github.com/ramusus/django-twitter-api and made the required changes to my .settings.py file in my django project folder. Any help? -
UpdateAPIView in django rest framework without providing lookup_field and something wrong with the update api view
Traditionally , when using UpdateAPIView in django rest framework, we need to provide a lookup_field or lookup_url_kwarg(default is pk). This means I need to provide <pk> in the url, which I do not intend to do. So I overwrite the get_object() method the get the specific object, and it works. But I meet another problem: In the api, it allows PUT and PATCH of HTTP, but there is something wrong with the HTML form(say Raw data as well). It's all blank like this: { "description": "", "phone_number": "", "picture": null } It is supposed to look like this: { "description": "something already here", "phone_number": "123456789", "picture": null } So any idea how to fix it? -
A multiple choice field in a form is throwing exception on resetting database
I'm running into a strange issue when resetting my database. A multiple choice field in a form is throwing exception Unhandled exception in thread started by .wrapper at 0x7f59df160510> Traceback (most recent call last): File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: app1_semester The above exception was the direct cause of the following exception: Traceback (most recent call last): ...... File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/urls.py", line 3, in from . import views File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/views.py", line 10, in from . import models, forms File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/forms.py", line 11, in class AddAssignmentForm(forms.Form): File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/forms.py", line 14, in AddAssignmentForm queryset=models.AssignmentType.get_assignment_types(), File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/models.py", line 180, in get_assignment_types return AssignmentType.objects.filter(semester=Semester.get_current_semester()) File "/home/abdullah/PycharmProjects/langs-dept/project1/app1/models.py", line 157, in get_current_semester return semester.first() if semester else None File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 260, in __bool__ self._fetch_all() File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql() File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/abdullah/PycharmVirtualEnvs/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line … -
How to implement django-markdown-deux in Django app's list view?
I have done: pip install django-markdown-deux added markdown_deux in INSTALLED_APPS of settings.py and then added the filter markdown in app_detail.html {{instance.content | markdown}} Its working. But how to implement it in my app_list.html within: <p>{{obj.content|linebreaks|truncatechars:120}}</p> Please guide. Thank You -
Return all of users posts and favourites? Django
I'm creating a summary page of all of the posts the user has liked and all of the posts which the user has created. I have two models in my db: Aircraft & Airline. The user can upload posts to either model that they prefer. I'm just slightly clueless on how to retrieve their posts? Aircraft Model class Aircraft(AircraftModelBase): manufacturer = SortableForeignKey(Manufacturer) aircraft_type = SortableForeignKey(AircraftType) body = SortableForeignKey(Body) engines = models.PositiveSmallIntegerField(default=1) Airline Model class Airline(AirlineModelBase): fleet_size = models.PositiveSmallIntegerField() alliance = models.CharField(max_length=100, null=True) average_fleet_age = models.PositiveSmallIntegerField() In my Accounts app I've made a model of the following: class FavoritedAircraft(models.Model): user = models.ForeignKey(User) aircraft = models.ForeignKey(Aircraft) def __str__(self): return self.aircraft.name class FavoritedAirline(models.Model): user = models.ForeignKey(User) airline = models.ForeignKey(Aircraft) def __str__(self): return self.airline.name How do I essentially return the users favourite posts and if the user has uploaded anything, those posts as well? Thanks for any help! -
ValidationError value must be an integer when dynamically adding forms to formset
I'm using jquery to dynamically add forms to an inline formset in my django view. I'm using dynamic-formset.js (https://djangosnippets.org/snippets/1389/). When I use formset.is_valid() in my view, if I have dynamically added any forms to the page I get the following error: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/ryoung/Documents/Database/prodman/tande/views.py", line 352, in week if time_formset.is_valid(): File "/Library/Python/2.7/site-packages/django/forms/formsets.py", line 316, in is_valid self.errors File "/Library/Python/2.7/site-packages/django/forms/formsets.py", line 290, in errors self.full_clean() File "/Library/Python/2.7/site-packages/django/forms/formsets.py", line 338, in full_clean form = self.forms[i] File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/forms/formsets.py", line 144, in forms for i in range(self.total_form_count())] File "/Library/Python/2.7/site-packages/django/forms/models.py", line 881, in _construct_form form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) File "/Library/Python/2.7/site-packages/django/forms/models.py", line 590, in _construct_form pk = to_python(pk) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 960, in to_python params={'value': value}, ValidationError: [u"'' value must be an integer."] But it works fine if I edit existing/add using the form generated on the page automatically with extra - TimeFormSet = inlineformset_factory(TimeSheet, Time, form=TimeForm, extra=1). What does this error mean?.... Models: class TimeSheet(models.Model): start_date = models.DateField() … -
AttributeError type object has no attribute
So I'm trying to open and print data from this JSON file using this code in my view: from django.shortcuts import render import json class OnlicarView(): import json from pprint import pprint with open('C:/Python34/Scripts/onlicar/mytest/onlicar/static/json/vehicles.json') as data_file: data = json.load(data_file) pprint(data) Here is my app url: from django.conf.urls import url from onlicar import views urlpatterns = [ url(r'^onlicar/$', views.OnlicarView.as_view(), name='onlicar_signup' ) ] Here is my root url: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^onlicar/', include('onlicar.urls')) I am having trouble with the app url. I am getting an error saying that there is an Attribute Error and I don't know how to fix it. Because I am getting the data from a JSON file there is nothing in my models at the moment. Am I meant to have something in the models? -
Django rest project dockerfile
I am absolutely new to docker. I have an existing Django Rest project whose structure looks like following: My requirements.txt: django==1.8.8 djangorestframework markdown django-filter django-rest-auth django-cors-headers django-secure django-sslserver django-rest-auth[extras] Normally I create a virtual env > activate it > do pip install requirements.txt and additionally I need easy_install mysql-python to get started. I want to dockerize this project. Can someone help me build a simple docker file this project? -
is there any way to authentication via face in django
I want to develop a website in which the authentication will be done through face recognition. I'd search alot through OpenCV and Python it is possible but this is not working with browser, Is there any way to recognizes and authenticate the face through browser with Django. Please suggest. -
django rest framework: Get url parameter value in a model property
I have a Product model and one propery in it is "my_test_fn". This is called from my serializer. My requirement is, I want to do some calculations based on the filter passing through the url. How can I get the url parameter values in a model property? models.py class Product(AbstractProduct): product_id = models.UUIDField(default=uuid.uuid4, editable=False) ##more fields to go def my_test_fn(self): filters = self.request.query_params.get('filters', None) return {"key":"value"} serializer.py class MySerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id','product_id','sku', 'title', 'my_test_fn',) views.py class ProductDetailConfiguration(viewsets.ViewSet): lookup_field = 'product_id' def retrieve(self, request, product_id=None): queryset = Product.objects.filter(product_id=product_id)[0] serializer = ProductConfigurationCustomSerializer(queryset, context={'request': request}) return Response(serializer.data) API url: http://127.0.0.1:8000/api/v1/product-configuration/2FC2AA43-07F5-DCF4-9A74-C840FDD8280A?filters=5 -
Selenium with Chrome cannot hangs when trying to open two windows to the local server
I have a LiveServerTestCase that opens two browser windows and attempts to access the live_server_url on both. The second browser window's test is stuck at getting the URL, and all I see is data:, in the URL bar: self.browser = webdriver.Chrome() self.browser.get(self.live_server_url + "...") browser_1 = self.browser browser_2 = webdriver.Chrome() self.browser = browser_2 self.browser.get(self.live_server_url + "...") # stuck here self.assertTrue(True) Setup: Django 1.10.2/1.11 Chromedriver 2.29 Chrome 57.0.2987.133 (64-bit) Windows 10 with Bash on Windows This seems to work fine if I use webdriver.Firefox() (Firefox is v45.8.0esr) instead. -
django.db.utils.IntegrityError.duplicate key - creating initial migrations schema
Stuck on typical django issue. There was problem with migration, so I followed the answer from here. Django 1.8: Create initial migrations for existing schema I deleted from django_migrations in database, deleted migrations folder, but after python manage.py migrate --fake command some sort of bug happened and sync loaded eternally without any result till laptop became hot from the process and it was only possible to abort it. So I ran next command python manage.py makemigrations app, which worked perfectly, but after python manage.py migrate --fake-initial raised the same error, why I started all that operation. django.db.utils.IntegrityError: duplicate key value violates unique constraint "pg_type_typname_nsp_index" DETAIL: Key (typname, typnamespace)=(django_admin_log_id_seq, 2200) already exists. I supposed error was raised because previously I had issue with migration and aplied similar actions but without clearing data from postgres table. So I don't even understand how is that possible now after delete from django_migrations; It's Django 1.8. How to fix? Are there actually less typical problems with migrations in later versions, or that's all my fault not having proper understanding how it works? -
Django sum all related objects of a filtered QuerySet
What I would like to do in psuedo code is: def import_transaction_deposit_crypto(Importer): logger = get_nexchange_logger(__name__, True, True) existent_addresses = Address.objects.filter( currency__is_crypto=True, type=Address.DEPOSIT, currency__wallet__in=Importer.RELATED_NODES ).tx_to_set.count() tx_to is a related_field (reverse relation): class Address(BtcBase, SoftDeletableModel): address_to = models.ForeignKey('core.Address', related_name='txs_to') The idea is to count all 'already imported' transactions that belong to a specific RPC node (wallet), in order to feed it to the from parameter of the listtransactions RPC endpoint (generally speaking, for pagination purposes). -
django management command to run at midnight
I am new to management commands so I am making an easy example. my command selects all the cars that are in the database, I want the command to run automatically at midnight, How do I achieve this? class Command(NoArgsCommand): help = "Gets all the cars that are in the database" option_list = BaseCommand.option_list + ( make_option('--print', action = 'cars_true', dest = 'send', default = False, help = 'This option will print a list of cars .', ), ) def handle(self, *args, **options): cars = Car.objects.all() count = 0 for car in cars: count += 1 print str(count) +' '+ str(car) print count -
order a QuerySet
I have a view like this def profile (request): articles = Post.thing.all() newSet = set() def score(): for thing in articles: Val = some calculation... .... newSet.update([(thing,Val)]) score() context = { 'articles': articles.order_by('id'), 'newSet':newSet, } return render(request,'my_profile/my_profile.html',context) and the outcome is a Queryset which looks like this: set([(<thing: sfd>, 1), (<thing: quality>, 0), (<thing: hello>, -1), (<thing: hey>, 4), (<thing: test>, 0) im now trying to order the set by the given Values so its a list which starts with the highest Value, but when i do newSet.order_by/filter/split/join it does not work since 'set' object has no attribute join/filter/split. Can anybody give me a hint how to sort the querySet i could not find anything helpful on my own. I need this to work out in the view so it cannot/should not be done in the model. Thanks for any advise.