Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix the problem:"TypeError: filter() takes no keyword arguments",please help me
I have followed the official tutorial of Django to make a poll app, but I have gotten an error: File "C:\Users\oliver\Desktop\TPA Part 5\mysite\polls\views.py", line 17, in get_queryset return Question.objects,filter( TypeError: filter() takes no keyword arguments The code(The code is at mysite\polls\views.py and the required changing action is on part 5 of the tutorial): class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future) """ return Question.objects,filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] Could you please help me? The platform: Windows 10 ,Django version: 3.0.4 ,Python version: 3.8.2 ,The database is MySQL8.0 and the tutorial:Tutorial,my code files:Files -
How to get image data from Django form which returns False for is_valid()
How to save image in Django form that is not validated. I could able to save data of Charfield using title = form_name["title"].data Other data that are passed are getting saved but image is not getting saved. How to fix it. form = forms.FormName() if request.method == "POST": form_name = FormName(data = request.POST) title = form_name["title"].data thumbnail = form_name["thumbnail"].data content = form_name["content"].data tags = form_name["tags"].data instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user) instance.save() -
Django: Iterate queryset over list
I cannot iterate over Querysets. Below produce an error meanwhile if I would manually type: return chain(queryset.filter(company__contains=1, queryset.filter(company__contains=2) it works. How do I solve this?, I cannot find anything online. Key here I that I do not know the size of the list beforehand and cannot use the manual notation, such as 1 | 2 from itertools import chain class ProductListView(ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super(ProductListView, self).get_queryset() query = [] for g in [1,2]: query.append(queryset.filter(company__contains=g)) return chain(tuple(query)) -
Django is not rolling back with atomic transactions
I have the following models: class InventoryAction(CustomModel): action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción")) action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción")) action_object = GenericForeignKey('action_content_type', 'action_object_id') timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora")) class Meta: verbose_name = _("Acción de Inventario") verbose_name_plural = _("Acciones de Inventario") def __str__(self): return "{}-{}/{}/{}".format(self.id, self.action_content_type.model, self.action_object_id, self.timestamp) class InventoryActionProduct(CustomModel): inventory_action = models.ForeignKey(InventoryAction, on_delete=models.PROTECT, related_name='products', verbose_name=_("Acción de Inventario")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='actions', verbose_name=_("Producto")) amount = models.FloatField(verbose_name=_("Cantidad")) class Meta: verbose_name = _("Producto de Acción de Inventario") verbose_name_plural = _("Productos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.inventory_action.action_content_type.model, self.product.name, self.inventory_action.timestamp) class InventoryActionItem(CustomModel): inventory_action_product = models.ForeignKey(InventoryActionProduct, on_delete=models.PROTECT, related_name='items', verbose_name=_("Producto de Acción de Inventario")) product_item = models.ForeignKey(ProductItem, on_delete=models.PROTECT, related_name='invetory_action', verbose_name=_("Artículo")) class Meta: verbose_name = _("Artículo de Acción de Inventario") verbose_name_plural = _("Artícuos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}".format(self.id, self.inventory_action_product.product.name, self.product_item.serial_number) class InventoryInput(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén")) class Meta: verbose_name = _("Entrada de Inventario") verbose_name_plural = _("Entradas de Inventario") def __str__(self): return "{}-{}".format(self.id, self.repository) KARDEX_INPUT = 'INPUT' KARDEX_OUTPUT = 'OUTPUT' KARDEX_CHOICES = ( (KARDEX_INPUT, _("Entrada")), (KARDEX_OUTPUT, _("Salida")), ) class Kardex(CustomModel): type = models.CharField(max_length=6, choices=KARDEX_CHOICES, verbose_name=_("Tipo de Movimiento")) repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='kardex', verbose_name=_("Almacén")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='kardex', … -
Django Rest Framework filter - Select a valid choice
I encountered such an error when using django rest framework filter. I want to return 0, is it possible to fix this? # http://localhost:8000/api/v1/target/?project=TEST-00002 # RESPONSE 400 Bad Request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } Definitions and test cases are below. ## Definition class Project(models.Model): project_number = models.CharField(max_length=255, unique=True, null=False, blank=False) project_name = models.CharField(max_length=255, null=False, blank=False) class Target(models.Model): project = models.ForeignKey(Project, db_column='project_number', to_field='project_number', on_delete=models.CASCADE, null=False, default=None) target_name = models.CharField(max_length=255, null=False, default='') comment = models.TextField(default='', blank=True, null=False) class TargetViewSet(viewsets.ModelViewSet): queryset = Target.objects.all() serializer_class = TargetSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ['id', 'project'] class TargetSerializer(serializers.ModelSerializer): class Meta: model = Target fields = '__all__' read_only_fields = ('created_at', 'updated_at', 'delete_at') ## TEST DATA { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" }, { "id": 2, "project": "TEST-00001", "target_name": "mary" } ] } } ## TEST ## http://localhost:8000/api/v1/target/?project=TEST-00002 ## 400 bad request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } ## http://localhost:8000/api/v1/target/?project=TEST-00001 ## no problem { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" … -
Should I Use Relational Database OR Non-Relational Database For My Application
I am in the early stages of building a music/video streaming app similar to Tidal/Spotify but for a different niche of artists. I have a somewhat basic question: I am afraid I don't want to make the mistake of building a database that can't scale linearly later on. I have decided I am going to be using Google Cloud Platform. I want to use Google Spanner because it scales very well and is relational (which my data is going to be, I am assuming. Playlists, library, users, artists... can be schemed relationally unless I am not seeing something I should be seeing). Anyways, I see that Google Spanner is really expensive especially for new applications that don't need that scaling option that early on. So my question is should I go with Cloud SQL with Postgres and if whenever if ever this app grows to a significant number of users, then migrate to Google Spanner. Or should I go with a non-relational database like BigTable or Datastore/Firebase that will scale by itself later on and also isn't expensive at the beginning. What databases would you use if you were asked to build this app that is required to scale? I … -
Django models AttributeError: 'User' object has no attribute 'set_attributes_from_name'
I am trying to create a simple chat app with Django and am working on creating the models right now: class User(models.Model): uuid = models.CharField(max_length=10) name = models.CharField(max_length=20) tag = models.IntegerField() creation = models.DateTimeField() status = models.IntegerField(default=0) login = LoginInfo() class Room(models.Model): users = ArrayField(User()) With the above code, I get the following error: AttributeError: 'User' object has no attribute 'set_attributes_from_name' Am I using ArrayField wrong? Does the User class need an extra method called set_attributes_from_name? I'm using postgresql for the databse management. -
Learning Postress for my Django App on Heroku
my app is ready to go live but I tried to deploy on Heroku and their Postgress DB keeps old fields values. I migrated, tried to reset the Heroku DB but still I can see the reason from the error in my log but cannot get hold on it. I need an advice from your own experience. Should I learn Postgress and it will make my life easier or is there a better path ? I'm happy to go full postgres for few days but I want to be sure I dig in the right place. Tks so much for your POV. -
Django forms widget renderer
I am porting some code from Django 1.9 to 1.11. There is the following form: class FruitForm(FormFieldMixin, forms.Form): choices=( ("app", "Apple"), ("pea", "Pea, not Pear"), ), widget=forms.RadioSelect(renderer=CustomRadioFieldRenderer), ) this fails in 1.11 with: TypeError: __init__() got an unexpected keyword argument 'renderer' looking at the source code, RadioSelect in 1.9 inherits from RendererMixin which indeed accepts a renderer argument. RadioSelect in 1.11 inherits only from ChoiceWidget which in turn inherits from Widget. Widget's render accepts a renderer. This is in agreement with the Django release notes for 1.11. So the new way would be to pass a renderer when the Widget render is being called. There are some oblique guidelines here but I cannot imagine how one would use the Widget.render directly. I do not want to set a universal form renderer, just for this one class. In summary, how do I do that class, with a custom widget renderer in 1.11 where we do not have a renderer argument. Thank you. -
Apache web server static files for IP
I am trying to server static files via apache. Its working when I do localhost/static/index.html but when i try 192.0.0.1/static/index.html its not working. where i can specify that private ip for it to work in my lab.am using ubuntu, and trying to run django project. -
Django - WSGI script cannot be loaded as Python module
This is a well-known issue it seems but I have spent 8 hours trying to fix the issue without any success. I have been running a Django project with Apache2 on this VPS before, this issue occurred when I deployed new code and ran a sudo apt-get update. I now receive an Internal server error when trying to reach the website. I am desperate, does anyone have a suggestion of what could have happend? What I have installed on my VPS - sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 - sudo apt-get install mysql-server - sudo mysql_secure_installation - sudo apt install git - pip3 install virtualenv - pip3 install django - sudo apt-get install libmysqlclient-dev - pip3 install mysqlclient Error log [Fri Mar 06 22:47:29.96579 2020] mod_wsgi (pid=4877): Target WSGI script '/var/www/project/project/wsgi.py' cannot be loaded as Python module. [Fri Mar 06 22:47:29.965710 2020] mod_wsgi (pid=4877): Exception occurred processing WSGI script '/var/www/project/project/wsgi.py'. [Fri Mar 06 22:47:29.965712 2020] mod_wsgi (pid=16955): Target WSGI script '/var/www/project/project/wsgi.py' cannot be loaded as Python module. [Fri Mar 06 22:47:29.965917 2020] mod_wsgi (pid=16955): Exception occurred processing WSGI script '/var/www/project/project/wsgi.py'. [Fri Mar 06 22:47:29.967013 2020] Traceback (most recent call last): [Fri Mar 06 22:47:29.967585 2020] File "/var/www/project/project/wsgi.py", line 17, in … -
Python muiltithreading is mixing the data of different request in django
I am using python muiltithreading for achieving a task which is like 2 to 3 mins long ,i have made one api endpoint in django project. Here is my code-- Def myendpoint(request): Print(hello) Lis = [ args ] Obj = Model.objects.get(name = jax) T1 = MyThreadClass(lis, obj) T1.start() T1.deamon = True Return httpresponse(successful, status 200) Class MyThreadClass(Thread): Def __init__(self,lis,obj): Thread.__init__(self) Self.lis = lis Self.obj = obj Def run(self): For i in lis: Res =Func1(i) Obj.someattribute = res Obj.save() Def Func1(i): Some big codes Context =func2(args) Return context By this muiltithreading i can achieve the quick response from the django server on calling the endpoint function as the big task is thrown in another tread and execution of the endpoint thread is terminated on its return statement without keeping track of the spawned thread. This part works for me correctly if i hit the url once , but if i hit the url 2 times as soon as 1st execution starts then on 2nd request i can see my request on console. But i can get any response from it. And if i hit the same url from 2 different client at the same time , both the individual datas are … -
Django template time filter not rendering
I have a little issue with Django's template not really rendering the time format as I'd like it to, following the documentations here proved to be a bit troublesome as it didn't work. Original Code: <p>Obtained this item on {{date_variable|date:"M j, Y"}} at {{time_variable|time}}</p> Tried these two time filter formats as shown below which are given by the Django's documentation. {{time_variable|time}} {{time_variable|time:"TIME_FORMAT"}} They represent the same thing as stated by the documentations. I even went as far as to try different formats i.e. {{time_variable|time:"h:i A"}}, {{time_variable|time:"P"}} etc. but none of it rendered in the web application. One solution I miraculously found was by removing the time filter {{time_variable}} and it showed the time entered from the form except the AM/PM. However, I need to display the AM/PM, looking to try for other solutions. Django version used is 2.2.2. Note: I have tried other solutions that are on stackoverflow but it seemed none of them worked, I don't really know why either as the information is entered through Django's form template, not processed or changed. -
How to make Django Redis cache shared between clients and sessions
This is probably quite related to the way Django uses Redis cache. I installed the debug toolbar and I watched the number of SQL request vs the cached content. Note that I'm using a Kubernetes cluster. So, this is what I do: 1 - I visit a page, I see 40 SQL requests. 2 - I refresh it, I see 40 SQL requests. 3 - I refresh it again, I see 1 SQL request - the cache start working from the second refresh. 4 - At this step, the page should be stored in the redis cache. To test this, I open a new private window ans visit the same page: I see 40 SQL requests! The problem is here. If I'm able to see that the page was cached, why opening a private window doesn't use the same cache ? If cache is only related to the user session, what's the benefit ? Is there a way to create a shared cache between all users ? I use django_redis.cache.RedisCache as a backend with these options: "CLIENT_CLASS": "django_redis.client.DefaultClient", "PICKLE_VERSION": -1, # Use the latest protocol version "SOCKET_CONNECT_TIMEOUT": 5, # in seconds "SOCKET_TIMEOUT": 5, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": … -
How to embed a Django website in external iframe
I would like to embed my Django website in a specific external website (not any website). I read a lot of docs and I don't understand if I have to use django-csp or X_FRAME_OPTIONS (which seems depreciated), or both to be compatible with every navigators. I tried to install and setup django-csp but in that case all of the ressources are blocked. CSP_DEFAULT_SRC = ("'none'", 'https://example.com') CSP_STYLE_SRC = ("'self'" ) CSP_SCRIPT_SRC = ("'self'" ) CSP_IMG_SRC = ("'self'" ) CSP_FONT_SRC = ("'self'" ) Here is the configuration : Django + REST Framework + React Thanks a lot! -
Dynamically getting an attribute from an objet to call a function based on that attribute
I'm inspecting an object and looking for a ManyToMany field that's of model "Risk", and then after that I want to call the obj.somefieldname.add() method. This is what I have so far for field in [f for f in obj.__class__._meta.get_fields() if isinstance(f, models.ManyToManyField) and (f.related_model._meta.object_name == Risk._meta.object_name)]: print(obj[field.name].add(...)) I can get it to fetch the appropriate fieldname, but I have no idea how to call the add function on this. Normally if it wasn't a many to many field I could just setattr but I'm in a bit of a loss as to how to do this. Also is there a better way to do the discovery than my approach? -
allign logged in user to form
I created a simple app where you can create poll, after login and see your polls in view. The problem is that i can't allign logged in user to my object. It worked fine when i had separate forms to create question and choice, but i want to do dynamic form and have these two forms in one view. I came up with that: forms.py class CreateChoiceForm(forms.ModelForm): choice_0 = forms.CharField(required=True) choice_1 = forms.CharField(required=True) class Meta: model = Question fields = ['question_text'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choice = Choice.objects.filter( question=self.instance ) for i in range(len(choice) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choice[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def save(self, commit=True): question = self.instance question.question_text = self.cleaned_data['question_text'] question.choice_set.all().delete question.save() for i in range(2): choice = self.cleaned_data['choice_%i' % (i)] Choice.objects.create(question=question, choice_text=choice) def get_interest_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] but now i've got this error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/createPoll/ Django Version: 2.2.5 Python Version: 3.6.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'pollapp'] 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'] Traceback: File "C:\Users\MaineKomputere\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py" in _execute 84. return … -
Selenium error: no chrome binary at '/app/.apt/usr/bin/google-chrome' for deployment to Heroku via Django
I am getting an error with Selenium deployed to Heroku via Django: selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome'. I feel like I've followed the steps exactly of similar problems/solutions but I'm still getting the same error. Is there anything else I can try to fix the issue? I don't understand why Selenium fails to see the Chrome Binary. Selenium options, config vars and full traceback below Builpacks: https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver Heroku Config Variables: GOOGLE_CHROME_BINARY = "/app/.apt/usr/bin/google-chrome" CHROMEDRIVER_PATH = "/app/.chromedriver/bin/chromedriver" Selenium options: from decouple import config class WebDriver: def __init__(self): self.GOOGLE_CHROME_BINARY = config('GOOGLE_CHROME_BINARY') self.CHROMEDRIVER_PATH = config('CHROMEDRIVER_PATH') self.chrome_options = Options() self.chrome_options.add_argument("--disable-dev-shm-usage") self.chrome_options.add_argument('--no-sandbox') self.chrome_options.binary_location = self.GOOGLE_CHROME_BINARY self.chrome_options.add_argument("headless") self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, chrome_options=self.chrome_options) Traceback: File "/app/tcg/tcg_scraper.py", line 19, in __init__ self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, chrome_options=self.chrome_options) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__ desired_capabilities=desired_capabilities) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 151, in __init__ self.start_session(desired_capabilities, browser_profile) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 240, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute self.error_handler.check_response(response) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome' -
Group by and count foreign key
I have a data model where I store certain Events that happen. Each Event is linked to an EventType. The data model roughly looks like this: class EventType(models.Model): name = ... class Event(models.Model): date = ... event_type = models.ForeignKey(EventType) What I would like to know is how often each event time appeared. I tried it like this: Event.objects.values('event_type', count=Count('event_type')) But the result looks like this: <QuerySet [{'count': 1, 'event_type': 71}, {'count': 1, 'event_type': 2}, {'count': 1, 'event_type': 71}, {'count': 1, 'event_type': 71}, ... So the entries did not get grouped. How can I make it such that they are grouped? -
Django test with different database user
I want to keep my unit test database completely separate from other environments including using different user credentials. This is mostly to prevent anyone from unintentionally running unit tests against the development database and mangling the dev data or wiping it out entirely if the --keepdb option isn't specified. The code below detects the "test" in the sys args and this seems to work but is very clunky. If I'm missing a better way to do this please advise. I have separate settings files for each environment so this will only be on the development server where the unit tests are run automatically and won't end up on any production servers. Environment: Django 1.11 Python 3.4.x MariaDB # this works but is clunky import sys if 'test' in sys.argv: DATABASES = { # test db and user 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_db_test', 'USER': 'test_user', 'PASSWORD': 'secretpassword', 'HOST': 'the-db-host', 'PORT': '3306', 'TEST': { # redundant but explicit! 'NAME':'dev_db_test', }, } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_db', 'USER': 'dev_db_user', 'PASSWORD': 'dev_password', 'HOST': 'the-db-host', 'PORT': '3306', 'TEST': { 'NAME':'dev_db_test', # redundant but explicit! }, } } I'd like to do this but unfortunately Django doesn't look at … -
Django Add Q filters to query when related object exists, Conditional query
I am triying to query my product model like this: I have Product model that is related to an user My user can have a related Store, and its store can be unactive or no-visible So, my products can be sold by an user that has a store or an user that not has a store; what I want to do is to make query adding these extra parameters when "has_store" condition beign True like this. store_query = ({"seller__user_store__is_active": True, "seller__user_store__is_visible": True} if F("seller__user_store__isnull=False") else {}) And then add that query to my filtering sentence: Product.objects.filter(Q(is_new=True) & Q(is_active=True), **store_query) My product model also has is_new, and is_active and other parameters. So, expected behaviour is something like add Q(seller__user_store__is_visible=True) and Q(seller__user_store__is_active=True) if product seller has a related store I hope have been clear, thanks you a lot -
How to extract "label" and "help_text" data from Django Rest Framework serializer?
I have defined Item model in models.py exactly like below. class Item(models.Model): transaction_id = models.CharField(max_length=25, unique=True) order = models.ForeignKey(Order, on_delete=models.CASCADE) item_type = models.ForeignKey(ItemType, on_delete=models.SET_DEFAULT, default=1) title = models.CharField(max_length=200) description = models.TextField(null=True, max_length=3000) seller_user_id = models.IntegerField(null=True) buyer_user_id = models.IntegerField(null=True) listing_id = models.IntegerField(null=True) creation_tsz = models.DateTimeField() price = models.DecimalField(max_digits=9, decimal_places=2) shipping_cost = models.DecimalField(max_digits=9, decimal_places=2) quantity = models.IntegerField() currency_code = models.CharField(null=True, max_length=5) product_data = JSONField(null=True) personalization = models.TextField(max_length=1000, null=True) I have also defined my ItemSerializer with part below. class ItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) transaction_id = serializers.CharField(read_only=True, max_length=25) title = serializers.CharField(max_length=200) description = serializers.CharField(allow_null=True, max_length=3000) seller_user_id = serializers.IntegerField(allow_null=True, validators=[validate_positive]) buyer_user_id = serializers.IntegerField(allow_null=True, validators=[validate_positive]) listing_id = serializers.IntegerField(allow_null=True, validators=[validate_positive]) creation_tsz = serializers.DateTimeField() price = serializers.DecimalField(label='Price', max_digits=9, decimal_places=2, validators=[validate_positive]) shipping_cost = serializers.DecimalField(max_digits=9, decimal_places=2, validators=[validate_positive]) quantity = serializers.IntegerField(read_only=True) currency_code = serializers.CharField(allow_null=True, max_length=5) product_data = serializers.CharField(allow_null=True) personalization = serializers.CharField(max_length=1000, allow_null=True) def update(self, item:Item, validated_data): #Validating whether if 'product_data' in validated_data: schema_obj = item.item_type.schema try: print(validated_data) jsonschema.validate( json.loads(validated_data['product_data']), schema=schema_obj) except Exception as e: raise ValidationError({'product_data':[f'Schema for product data is not valid. {str(e)}']}) for key in validated_data: setattr(item, key, validated_data[key]) item.save() return item def validate_product_data(self, value): """ Validate whether property is json parsable :param value: :return: """ try: cur_obj = json.loads(value) return value except Exception as e: raise ValidationError("This field should … -
Django renew field from database,calculated field in Database
Newby in django, have two question, can't find needed info. 1) I have database (SQLite) which have table scale_calibration and field weight. Other application rewrite value in field weight 1-2 times per second. Is there possibility in Django to renew this field without renew browser (F5)? models.py: from django.db import models class Calibration(models.Model): mean_weight = models.FloatField(editable=True) hours_to_export = models.PositiveIntegerField(default=4, editable=True) weight = models.FloatField(editable=True) admin.py: from django.contrib import admin from .models import Calibration # Register your models here. admin.site.register(Calibration) 2) I try follow that link to make easy calculated field (that will be write to database when save), but i have no results and no error, don't understand where i get mistake. models.py: from django.db import models class Calibration(models.Model): mean_weight = models.FloatField(editable=True) hours_to_export = models.PositiveIntegerField(default=4, editable=True) weight = models.FloatField(editable=True) calibration_factor = models.FloatField(editable=True) @property def get_calibration(self): return self.weight/self.mean_weight def save(self, *args, **kwarg): self.calibration_factor = self.get_calibration() super(Calibration, self).save(*args, **kwarg) Please help with advise. -
Flask or django to do image processing on a web application
Im working on a project of image processing using opencv in a web application but i dont know what to use flask or django ? Some one to help me ? -
Is there a standard way to create dynamic formsets in Django?
I have created formsets in Django, and am able to render them in templates. The issue is that there does not seem to be a “standard” way to Add/Delete forms from formsets in the templates. I have tried “Django-dynamic-formsets” but this seems like a hack of a way to achieve something that is built into the Django admin. So is there a Django way to have an “Add” and “Delete” button on a template for adding and deleting forms from a formset? If it matters, I’m using inline formsets Django 2.2