Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializing Multiple API Fields into one. Django
I have a pre-defined API, like: { time : some_time, height : {1: 154, 2: 300, 3: 24}, color : {1: 'red', 2: 'blue', 3: 'green'}, age : {1: 27, 2: 324, 3: 1}, ... many, many more keys. } I have no control of this API, so cannot change its structure. Each integer key inside the sub dictionaries are linked and part of one record. For example the object that is 154 in height, is also colour: red and age: 27. I am aware one strategy to work with this is to have separate serialisers for each field. class MySerializer(serializers.ModelSerializer): # Nested serializers height = HeightSerializer() colour = ColourSerializer() age = AgeSerializer() etc, etc, etc But that still gives me messy data to work with, that requires lots of update() logic in the serializer. What I instead want to do is have one nested serializer that has access to the full request data, and can work with height, colour and age simultaneously and return me something like from the to_internal_value() method: { ['record' : 1, 'height': 154, 'colour' : 'red', 'age' : 27], ['record' : 2, 'height': 300, 'colour' : 'blue', 'age' : 324], ['record' : 3, 'height': 24, … -
Django ORM - How to calculate sum of array elements using PostgreSQL?
Here is what I have. class Array(Subquery): template = 'ARRAY(%(subquery)s)' class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A) class C(models.Model): b = models.ForeignKey(B) b_sub = B.objects.filter(a=OuterRef('pk').annotate(items=Count('c').values('items') result = a.objects.annotate(items=Array(b_sub)) And I'm getting # >>> result.first().items [4, 6, 10] But I need the sum of all items(4+6+10)->20 for each A row. Like this # >>> result.first().items 20 Is it possible ? -
How can I check the field value is unique in model django
I need that user can select only one photo with value 'COVER' in photo_tipo. Models.py class Listing(models.Model): ... class Photo(models.Model): PHOTO_TIPO_CHOICES = ( ('GALLERIA', 'Galleria'), ('COVER', 'Cover'), ('PLANIMETRIA', 'Planimetria'), ) photo_tipo = models.CharField( max_length=20, choices=PHOTO_TIPO_CHOICES, verbose_name='Tipo immagine', default='GALLERIA', ) Admin.py class PhotoInline(admin.TabularInline): model = models.Photo readonly_fields = ('image_tag',) @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): inlines = [ PhotoInline, ] enter image description here Can i control user selection with error message, or remove 'COVER' from selection list if he have already chosen COVER photo ? I can't use unique=True in field because all model must have COVER photo. -
Getting Started With DJango REST Framework SyntaxError: invalid syntax
I am new to python and even newer to DJANGO. I've written two Python app before but it free form. I've started learning DJANGO Rest Framework this: https://www.django-rest-framework.org/tutorial/quickstart/ Copying exactly I've made it up to Testing our API, and running python manage.py runserver gives me: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x10350c410> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/devindixon/Sites/Hearst/tutorial/tutorial/urls.py", line 18, in <module> from rest_framework import routers File "/Library/Python/2.7/site-packages/rest_framework/routers.py", line 25, in <module> from rest_framework import views File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 16, … -
Django convert latitude and longitude into city and county
I need to convert longitude and latitude coordinates to city and county in website design. When user input the longitude and latitude as charfield. How could I convert it into string and get the city and county using google API in Django? Thank you -
How can I pre populate a textfield with one value based on a pk in django
Having a model of Preorder and Product I created an inline formset. A client can make a preorder(FK). My goal for this inline formset is to have only a pre populated value in a textfield and not all the values. My desired prepoppulated value is related with the pk of the client. Here is my view: class PreorderProductCreateView(LoginRequiredMixin, CreateView): model = Preorder fields=['preorder_date','client'] template_name='test/test.html' def get_context_data(self, **kwargs): data = super(PreorderProductCreateView, self).get_context_data(**kwargs) data['client']=Client.objects.filter(pk=self.kwargs.get('pk')) # print(Client.objects.filter(pk=self.kwargs.get('pk')))# if self.request.POST: data['formset'] = PreorderProductFormSet(self.request.POST)#bound the formset with data else: data['formset'] = PreorderProductFormSet()#empty formset return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(PreorderProductCreateView, self).form_valid(form) def get_success_url(self, **kwargs): return reverse('client_list') I can fetch the pk of the current client successfully but I can not feed the returned client object to my data dictionary and finally can not load only the desired client object. Here is my url: url(r'^preorders/edit/(?P<pk>\d+)/$', views.PreorderProductCreateView.as_view(), name='preorder_edit'), Any suggestions? -
how to deploy django project and active virtualenv in cpanel
i am try to live my django project(hosting it) , my host provider company has accept python too , but i'm try to active virtual environment,and then install django , but i don't know how to active virtual env , what should i do with WSGI file location , thanks for advice -
Insert form Data in Django Database
When i have form data insert into django database but error on there built in function save(). Error is that form.save() AttributeError: 'FormName' object has no attribute 'save' Please anyone tell whats the problem and where and what the solution of that particular problem Thanks Regards Zeeshan -
how can I print side by side in a cycle for? (by the way I'm trying to do this in a django template)
<h3>Concepto:</h3> {% for j in li %} <h3> * {{ j.concepto_id }} de {{ j.fecha_realizado }} /</h3> {% endfor %}</center> this is a part of my template, what can I change in the last for to print side by side? and also I want to add decimal separator to the variable adicion -
How can i add filter to all querysets at the end of sql-query?
If i add filter in manager, sql-query to the database will be too long, because my filter will be at start of sql-query. I need to add this filter at the end, after all other filters and changes. -
how a django can a handle multi server - multi client?
How can I solve this very big problem? Multi-threading may help? The problem is that if multiple clients try to log in, when the server receives the first response from several IdP, all the users will show my page as logged in with the credential of the first user or several users. In the meanwhile my server starts listening for the IdP response. When the user logs in the in IdP page, the IdP sends data to my server, that handles them and shows my page to the user. -
ValueError at / ModelForm has no model class specified
I created a Todo list app.When I try to add item to list I get an error like this; ModelForm has no model class specified.How can I solve this? models.py from django.db import models class List(models.Model): item = models.CharField(max_length = 200) completed = models.BooleanField(default = False) def __str__(self): return self.item + ' | ' + str(self.completed) forms.py from django import forms from .models import List class ListForm(forms.ModelForm): class Meta: model:List fields: ["item", "completed"] views.py from django.shortcuts import render,redirect from .models import List from .forms import ListForm from django.contrib import messages def home(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request, ('Item has been added to list')) return render(request, 'home.html', { 'all_items': all_items}) else: all_items = List.objects.all return render(request,'home.html',{'all_items': all_items} ) -
Can not save django model object
Have one request with new value for one field. Than getting this value, setting it to the model object. And during saving have next error: TypeError: expected string or bytes-like object here is all Traceback: Traceback (most recent call last): File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\braces\views\_access.py", line 102, in dispatch request, *args, **kwargs) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\admin\PycharmProjects\squirrel_web\webinterface\webinterface-master\core\views.py", line 283, in post pprint(company.save()) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 905, in _save_table forced_update) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\base.py", line 955, in _do_update return filtered._update(values) > 0 File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 1204, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 876, in execute_sql sql, params = self.as_sql() File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\sql\compiler.py", line 1170, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\fields\__init__.py", line 770, in get_db_prep_save prepared=False) File "C:\Users\admin\Anaconda2\envs\web\lib\site-packages\django\db\models\fields\__init__.py", line 1459, in get_db_prep_value value = self.get_prep_value(value) File … -
Is it possible to open a new page (and let the client side see it) using selenium and python on linux server side? (Without --headless option),
I have a code that is running ok on a linux server. On the code, i used Linode, python, django and selenium. I have no problem when using the '--headless option'. opts = FirefoxOptions() opts.add_argument("--headless") Using headless, the code do what is suposed to do. But there is a specific case that i need to open a new page and let the client see it. So i cant use '--headless option'. And i cant figure out a way to do that. Some tips? Is there a way to run selenium and python on a linux server side, without the '--headless' option? -
Django-simple-history how to append extra info/object to historical record?
I'm looking for a way to change extra field in historical record. I have a model Invoice and Balance. class UserBalanceHistoricalModel(models.Model): """ Abstract model for history models tracking the IP address. """ invoice = models.ForeignKey('Invoice', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Faktúra') class Meta: abstract = True class UserBalance(TimeStampedModel): objects = UserBalanceManager() user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_balance', verbose_name='Užívateľ') balance = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name="Eur na konte") history = HistoricalRecords(bases=[UserBalanceHistoricalModel, ]) class Invoice(models.Model): ... Everytime when Invoice object is created, the UserBalance.balance is modified and historical record is automatically created. I want to add this Invoice object to the historical record but it doesn't work. The invoice_id is None. In [10]: u = User.objects.first() In [11]: i = Invoice.objects.first() In [12]: balance = u.user_balance In [13]: balance.balance = 45 In [16]: balance.history.invoice = i In [18]: balance.save() In [28]: balance.history.all().values_list('invoice_id',flat=True) Out[28]: <QuerySet [None, None, None, None]> Do you know what I'm doing wrong? -
Flask in Docker container access localhost
On my localhost I have a Django application running on port 8000. A Docker compose sets up different containers, among them a Flask application with the config: redirection-service: container_name: redirection-service build: context: "..." ports: - 5000:5000 links: - redis In the flask application I use a requests call to access an endpoint of the Django application on the localhost: backend_url = 'localhost:8000/...' requests.post(backend_url, data={}, allow_redirects=True, verify=False) But I get the error requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /.../ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f4d706f7588>: Failed to establish a new connection: [Errno 111] Connection refused',)) -
Captcha verification Python Django
I am getting Invalid captcha response for below set up. Contact form worked perfectly fine, I added rule that verifies captcha, I checked secret keys and still getting Invalid Captcha even after solving it. Below is my setup: views.py def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def grecaptcha_verify(request): response = {} data = request.POST captcha_rs = data.get('g-recaptcha-response') url = "https://www.google.com/recaptcha/api/siteverify" params = { 'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs, 'remoteip': get_client_ip(request) } verify_rs = requests.get(url, params=params, verify=True) verify_rs = verify_rs.json() response["status"] = verify_rs.get("success", False) response['message'] = verify_rs.get('error-codes', None) or "Unspecified error." return response def contact(request): if request.method == 'POST': if grecaptcha_verify(request) == "success": subject = request.POST.get('subject') message = request.POST.get('message') email = request.POST.get('email') if subject and message and email: try: send_mail(subject, message, email, ['myemail@gmail.com'],fail_silently= True) except BadHeaderError: return HttpResponse('{Bad Header}') return greatsuccess(request) else: return HttpResponse('{Invalid Form}') else: return HttpResponse('Invalid Captcha') return render(request, 'personal/contact.html') My template: <div class="form-area"> <form role="form" method="POST"> {% csrf_token %} <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required> </div> <br> <div class="form-group"> <input type="email" class="form-control" id="email" name="email" placeholder="Email" required> </div> <div class="form-group"> <textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea> </div> <button type="submit" name="submit" class="btn btn-m btn-secondary">Submit</button> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" … -
how to convert pdf to json in Django
I am trying to pdf file to Json file in Django but I did not get, please any can help me, how to convert pdf to Json file .afer I want to convert Json file to excel file please help me. -
Django, python, redis sorting
I used redis to sort out the most viewed items in a project I am working on. I would like to sort out only the most viewed for the day and out the overall most viewed. In other words, viewing count should restart everyday. Here is my code @login_required def image_ranking(request): image_ranking = r.zrange('image_ranking', 0, -1, desc=True[:110000] image_ranking_ids = [int(id) for id in image_ranking] most_viewed = list(Image.objects.filter(id__in=image_ranking_ids)) most_viewed.sort(key=lambda x: image_ranking_ids.index(x.id)) paginator = Paginator(most_viewed, 24) page = request.GET.get('page') try: most_viewed = paginator.page(page) except PageNotAnInteger: most_viewed = paginator.page(1) except EmptyPage: if request.is_ajax(): return HttpResponse('') most_viewed = paginator.page(paginator.num_pages) if request.is_ajax(): return render(request, 'images/image/ranking_ajax', {'section': 'images', 'most_viewed': most_viewed}) return render(request, 'images/image/ranking.html', {'section': 'images', 'most_viewed': most_viewed}) -
Is it possible to make a PUT request on list view, using ModelViewSets?
My goal is to handle a PUT request that contains multiple jsons. In simple words, I just want to be able to update multiple items with 1 PUT request. I tried to override the update() method in my ModeViewSet, but as I saw in my tests, the following request: (example) response = self.client.put('/collections/', [{'id':1, ...}, {'id':2, ...}]) didn't even go into the update method's code. Instead, it returned a 'method not allowed' error. I looked for this issue and I found out that, by default, drf supports PUT requests only on detail views. I also found this answer here on stack overflow, but I would prefer to see if it can be done without using a 3rd-party package. So, is there a proper solution without using a 3rd party package? Is it possible to make it work using ModelViewSets or should I use something different? -
XMLHttpRequest Synchronous Error in Bootstrap modal and Django
The program open Bootstrap Modal and load Django Form to create new permission, this is works. But when i want in the form add new Ajax call to load dynamically elements in Django ChoiceField appears the error and browser not finish the call never. I open browser inspect console and appears XMLHttpRequest error url.py: path('permisos/', general_views.permission_list,name='permission_list'), path('permisos/crear', general_views.permission_create, name='permission_create'), path('permisos/<int:id>/editar', general_views.permission_update, name='permission_update'), path('permisos/<int:id>/detalle', general_views.permission_detail, name='permission_detail'), path('permisos/<int:id>/borrar', general_views.permission_delete, name='permission_delete'), path('permisos/crear/cargar_elementos/', general_views.permission_load, name='ajax_load_permissions'), never get to call this function from ajax views.py: def permission_load(request): type = request.GET.get('type') if type == 2: # object list = ['general', 'billing', 'accounting'] elements = ContentType.objects.filter(app_label__in=list) elif type == 3: # instance list = ['general', 'billing', 'accounting'] content_type = ContentType.objects.filter(app_label__in=list) elements = general_models.content_type.model.objects.all() elif type == 4: # attribute list = ['general', 'billing', 'accounting'] content_type = ContentType.objects.filter(app_label__in=list) elements = general_models.content_type.model.objects.all() # get instance atributtes else: # module elements = general_models.Modules.objects.all() # other aspect is that i dont know how to load view result in the html choicefield response = { 'element': elements } json = simplejson.dumps(response) return HttpResponse(json, mimetype="text/json") forms.py: class CustomPermisisonForm(forms.Form): name = forms.CharField() ACTION_TYPE = ((1, ('Ver')),(2, ('Añadir')),(3, ('Modificar')),(4, ('Borrar'))) action = forms.MultipleChoiceField(choices=ACTION_TYPE, label='Acciones', initial=1, widget=forms.SelectMultiple()) PERMISSION_TYPE = ((1, ('Módulo')),(2, ('Objecto')),(3, ('Instancia')),(4, ('Atributo'))) type = … -
Django drf requests seem to be restarting when taking a long time
I'm using Django with DRF and I have a viewset that writes info to a csv file and then sends the link to the user. The function works correctly when the data retrieved is not too big, so when the response time is reasonable everything works ok. The problem is when the request takes a longer time. It seems like it simply restarts from the request call all by itself def get_operations(self, request): logger.info("Starting export request...") #[...business logic to retrive the data ...] file_url = settings.MEDIA_PREFIX_PATH + file_path logger.info("Saving response in %s", file_absolute_path) f = open(file_absolute_path, "w+") all_operations = operations.all() i = 0 for operation in all_operations: i = i + 1 #code to show progress in the log if (i / len(all_operations)*1000) % 5 == 0: logger.info("Progress: %d ", (i / len(all_operations)*100)) f.write("%s,%d,%d,%d,%s,%s\n" % (operation.datetime, operation.amount, operation.field2, operation.field3, operation.field5, operation.field6)) logger.info("Response saved, sending link %s", file_url) return Response(file_url) In the log, this is what I'm getting INFO 2018-11-26 11:23:33,525 Starting export request... INFO 2018-11-26 11:23:34,223 Response retrieved : 17010 records INFO 2018-11-26 11:23:34,225 Saving response in /tmp/generated_csv/1543231414.2250094.csv INFO 2018-11-26 11:23:42,825 Progress: 10 INFO 2018-11-26 11:23:51,161 Progress: 20 INFO 2018-11-26 11:23:59,072 Progress: 30 INFO 2018-11-26 11:24:07,694 Starting export request... INFO … -
Moving HTML Forms Over To Django 2.1
I have a number of forms for a website which have been prewritten. I am required to keep these as they are and not modify them. I am also required to move these to a Django 2.1 back end, which appears to have a built in form generation system, which doesn't appear to be compatible with the forms in themselves (I.E. The Jinja Scripting for forms appears to auto generate the forms without having any real choice in the matter). I cannot find any documentation on how to move pre existing forms into Django, and I have no idea how. Thanks for helping me. -
Django update all Users field Decimal
from decimal import Decimal from apps.main.models import User from django.db.models import F User.objects.all().update(freeze_balance=F('freeze_balance') + Decimal(F('balance') / 8300)) ERROR -> TypeError: conversion from CombinedExpression to Decimal is not supported How to write an ORM request (sorry for bad English) -
djngo form contains ">" symbol at the beginning , how to remove it?
> Username* Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. screenshot of the page : screenshot