Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Seleium Can not lauch Chrome Browser on Apache via mod_wsgi
I am developing a Django Project. I use a view named test_seleium_view() to lauch a Chrome Browser by Seleium. For demonstration purpose, my code is as simple as below: urls.py # coding=utf-8 from __future__ import unicode_literals, absolute_import from django.conf.urls import url from .views import * urlpatterns = [url(r'^test_seleium$',test_seleium_view,name='test_seleium'),] test_seleium.py # coding=utf-8 from __future__ import unicode_literals, absolute_import import time from django.shortcuts import render_to_response from selenium import webdriver def test_seleium_view(request): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--start-maximized") chrome_options.add_argument('--disable-extensions') CHROME_DRIVER_PATH = r"C:\Program Files (x86)\chromedriver\chromedriver_win32_v2.43.exe" driver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH, chrome_options=chrome_options) driver.get('http://www.google.com') time.sleep(5) driver.quit() return render_to_response('result.html',{'text': "success"}) When I visit http://127.0.0.1:8000/app_name/test_seleium on Django development server, everything is working fine, Seleium lauch a Chrome browser then open http://www.google.com wait for 5 seconds then close Chrome browser. Then I take this Django project to my virtual machine(VMware Workstation, win 7 64bit installed) which installed Apache and mod_wsgi, when I visit http://my_vmware_virtual_host_ip:8000/app_name/test_seleium, it doesn't lauch Chrome browser, but after a while, the page show the text "success",just like test_seleium_view() had ran successfully, and there is a chrome.exe process on windows 7 background. my environment: VMware Workstation 15.0.0 build-10134415 Windows 7 64bit on VMware Virtual Machine Apache 2.4.37 Win64 mod_wsgi 4.6.5+ap24vc14-cp36-cp36m-win_amd64 python 3.6.4 64bit Django 2.0.7 selenium 3.14.1 chromdriver win32_v2.43,win32_v2.42 I search this … -
Graphene Django: Change field names
If I have a Django model with fields names in french like this (nom is the french translation of name): class Categorie(models.Model): nom = models.CharField(max_length=100) def __str__(self): return self.nom Is it possible to configure a GraphQL Query with Graphene Django in order to query the graph with an english translation of the field (using name instead of nom): query { allCategories { id name } } Thanks, -
Django changes made to M2M field by signals not saved
I have the following models : class Case(models.Model): title = models.CharField(verbose_name="Titre", max_length=1000) statement = models.CharField(verbose_name="Énoncé du problême", max_length=1000) class GivenCase(models.Model): given_case = models.ForeignKey(Case, on_delete=models.CASCADE) title = models.CharField(verbose_name="Titre", max_length=1000, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Candidate(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) cases = models.ManyToManyField(GivenCase, verbose_name="Cas", related_name="cases", blank=True) assigned_cases = models.ManyToManyField(Case, verbose_name="Cas assignés", related_name="assigned_cases") To put it simply, I have Candidates that can have multiple Cases, whenever a Case is assigned to a Candidate the signal is handled and a GivenCase is created and assigned to the Candidate. Here's my signal handler : @receiver(models.signals.post_save, sender=Candidate) def generate_exercise_for_new_user(sender, instance, **kwargs): cases = Case.objects.all() assigned_cases = GivenCase.objects.filter(user=instance.user).values_list("title", flat=True) for case in cases: if case.title not in assigned_cases: new_case = GivenCase(title=case.title, given_case=case, user=instance.user) new_case.save() instance.cases.add(new_case) if new_case in instance.cases.all(): print("ITS HERE") my problem is when I make changes to a Candidate in the admin view the signal code is firing (checked with prints) and the new_case is saved in my M2M field (the last if at the end of the signal returns true), despite all that when I go back to my Candidate after saving the changes no GivenCase is saved inside it despite being created (They are visible in the available Case, but … -
Celery not queuing to a remote broker, adding tasks to a localhost instead
My question is same like this Celery not queuing tasks to broker on remote server, adds tasks to localhost instead, but the answer is not working to me. My celery.py # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='amqp://<user>:<user_pass>@remoteserver:5672/<vhost>', backend='amqp') # app = Celery('project') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When I run: $ celery -A worker -l info I receive the following output: -------------- celery@paulo-Inspiron-3420 v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-36-generic-x86_64-with-Ubuntu-18.04-bionic 2018-10-30 13:44:07 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mycelery:0x7ff88ca043c8 - ** ---------- .> transport: amqp://<user>:**@<remote_ip>:5672/<vhost> - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery I tried stop rabbitmq server and uninstalled it … -
Django Rest Framework deserialize queryset into other model
I have a generic 'Order' model. There are other models which represent other forms of 'Order's. I need to deserialize these other instance to our generic 'Order' model. So I retrieve a queryset and turn it into a list but am unable to correctly deserialize it into Order. Order has 4 fields, reference, delivery_date, note and customer_note. The other model has equivalent fields named external_reference, expected_delivery_date, note and customer_note. class OrderSerializer(serializers.ModelSerializer): reference = serializers.CharField(source='external_reference', required=True) delivery_date = serializers.DateField(source='requested_delivery_date') note = serializers.CharField() customer_note = serializers.CharField() class Meta: model = Order fields = ('reference', 'delivery_date', 'note', 'customer_note') Since you can't provide a QuerySet as data input for a Serializer I turned it into a list: orders = AppOrder.objects.all() data = list(orders.values()) serialized = OrderSerializer(data=data, many=True) However, this does not work. Source does not grab the correct field: delivery_date': ['This field is required.'] It may be that I am doing this entirely wrong and that there are better ways to deserialize one model to another, if so please do tell as well. -
Django forms concurrency/validation problem
I have a question regarding django form validation and concurrency. Say I have a invoice form where the form clean checks if on of the invoice positions about to be created already exists in an other invoice (check is executed via querying the database!). If so it raises an validation error. Now I have the case that 2 users create a new invoice with the identical position and click on save at the same moment. The form validation passes in both cases because the first invoice was not saved to database while the second one passes the form validation. Now I have 2 invoices with the same position which should not be possible. Is there a decent way to solve this problem? Thanks for your help! Jonas -
I am having this issue with chrome and opera when connecting to localhost django
localhost sent an invalid response. ERR_SSL_PROTOCOL_ERROR Even when I remove secure SSL and HSTS I can't connect to localhost. this is the message returned in terminal console [30/Oct/2018 13:34:42] code 400, message Bad request version ('ÊÊÀ+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [30/Oct/2018 13:34:42] You're accessing the development server over HTTPS, but it only supports HTTP. -
django list model entry with multiple references
I have the following models which represent songs and the plays of each song: from django.db import models class Play(models.Model): play_day = models.PositiveIntegerField() source = models.CharField( 'source', choices=(('radio', 'Radio'),('streaming', 'Streaming'), ) ) song = models.ForeignKey(Song, verbose_name='song') class Song(models.Model): name = models.CharField('Name') Image I have the following entries: Songs: |ID | name | |---|---------------------| | 1 | Stairway to Heaven | | 2 | Riders on the Storm | Plays: |ID | play_day | source | song_id | |---|----------|-----------|---------| | 1 | 2081030 | radio | 1 | | 1 | 2081030 | streaming | 1 | | 2 | 2081030 | streaming | 2 | I would like to list all the tracks as follows: | Name | Day | Sources | |---------------------|------------|------------------| | Stairway to Heaven | 2018-10-30 | Radio, Streaming | | Riders on the Storm | 2018-10-30 | Streaming | I am using Django==1.9.2, django_tables2==1.1.6 and django-filter==0.13.0 with PostgreSQL. Problem: I'm using Song as the model of the table and the filter, so the queryset starts with a select FROM song. However, when joining the Play table, I get two entries in the case of "Stairway to Heaven" (I know, even one is too much: https://www.youtube.com/watch?v=RD1KqbDdmuE). What … -
how to retrive particular form from formset_factory django
I want to add form with counter value to get the form based on the loop how can i do that? models.py TestForm = modelformset_factory(TestForm,fields="__all__",extra=5) view.py class IndexView(FormView) form_class = TestForm def get_context_data(self,*args,**kwargs): ctx=super(IndexView,self).get_context_data(*args,**kwargs) ctx['profile'] = Profile.objects.all() index.html {% for profile_data in profile %} {{form.management_form}} {{form.forloop.counter0.firstname}}<!-- how to do like this --> {% endfor %} -
Override 'create' function in Django serializer
I wonder how to handle POST request to properly save the incoming data, having such models: class Recipe(models.Model): author = models.ForeignKey('auth.user', related_name='recipes', on_delete=models.CASCADE) image = models.TextField(default='None') name = models.CharField(max_length=100) description = models.TextField(default='No description') votes = models.IntegerField(default=0) def __str__(self): return self.name class Ingredient(models.Model): image = models.TextField(default='None') name = models.CharField(max_length=100) description = models.TextField(default='No description') price = models.DecimalField(max_digits=8, decimal_places=3) unit_price = models.DecimalField(max_digits=8, decimal_places=3) unit_quantity = models.CharField(max_length=20) def __str__(self): return self.name I wanted to avoid duplicating Ingredient objects, so to provide quantity of specific Ingredient in Recipe I've created a RecipesIngredient model that binds Ingredient with Recipe, but also contains a quantity of this Ingredient: class RecipesIngredient(models.Model): recipe = models.ForeignKey(Recipe, related_name='ingredients', on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.CharField(max_length=100) def __str__(self): return self.quantity I've also prepared some serializers for these models: class IngredientSerializer(HyperlinkedModelSerializer): class Meta: model = Ingredient fields = ( 'url', 'image', 'name', 'description', 'price', 'unit_price', 'unit_quantity' ) class RecipesIngredientSerializer(HyperlinkedModelSerializer): ingredient_name = ReadOnlyField(source='ingredient.name') ingredient_price = ReadOnlyField(source='ingredient.price') ingredient_unit_price = ReadOnlyField(source='ingredient.unit_price') ingredient_unit_quantity = ReadOnlyField(source='ingredient.unit_quantity') class Meta: model = RecipesIngredient fields = ( 'url', 'ingredient_name', 'quantity', 'ingredient_price', 'ingredient_unit_price', 'ingredient_unit_quantity' ) class RecipeListSerializer(HyperlinkedModelSerializer): author = ReadOnlyField(source='author.username') author_url = ReadOnlyField(source='author.url') class Meta: model = Recipe fields = ( 'url', 'author', 'author_url', 'image', 'name', 'description', 'votes' ) class RecipeDetailSerializer(HyperlinkedModelSerializer): … -
MySQL in 5 different locations Mac OS. Unable to access database
Okay, I'm still a beginner here..clearly. I am running a django python project that was set up with MySQL and the database was accessed through SequelPro. All working fine. Set up a new project, new virtualenv, and went to configure MySQL but was having lots of problems. Checked the MySQL server under settings to see if was running and it was totally unresponsive with no ability to connect / start server etc. I re downloaded the MySQL community server. It gave me new root password etc. I've discovered I now have 5 instances of mysql on my computer. (lol) The 5 paths are usr/local/mysql usr/local/mysql.5.7.23-macos10.13-x86_64 usr/local/mysql.bak usr/local/var/mysql /Applications/XAMPP/xamppfiles/var/mysql/ The databases that I have been working on are located in only the 3rd and 4th locations usr/local/mysql.bak/data usr/local/var/mysql/data The connection to said database no longer works through SequelPro, it throws MySQL said: Access denied for user 'root'@'localhost' (using password: YES) If someone can point me in the right direction to remedy this and not lose my databases I'd really appreciate it. -
How can I set Django password emails connect to my db
I am new to django, but have set up a db and user authentication. I now have set up the password options through django auth and am using the built in templates. The problem is, I cannot receive the password reset emails from any users from my db, only the super user email. Is there a way i can redirect it to my database? """ Django settings for TalkingDead project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import posixpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'app', # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'TalkingDead.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
Allow a user to authorize another user with read only permision to Google Analytics by code
I need to allow users to give read-only permission to a second user, identified by the email address, to a Google Analytics property. What I do now is similar to the sample in: https://developers.google.com/analytics/devguides/config/mgmt/v3/user-management But, this way I need the user to give the app a token with user management permissions. Is there a way I can do this without user management permissions? Maybe given the user with a link, so he can give another user access using the same Google Analytics permission interfaces? But facilitating the process. Thanks, Rodolfo -
Use TO_CHAR in Django filter query method that makes a join
I need to cast a field via TO_CHAR using Django. I know I can: Author.objects.extra(where=["TO_CHAR(name) = 'John'"]) and I also can: Author.objects.filter(article__name='CoolArticle') which will make the join on Article behind the scenes. Is there a way to combine both and achieve this: author.articles.filter(website__name='AwesomeWeb') # where website__name is casted via TO_CHAR -
i am submitting a form which has two files and doing a ajax post request. But i am not able to get the file in my django view
i am able to do a post request but not able to retrive the files in my django view. this is the ajax post request performed on button click $("#upload-button").on('click', function() { var formdata = new FormData(); var idElementForFiles = 'file1-to-upload'; var uploadedFiles = document.getElementById(idElementForFiles); formdata.append("metadata_name",uploadedFiles.files[0].name); formdata.append("metadata", uploadedFiles.files[0]); var idElementForFiles = 'file2-to-upload'; var uploadedFiles = document.getElementById(idElementForFiles); formdata.append("name",uploadedFiles.files[0].name); formdata.append("file", uploadedFiles.files[0]); var csrfmiddlewaretoken= document.getElementsByName('csrfmiddlewaretoken') [0].value; formdata.append("csrfmiddlewaretoken", csrfmiddlewaretoken); $.ajax({ type:'POST', url: '/submit', processData:false, contentType:false, data : { "formdata" :formdata, "value":"testing", }, "beforeSend": function(xhr, settings) { console.log("Before Send"); $.ajaxSettings.beforeSend(xhr, settings); }, cache: false, success: function(data){ console.log(data); }, error: function(jqXHR, textStatus, errorThrown){alert(errorThrown);} }); }); code to retrive the files in my views.py which is not working def save_files(request): if request.method == 'POST': v=request.POST.get("value") fs = FileSystemStorage() # get the PDF file and save it file1 = request.FILES['file'] filename1 = file1.name fs.save((os.path.join("static","pdf_files",filename1)), file1) #fs.save(os.path.join("static","pdf_files",filename1)) file2 = request.FILES['metadata'] filename2 = file2.name fs.save((os.path.join("static","metadata_files",filename2)), file2) return HttpResponse("its working") -
How to allow one django project alow to different application notification settings
PUSH_NOTIFICATIONS_SETTINGS = { 'FCM_API_KEY': '[key]', "FCM_ERROR_TIMEOUT": 1800, 'APNS_CERTIFICATE': os.path.join(BASE_DIR, "[.pem]"), "APNS_USE_SANDBOX": "api.development.push.apple.com", "UPDATE_ON_DUPLICATE_REG_ID": True, "APNS_USE_SANDBOX":True } above setting declared two times with two different app -
How to reuse multiple apps from a django project with another django project?
I have a project with multiple apps that I want to reuse in a number of other django projects, I've been looking through the documentation here https://docs.djangoproject.com/en/1.10/intro/reusable-apps/ but that example only uses a single app I'm wondering if theres anything I need to watch out for considering I want to use more than a single app across my other projects -
How to run Python Django and Celery using docker-compose?
I've a Python application using Django and Celery, and I trying to run using docker and docker-compose because i also using Redis and Dynamodb The problem is the following: I'm not able to execute both services WSGI and Celery, cause just the first instruction works fine.. version: '3.3' services: redis: image: redis:3.2-alpine volumes: - redis_data:/data ports: - "6379:6379" dynamodb: image: dwmkerr/dynamodb ports: - "3000:8000" volumes: - dynamodb_data:/data jobs: build: context: nubo-async-cfe-seces dockerfile: Dockerfile environment: - REDIS_HOST=redisrvi - PYTHONUNBUFFERED=0 - CC_DYNAMODB_NAMESPACE=None - CC_DYNAMODB_ACCESS_KEY_ID=anything - CC_DYNAMODB_SECRET_ACCESS_KEY=anything - CC_DYNAMODB_HOST=dynamodb - CC_DYNAMODB_PORT=8000 - CC_DYNAMODB_IS_SECURE=False command: > bash -c "celery worker -A tasks.async_service -Q dynamo-queue -E --loglevel=ERROR && uwsgi --socket 0.0.0.0:8080 --protocol=http --wsgi-file nubo_async/wsgi.py" depends_on: - redis - dynamodb volumes: - .:/jobs ports: - "9090:8080" volumes: redis_data: dynamodb_data: Has anyone had the same problem? -
Cursor.execute is not wroking
cursor.execute(query) is not executing in Django if I have entered tuple manual in oracle using sqldeveloper. with connection.cursor() as cursor: try: print(value) print(username) cursor.execute("Select * from users where id=1") finally: cursor.close() -
Django form widget : submit onchange
I have a Django form with django-select2 and I would like to submit this one, not with a submit button but with onchange widget attribute. I tried to write this : class ManageDocForm(forms.Form): def __init__(self, *args, **kwargs): super(ManageDocForm, self).__init__(*args, **kwargs) omcl_list = forms.ModelChoiceField( queryset=Omcl.objects.all(), label=_('OMCL Choice'), widget=ModelSelect2Widget( model=Omcl, search_fields=['code__icontains', 'name__icontains'], attrs={"onChange": 'actionform.submit();', 'data-placeholder': "Please select an OMCL"} ) ) But it doesn't seem to work. This is my template : <div class="col-md-12"> <form action="" method="POST"> {% csrf_token %} <fieldset> <legend><span class="name">{% trans 'Select an OMCL' %}</span></legend> {{ form.omcl_list }} </fieldset> </form> </div> And my views.py file : class ManageDocView(AdminRequiredMixin, View): """ Render the Admin Manage documents to update year in the filename""" template_name = 'omcl/manage_doc_form.html' form_class = ManageDocForm success_url = 'omcl/manage_doc_form.html' @staticmethod def get_title(): return 'Change Document Title' def get(self, request): form = self.form_class() context = { "form": form, "title": self.get_title() } return render(request, self.template_name, context) def post(self, request): form = self.form_class() query_document_updated = None query_omcl = None query_document = None omcl_list = request.POST['omcl_list'] query_omcl = Omcl.objects.get(id=omcl_list) query_document = Document.objects.filter(omcl=omcl_list) context = { 'form': form, 'query_omcl': query_omcl, 'query_document': query_document, 'title': self.get_title() } return render(request, self.template_name, context) When I select an OMCL in my list, it doesn't submit the value and … -
Django Manager for Group model does not work - returns empty queryset
I'm junior dev. I want to create managers for Django Groups. One new one and one that will overwrite default manager EDIT: Django 1.8, python 2.7.15 My managers: class DefaultGroupManager(models.Manager): def get_queryset(self): test_ids = Test.objects.values_list('rel_group_id', flat=True) return super(DefaultGroupManager, self).get_queryset().exclude(id__in=test_ids) class AllGroupsManager(models.Manager): def get_queryset(self): return super(AllGroupsManager, self).get_queryset().exclude(rel_group__start_date__lte=datetime.now()-timedelta(days=30)) With these managers I created something like this: dgm = DefaultGroupManager() agm = AllGroupsManager() agm.contribute_to_class(Group, 'get_all') dgm.contribute_to_class(Group, 'objects') And it was working. I could use Group.get_all.all() and new Group.objects.all(). In return I had proper lists of objects. But my senior dev said that I have to do it by creating the new Group model that inherits from Group. So I did: My Group model: class GroupModel(Group): get_all = DefaultGroupManager() objects = AllGroupsManager() But it does not work! When I use GroupModel.get_all.all() or overwrited GroupModel.objects.all() it returns empty list [] Everything seems to be good :( I will appreciate any help! -
Save image from canvas image in Django folder
I want to save image in my canvas window. var Pic = document.getElementById("myCanvas").toDataURL("image/png"); Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, ""); In views.py, i am able to get image data after Base64 decode @csrf_exempt def add(request): if request.method == "POST": payload = json.loads(request.body) image_data = base64.b64decode(payload['imageData']) f = open('Pic.png', 'w') f.write(str(image_data)) f.close() return HttpResponse(request) else: return HttpResponse('no data') After doing the base64 decoding, I get this. It is not recognized by image viewer. b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03 \x00\x00\x02X\x08\x06\x00\x00\x00\x9av\x82p\x00\x00 \x00IDATx^\x8c\xbdks$Yr\x1dx#2\x12@U\xf5kD\x0e\xf7W\xe9\xc3\x9a\x96\x1c\xa3v?\xe9\xc1\x99\xa6(\xfd\xe5\xb5\xb55\xe9\x039\xd3\xd3\xdd\xd5\xf5\x002#Rv^\xee7QM\x8d0\x04Q\rdFF\xdc\x87\xbb\x9f\xe3\xc7\xfd.\xff\xf6\x1f\xff\xe3\xed\xb4\xae\xe3\xb4\x8c\xb1\x0e}\xed\xeb\x18\xb7\xdbm\x1c\xf8\xf7m\x8c\xeb\xbe\x8f\x1d\xff\xb5,\xe34Nc[\xf5\xfdv_\xc68nc\xd9oc=n|\xef\xe9\x86w\x8d\xb1\x8c\xdb8\xad\xcbX\x96e\xec\xeb\xc1\x9f\xd7\xe54\xf6u\xe1\xb5\xc7m\xd5\x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a4_\x07\xf6\xd1\xd5c~\x8c\xfd\xc0\xf8\xc3\xf6\xe9\xf5+\xec,\xc6\x99\x0f\x8d\xe7\x81}\x97\xdd\xe0\xfd{o\xad\x87\xee\x85\xcfl;y\xb5M\x8c\x8f\xa2-\xdc6\xda\xf6\xd3v\x1a\xdb\xf9\xa4u\xe0}\x8c\xf7b\xeee{\xf4\x19\x18\x14\xbe\xef\x04\x9b\xa39\xe0\x8c`\xfc\x8ec\xdc\xae\x17\xd9\xf0\xfd2\x96\xfd\xc2\xb5}\xcd\xbd\xf8\xf91>\xe7\xe3il\xeb\xc6\xef\xf3i\xe3\xe7\xdeNY_\xd8\x13\x07\xfd\xd1e\x835\xc4:\xec5\xd4\xbeI\xeb\x19{\xf9\xca\xcf\xe7+\x07L\x03\xd6\xe4\t\xff\xe6\x1ca\xde\xf4\xda\x9d\xf3\x06\x1b\n\ -
Change the background color on the button
i've trouble. I don't know how make event handler for button, which will change background color. This my code Html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Flask Tutorial</title> </head> <body> <h1> My First Try Using Flask </h1> <p> Flask is Fun </p> <form method="post"> <input type="submit" name="red" value ="red" > </form> </body> </html> and i try wrote it, used flask from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): red = request.form("background-color:red;") return render_template("home.html") if __name__ == "__main__": app.run(debug=True) If u know how make event handler on django - write here, pls. -
DRF annotated queryset filtering with django-filter
can anyone help with filtering in DRF. I have some products models, say Product and manager ProductManager: class ProductItem(Model): price = DecimalField() class Product(Model): items = ManyToManyField(ProductItem) priceman = ProductManager() class ProductManager(Manager): def get_queryset(self): qs = super().get_queryset().annotate( total_price=Sum('items__price') ) return qs Here if filter class: class ProductFilter(django_filters.rest_framework.FilterSet): class Meta: model = Product fields = { 'total_price': ['lt', 'gt'], } Here is view: class ProductViewSet(ModelViewSet): queryset = Product.priceman.all() filterset_class = ProductFilter and I get the error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: total_price How should I configure the filter class to make this work? -
How to compress video size in python
I have used python3 with Django==1.11.6. I haved used on filefields in databased. But we have compress video size its not working. Plz give me ans how to compress video size. Example:- def user_directory_path(instance, filename): if instance.post_image.file.content_type[0:5] == 'video': return 'images/'+str(instance.post.user.user.email)+"/"+str(time.time())+"/post/"+str(instance.post.id)+"/video/%s" %(filename) class Img(models.Model): post_video = models.FileField(upload_to=user_directory_path, default=None, blank=True, null=True, max_length=1000)