Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute file.py on HTML button press using Django?
My goal is to click an HTML button on my Django web page and this will execute a local python script. I am creating a local web application as an interface to a project. This will not be hosted and will always just run on my local machine. My project is run with a python script (which carries out numerous tests specific to my project). All I need is for a button in my web interface to execute this script on my machine. Where in the Django framework can I specify a call to a local python script when a button is pressed? -
How can I access admin changelist from views?
How can I access filtered table from view? I want to export my table to xls, but it takes whole table, not the filtered one. In admin.py I can get filtered queryset like this: response = super(ScheduleAdmin, self).changelist_view(request, extra_context) qs = response.context_data["cl"].queryset Here is my admin.py class: class StatsScheduleAdmin(ScheduleAdmin): list_display = ( 'get_name', 'code', 'get_planned_hours', 'get_done_hours', #'get_planned_cost_workers', 'get_done_cost_workers', #'get_planned_cost', 'get_avg_cost', #'get_planned_hour_cost', 'get_avg_hour_cost', #'get_planned_score', 'get_done_score' ) search_fields = ('facility__name',) def changelist_view(self, request: object, extra_context: object = None) -> object: request.GET = request.GET.copy() self.month = request.GET.get('month', None) self.year = request.GET.get('year', None) if self.month or self.year: self.date = datetime.date(int(self.year), int(self.month), 1) else: self.date = timezone.now() self.month = self.date.month self.year = self.date.year extra_context = extra_context or {} extra_context['next'] = self.next_date extra_context['prev'] = self.prev_date extra_context['date'] = self.date sum_done_score = 0 sum_done_hours = 0 sum_done_cost_workers = 0 sum_schedule_income_value = 0 response = super(ScheduleAdmin, self).changelist_view(request, extra_context) qs = response.context_data["cl"].queryset #qs = self.get_queryset(request) for q in qs.values('id'): schedules = Schedule.objects.filter(id = q['id']) for s in schedules: sum_done_score += s.get_value() sum_done_hours += s.get_done_hours() sum_done_cost_workers += s.get_done_cost_workers() sum_schedule_income_value += s.get_schedule_income_value() extra_context['sum_done_score'] = sep('%.2f zł' % sum_done_score, thou=".", dec=",") extra_context['sum_done_hours'] = sep('%.2f h' % sum_done_hours, thou=".", dec=",") extra_context['sum_done_cost_workers'] = sep('%.2f zł' % sum_done_cost_workers, thou=".", dec=",") extra_context['sum_schedule_income_value'] = sep('%.2f zł' % sum_schedule_income_value, … -
How to add recommended products in django oscar dashboard
I am using django-oscar == 1.6.1 for a project. I am trying to add recommended products to an individual product in the dashboard, currently I see that the recommended product field is empty, how do I populate it and give the ranking? -
django list_filter filter by id display by name
Currently in the admin interface it is possible to filter the projects by company name not the company instance in the database. Because of that it is impossible to filter out the projects of one specific company if there are multiple companies with the same name. Please fix it - make it possible to filter projects by actual companies in the database (company name should still be visible in the filter options. list_filter = ('company__name',) #I change and become list_filter = ('company__id',) But now, the filter displays the id, but name need. How do I display by name but filter by id? -
Django Rest Framework Serializer lost ListField data during validation
I want to serialize a list of strings as well as some other fields. Somehow it doesn't appear to be in validate data. class IpandaOptionsSerializer(serializers.Serializer): lst = serializers.ListField( serializers.CharField(), ) field_a = serializers.CharField() field_b = serializers.IntegerField() Request payload: {"lst":["abc"],"field_a":"some text","field_b":1} Debugger output: ipdb> serializer.is_valid() True ipdb> serializer.validated_data OrderedDict([('field_a', 'some text'), ('field_b', 1)]) Any ideas about why is it so? -
React / Django/Webpack Update Existing Form & URL slug by primary key
I've created a form to add new client details, and would like to allow users to edit click on a link to update existing forms (with the fields pre-populated with the existing data) but don't know how to route the url (with the client primary key as the slug) on both the React and Django (with Webpack). Creating a new client form currently has the url localhost:8000/client And would like the existing form, say client with primary key 1 to have the form url be: localhost:8000/client/1 really appreciate it if someone can give some pointers, thanks! -
Timed Pagination or Scrolling in Django
I have a very simple Django webapp that tracks job status in a shop. It works fine, but I'd like to add in a feature that automatically scrolls or changes pages, whichever is easier, every 30 seconds so that if there are more jobs than fit on one screen, it shows all the jobs on a time interval. Is anyone aware of a method to do this with Django or javascript? Much appreciated. -
getting error mysqlclient not install after the installation?
getting the following error when I trying the django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install MySQL client? I install MySQL and MySQL client and configure the setting.py file in Django project. and now when i am going to migrate a project it will throwing following error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install MySQL client? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangodb', 'USER': 'ROOT', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', } } it is giving the following error Did you install MySQL client? -
Model save method data check not working as expected
I am hitting a blank, maybe you can help me steer in the right direction. Model method: def save(self, *args, **kwargs): query = Contract.objects.filter(rented = self.rented).exclude(id=self.id) check_data = gatekeeper_check(self, query) if check_data: super(Contract, self).save(*args, **kwargs) Function: def gatekeeper_check(self, query): current_contracts = {} for item in query: print(item) if (item.agreement_ends >= self.agreement_starts): current_contracts[item.id] = f'{item.agreement_starts} - {item.agreement_ends}' print(item.agreement_ends, item.actual_agreement_end, self.agreement_starts) raise ValidationError(mark_safe(f'Rentable already booked for the date range: <br>' + '<br>'.join({f'Contract ID: {k} | Start-End Date: {v}' for k, v in current_contracts.items()}))) else: return True The result is not what i expect: Rentable already booked for the date range: Contract ID: 6UOj2RnNDX6jiGlC | Start-End Date: 2019-09-30 - 2019-10-29 On the current object: start_date: 2019-01-29 end_date: 2019-04-29 This should save ideally because the rentable is not booked on these days. It is however booked from 2019-09-30 What am i doing wrong? -
Django in Subdirectory - Redirect
I have a url http://localhost/project_name/. My ListView is working prefectly fine as url http://localhost/project_name/company/. But when i am adding a company using CreateView then it is redirecting me to http://localhost/company/ which is saying Page Not Found. class CompanyListView(LoginRequiredMixin, generic.ListView): template_name = 'company/company.html' queryset = Company.objects.all() context_object_name = 'companies' paginate_by = 10 def get_queryset(self): return ( self.queryset.exclude(id=1) .exclude(company_is_deleted=True) .annotate(number_of_company_users=Count('userprofile')) ) class CompanyCreateView(LoginRequiredMixin, generic.CreateView): model = Company template_name = 'company/company_form.html' fields = ['company_name', 'company_description', 'company_email', 'company_website', 'company_address', 'company_phone', 'company_status', 'company_monthly_payment', 'company_logo'] def get_success_url(self): return reverse('superadmin_company') project_name/urls.py path('company/', include(company_urls)), apps/company/urls.py path('', views.CompanyListView.as_view(), name='superadmin_company'), path('add', views.CompanyCreateView.as_view(), name='superadmin_company_create'), How can i redirect using get_succes_url() with project_name in url as http://localhost/project_name/company/ after adding the data using CreateView -
Django-viewflow passing primary key pk to proofread existing entry
I'm trying to implement viewflow, I want on first step a model entries are made and on second step I want to those entries to be proof read and on third step I want those to be approved and saved. I can't get the values of the model on the second step it says: Generic detail view ImageUpdateView must be called with either an object pk or a slug in the URLconf. How can I pass pk of the image to handle second step? @kmmbvnr -
how to create method post django
I already practice with list, and retrieve in viewset views.py, but when I use create it's quite strange for me to get use to it, here is my model: remind.py class Remind(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "remind" variant.py class Variant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=255) size = models.CharField(max_length=5, null=True, blank=True) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) color = models.CharField(max_length=20, null=True, blank=True) image_link = models.ImageField( upload_to=get_image_path, blank=True, null=True, max_length=50000) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "variant" all I want is check if the quantity in variant table if it ==0 I will get user.id ( which login) and variant.id and create in "remind table" This is how I get user.id: user = get_object_or_404(User, pk=request.user.id) and here is my code for views.py: class RemindViews(viewsets.ViewSet): def create(self, request, pk=None): user = get_object_or_404(User, pk=request.user.id) remind = Remind.objects.create(user=user.id, variant=pk) serializer = RemindSerializer(remind, many=True) return Response(serializer.data) my serializer.py: class RemindSerializer(serializers.ModelSerializer): class Meta: model = Remind fields = '__all__' IDK how to express the condition query (using django query) and also in serializer.py, could … -
Access to Django ORM from remote Celery worker
I have a Django application and a Celery worker - each running on it's own server. Currently, Django app uses SQLite to store the data. I'd like to access the database using Django's ORM from the worker. Unfortunately, it is not completely clear to me; thus I have some questions. Is it possible without hacks/workarounds? I'd like to have a simple solution (I would not like to implement REST interface to object access). I imagine that achieving this could be done if I started using PostgreSQL instance which is accessible from both servers. Which project files (there's just Django + tasks.py file) are required on the worker's machine? Could you provide me with an example or tutorial? I tried looking it up but found just tutorials/answers bound to a problem of local Celery workers. -
How to fix Invalid formset error in django?
I trying to code quiz app, where i used to formset to add multiple choices. But when i submit the form, it shows not valid. I tried every possible scenario to make form valid. like giving request.POST, request.FILES inside the parenthesis. def insert_qustin(request): if request.method == 'POST': data = TestChoice() form = TestChoiceForm(request.POST) frmset = TestChoiceFormset(request.POST, prefix='frmset') testquestion = request.POST.get('ques') idd = TestQuestion.objects.get(ques=testquestion) data.testquestion = idd print(frmset.errors) if form.is_valid() and frmset.is_valid(): data = form.save(commit=False) for ch in frmset: choice_opt = ch.cleaned_data.get('choice_opt') is_answer = ch.cleaned_data.get('is_answer') data.choice_opt = choice_opt data.is_answer = is_answer data.save() print("data saved") else: print("not valid") return HttpResponse('Success') If form gets validated successfully i can save the data. -
django responsive templates does not work in mobile
Hello i am new in django i am work on a project i am use responsive template in my project and its work proparly in desktop full screen this is my website http://hp30405.pythonanywhere.com/ and if i open it in my mobile then its not working this is my project link : http://hp30405.pythonanywhere.com/ 1 its work proparly in full screen desktop mode this is desktop mode photo 2 its work proparly in small screen in desktop nav bar is convert in 3 dot menu working responsive in desktop 3 nut its not work in mobile phone nav bar is not convert in 3 dot menu this is mobile photo my desktop mode is off in mobile please try it and give me ans how can i solve it -
how to disable django cassandra engine Limit value?
I'm using Django cassandra engine as as my cassandra driver. by default all queries are limited with value 10000. I know that I can append .limit(None) to my query. Is there a way that do this with an option in cassandra configs or Djanog cassandra engine configs? thanks in advance. -
what does "?" doing in variable definition
i'm new in django , css ,javascript and etc.i saw sometimes people using "?" in variable definition imageURL?: string; and i don't know what is usage for.here some sample code that i found in local storage : interface Account { displayName: string; id: string; imageURL?: string; name?: string; rpDisplayName: string; } interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; } tnx -
Pass json output to the py file
I'm new to Django. I want to pass a json object using ajax to a python file. But it get's an error "path('myreq/', views.requestAjax,name='myreq'), AttributeError: module 'uml1app.views' has no attribute 'requestAjax' " This is my javascript code. $.ajax({ method: 'POST', url: "/myreq", data: {'data': JSON.stringify(jsonArr)}, success: function(response) { console.log(response) alert('success'); }, error: function(response) { console.error(response) alert('error'); } }); This is the code of views.py def requestAjax(request): if request.is_ajax(): message = request.POST.get('data') return JsonResponse(message) This is the code of url.py path('myreq/', views.requestAjax,name='myreq'), does anyone can solve that? thanks on advanced. -
Cant send message from back to front using django channels
I can send data from front to back but there is problem in sending message from my WebSocket recieve function in consumers.py to socket.onmessage in thread.html. Here is both codes: import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) async def websocket_receive(self, event): print("receive", event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') print(msg) user = self.scope['user'] username = 'default' if user.is_authenticated: username = user.username myResponse = { 'message': "this is a instant message", 'username': username } await self.send({ "type": "Websocket.send", "text": json.dumps(myResponse), }) # {'type': 'websocket.receive', 'text': '{"message":myResponse}'} async def websocket_disconnect(self, event): print("disconnected", event) @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] I have put print function inside websocket recieve and it is called but I'm not sure about self.send and I don't know how can i send it and here is thread.html: {% extends "base.html" %} {% block content %} <p>Thread for {% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif … -
Pytesseract doesn't find any text only on some files
I have following code and the problem is, that on some images the return value is empty. The structure of the images is always the same. it is plain black text on white background. Clearly readable. 50% of the results are excellent and other ones are just empty. the only error I get is: wand/image.py:4623: CoderWarning: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `filename.png' @ warning/png.c/MagickPNGWarningHandler/1747 self.raise_exception() But it raises this error everytime, even if the output is fine. def retrievetext(self,docname): r = BytesIO() self.ftp.retrbinary("RETR /httpdocs/"+docname , r.write ) r.seek(0) with wi(file=r, resolution = 400) as pdf: pdfImage = pdf.convert('png') imageBlobs = [] for img in pdfImage.sequence: imgPage = wi(image = img) imgPage.crop(left=200,top=600,width=1800,height=800) imageBlobs.append(imgPage.make_blob('png')) recognized_text = [] for imgBlob in imageBlobs: im = Image.open(BytesIO(imgBlob)) im = im.convert('L') text = pytesseract.image_to_string(im, lang = 'deu') recognized_text.append(text) return recognized_text Somebody has an idea how to improve the results? Best regards -
Use specific form in view, based on chosen option
I am writing web-application for Hydrological observation. There are different types of Hydroposts. Hydroposts are classified by observations they are making. HydropostType1 observes water level, water temperature, air temperature, discharge HydropostType2 observes water level, water temperature, air temperature HydropostType3 observes water level, water temperature, water ripple and so on. My forms.py looks like that forms.py #Minimum forms for observation class BasicObservationForm(forms.Form): level = forms.IntegerField(label = 'Уровень воды') water_temperature = forms.DecimalField(label = 'Температура воды', max_digits = 5, decimal_places = 2, max_value = 70, min_value = -70, required = False) class AirTemperatureForm(forms.Form): air_temperature = forms.DecimalField(label = 'Температура воздуха', required = False) class RippleForm(forms.Form): ripple = forms.IntegerField(label = 'Волнения воды', required = False) class DischargeForm(forms.Form): discharge = forms.DecimalField(label = 'Расход воды', required = False) class PrecipitationForm(forms.Form): precipitation = forms.CharField(label = 'Атмосферные осадки', required = False) class Hydropost1CategoryForm(BasicObservationForm, AirTemperatureForm, DischargeForm): pass class Hydropost2CategoryForm(BasicObservationForm, AirTemperatureForm): pass class Hydropost3CategoryForm(BasicObservationForm, AirTemperatureForm, RippleForm): pass Right now I am using multiple views for each category form. views.py @login_required(login_url = '/login/') def Hydropost1CategoryRecord(request): if request.method == 'POST': form = Hydropost1CategoryForm() context = { 'form': form, } if form.is_valid(): return redirect('/') elif request.method == 'GET': form = Hydropost1CategoryForm() context = { 'form' : form, } return render(request, 'hydrology/record.html', context) @login_required(login_url = … -
Django RestFramwrok loop issues it only runs for the firsst element
It supposed run 3 times but it only runs for the first element. I have tried to run it on python console and the same approach works fine. not able to figure out the issue with code. @api_view(['POST']) def SaveVisitView(request): if request.method == 'POST': visits = json.loads(request.POST.get('request')) for i in range(len(visits['visits'])): serializer = VisVisitsSerializer(data=visits['visits'][i]) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) data { "visits": [ { "action": "i", "local_id": "170", "visit_id": "", "school_program_id": "1", }, { "action": "i", "local_id": "172", "visit_id": "", "school_program_id": "1", }, { "action": "i", "local_id": "172", "visit_id": "", "school_program_id": "1", }, ] } -
how to connect python with html code using django
i am designing a website with sliding slide shows in it and i want to add a python hand gesture module so that i can control my website with my hand . For hand gesture i have created a python script on openCV which has been trained with all hand gestures like slide using hand . Please tell me how to do this job using django such that the response on website is fast when a gesture is passed on openCV ? i have tried it using post request with postman tool but its response is very slow and i can not connect it with html ? -
Django Rest Framework - Import CSV(" No file was submitted ")
I am trying to upload CSV file in Django Rest Framework using the serializer. Below have provides the image which contains code for Model,View and Serializer and the console output when I try to submit the CSV file. Before validating a serializer when I check with print(serializer.initial_data) there is file inside the serializer, but as soon as the serializer is validate it says no file was submitted. Code for Model, View, Serializer and Output Output System check identified no issues (0 silenced). January 30, 2019 - 11:22:06 Django version 2.1, using settings 'hoplet.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QueryDict: {'inventory': [<InMemoryUploadedFile: MOCK_DATA_2.csv (application/vnd.ms-excel)>]}> {'shop_inventory': [ErrorDetail(string='No file was submitted.', code='required')]} [30/Jan/2019 11:22:18] "POST /uploadinv HTTP/1.1" 200 10 -
Intercept Celery connection error and revert to synchronous execution
I am using celery with redis as a broker on django and would like to call task.delay() only when a connection to the broker is successful. Otherwise, I intend to execute the task synchronously using task.apply() and block until its finished. My thinking for this is so that I can at least get the app to run even without a redis server set up. My question is how/where to intercept the Connection Error or any idea on how to go about achieving this. Thanks.