Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django validate_unique method all ready exists message
Thinking How to get the instance pk that exists during validate_unique? it is not a good practice to overwrite the method validate_unique and I don't know if it would be correct to validate unique fields in the clean() method. but imagine the following situation: you want to show admin users which is the instance that already exists so they can edit it if they want, I think it would be more intuitive when working with thousands of data. the following code is just an example - think about it as a pseudocode although I tried it and it works, I know it could be better def clean(self): lockup ={} unique_togethers = self._meta.unique_together[0]#these could throw an error for field in unique_togethers: f = self._meta.get_field(field) value = getattr(self, f.attname) if value is None: continue if f.primary_key and not self._state.adding: continue lockup[str(field)] = value qs = snippet.objects.filter(**lockup) if qs.exists and self._state.adding: raise ValidationError( format_html('''this object all ready exist plese edit it on <a href="{}">Edit</a>''', reverse('admin:testing_snippet_change', args=(qs[0].pk,)))) Is this approach correct, how to apply it to the validation_unique method to works in all unique validations? Result -
Get the dropdown data and update the data in Django
dear all of django developer , i having facing this below issue . i try to update this db table data where has one field and one drop down field data , i getting basic field data . but not get the drop down list data . i request expert for help me the issue . Advanced Thanks For All views.py def update_brands(request, id): brand = Brand.objects.get(id=id) form = AddBrandForms(request.POST, instance=brand) if form.is_valid(): form.save() return redirect('/parts/brands') return render(request, 'parts/edit_brands.html', {'brand': brand }) edit_brands.html {% extends 'parts/base.html' %} {% block content %} <form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form"> {% csrf_token %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <input type="text" name="country" value="{{ brand.brand_name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <select id="cars" name="cars"> {% for db in dbf.all %} <option value="{{ db.db}}">{{ db.db}}</option> {% endfor %} </select> </div> </div> <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} -
Why form.is_valid() does not returns false immediately when the first clean_<field_name> raises ValidationError?
I have defined a form with two CharField. I have defined clean method for both fields. In my view i am calling is_valid() method of the form I defined. I am giving an invalid input for field1 so that clean_field1 method raises ValidationError. In clean_field2 i am accessing cleaned_data[field1]. When calling the url, it is giving 500 error. And in stack trace it says KeyError: 'field1'. On debugging I found ValidationError was raised in clean_field1 method. I expected that form.is_valid() will return false when clean_field1 raised ValidationError. But django went on to execute clean_field2. Why django is executing clean_field2, when clean_field1 raised ValidationError. form.is_valid() should have returned false when clean_field1 raised ValidationError. Am I correct? Does Form.is_valid() method return only after executing all clean_<'field_name'> methods(even if ValidationError was raised)? If yes, then this poor design I think. If first clean_<'field_name'> method raises ValidationError then what is the point in executing other clean_<'field_name'> method? I think Form.is_valid() should return false when it encounters first ValidationError. Or am I missing something? It will be really helpful if anyone can explain what is going on? Thank you. The code that I was executing: class MyForm(Form): field1 = forms.CharField() field2 = forms.CharField() def clean_field1(self): … -
Django queryset get empty values in query
So I'm trying to get all the values to be able to display in my templates. However I have encountered myself with this problem: I have these models: class Project(models.Model): projectId = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) class PM(models.Model): PMid = models.AutoField(primary_key=True, db_column="Id", db_index=True) PMNumber = models.CharField(max_length=50, unique=True, db_column="PMNumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') And I'm trying to get all the projects with their respective PMNumber. For which I'm trying something like this: fpm = PM.objects.all() projects = [] for i in fpm: projects.append('ProjectName': i.projectId.description, 'PMNumber': i.PMNumber}) After that the result is like this [{'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] However, I'm still missing some projects that don't have a PM related to them, I want all the projects in the queryset to be able to show them in a template, not just the ones that have a PM. It should look something like this: [{'ProjectName': 'pr2', 'PMNumber':'None'}, {'ProjectName':'pr3' , 'PMNumber':'None'}, {'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] Is there a way to do this? or is there another way to do this in the views? Note: I know that setting an ID for each class in Django is not … -
Unsupported config option for services.volumes: 'postgres_data'
My docker-compose.yml is below, version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: but while running the command docker-compose up -d --build I got the following error message,someone please help me, ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services.volumes: 'postgres_data' -
Save table loop data in database in django
html file <table style="border-spacing: 10px;"> <thead> <th>Test</th> <th>Rate</th> </thead> <tbody> {% for booktest in var1 %} <tr> <td width="100%">{{ booktest }}</td> <td>{{ booktest.rate }}</td> </tr> {% endfor %} <br> <th scope="row">Total</th> <td><strong> {{ total_rate }} </strong></td> </ul> </tbody> </table> I want to save the {{ booktest }} and {{ booktest.rate }} value in database , as both has multiple values has it is in for loop -
How to correctly add AJAX to DataTable?
i'm using a bootstrap data table and i'm passing the registers through ajax. However, for some reason since i started filling the table with the ajax function, the search box, the pagination and the column ordering stopped working. At first it does print the registers, but if i search for one, it adds a row at the beggining of the table saying "No registers found", like it's empty. Same thing happens when i try to switch how many registers it shows per page. (And it doesn't paginate at all) Here is my code: <script type="text/javascript"> $(document).ready(function() { $('#dom').DataTable({ ajax:{ url: '/restapi/enviarjson/', type: 'get', success: function (json){ $("#dom > tbody").empty() var table = []; $.each(json, function(key, val){ table.push('<tr>'); table.push('<td style="vertical-align: middle; text-align: center;">'+ '<input type="checkbox" id="onff2" name="onff2" value="'+val.pk+'">' + '</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.pk+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.nombre_activo+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.desc_act+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.dat_cont_arch+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.resp_dom+'</td>'); table.push('<td style="color:#A9A9A9; vertical-align: middle; text-align: center;">'+val.fields.estado+'</td>'); table.push('</tr>'); }); $("<tbody/>", {html: table.join("")}).appendTo("table"); } }, language: {searchPlaceholder: "Buscar", search: "", "paginate": { "first": "Primero", "last": "Ultimo", "next": "Siguiente", "previous": "Anterior" }, "zeroRecords": "Sin resultados encontrados", "infoEmpty": "", "emptyTable": "No hay información", "lengthMenu": "Mostrar … -
how to return 200OK before the function is completed
I write a bot for Vkontakte on Django(2.2.4), with the vk_api library Some of the functions are quite long (performed in 5-7 seconds). But Vkontakte requires the server to respond no longer than 3 seconds. If the response is delayed, the request is sent again, and the bot starts sending the same message many times after a while. (I Use The Callback Api) I will describe my problem briefly my function runs for more than 6 seconds the 200OK response must be sent in less than 3 seconds Is it possible to solve this problem without major changes in the code? # views.py @csrf_exempt def MainBotView(request): # i need something like return HttpResponse('ok') here ... my slow code ... return HttpResponse('ok') # but I don't need it at the end (I use pythonanywhere and Celery perhaps does not work there) Should I use threading? How? -
Passing User Data to Admin Actions in Django
I am attempting to write an admin action that accesses data from selected users. i.e. email. However, when I access Account instances, I have only been able to access the instance/data of the user that is currently logged in. For example, to access the emails of selected users, I have tried: #models.py class Account(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) #admin.py from account.models import Account for Account in queryset: author = request.Account.email #OR author = Account.objects.get(email=request.email) and both of these will fill "author" with the email address of the admin that is trying to pull the data. Does anyone know how I could call to the instances of selected accounts with an admin action? -
How to calculate django model fields
I have the following fields in my models: class Materiale(models.Model): quantity=models.DecimalField(max_digits=5, decimal_places=2, default=0) price=models.DecimalField( max_digits=5, decimal_places=2, default=0) VAT=models.DecimalField(max_digits=5, decimal_places=2, default=0) VAT_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) But the VAT_amount is the result of quantity*price*VAT. How can store in my database that value automatically??? It's important that the field (VAT_amount) is present in database. Thanks. -
Django Rest Framework Permissions List Issues in ModelViewSet
I am trying to check multiple permissions classes in the get_permissions method of a ModelViewSet but even though the has_object_permission returns false on all of the classes in the list I'm still able to perform the action. Here's my get_permissions method: def get_permissions(self): if self.action in ("retrieve", "list",): permission_classes = [AllowAny] elif self.action in ("update", "partial_update", "destroy",): permission_classes = [IsOwner | IsAdminUser] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] On an update IsOwner returns True for has_permission and False for has_object_permission but even a non-admin can make updates. Anyone know what I'm doing wrong here? -
WebSocket handshake failed.. Error in the browser console, with response code: 500
My django channels app is not working. Can this be a reason that my site is 'not secure'. Does sockets work only on HTTPS? If someone could help... -
How to add more features to user permission in django?
I am new to django. I want to edit default user auth_permissions. More precisely I want to add an integer field in addition to "label", "code" features to distinct permission types (like strong, moderate and etc.). So far I could not find anything like this. I tried to make custom permissions, but could not add them to the permission database. Anyone could help me? -
Drag drop save database django
I have a django project that teacher assign students courses by drag drop.I made html part but I couldnt figure out how to save db. Is there any framework or method ? screenshot from my project -
Hosting a django app on a personal wondows machine
I've developed a django web application which I now want to deploy so that everyone in my organization can start accessing the website. However, I do not have a dedicated server location to actually host it. I have been given a dedicated Windows machine to host the app on. Previously I've always used things like Heroku or AWS to deploy websites which make it really easy, so I really have no idea how to turn a desktop into a server hosting a web application. Does anyone have any suggestions on how to do this using free software? Thanks in advance. -
Django admin filtering based on user profile
I have the following models in django: class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) In Djanog admin I would like to filter based on the company field of Manager OR Admin based on which is currently logged in. I have the followin code for this: def get_queryset(self, request): qs = super(EmployeeAdmin, self).get_queryset(request) if request.user.is_superuser: return qs if hasattr(request.user, 'manager'): return qs.filter(company=request.user.manager.company) elif hasattr(request.user, 'admin'): return qs.filter(company=request.user.admin.company) It works nice, but I don't really like the way I have to allways check with hasattr() function which one is logged in. Also this is an error prone way, if I add another role for eg: Employer besides Manager and Ddmin and I forget to handle Employer... Could you recommend a more neat solution for this? Thank you! -
Not returning html page for viewing - django
error message --> The view orders.views.charge didn't return an HttpResponse object. It returned None instead. any reason why my charge.html isn't working? views,py import time import stripe from django.conf import settings from django.shortcuts import render from django.urls import reverse def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='eur', description='A Django charge', source=request.POST['stripeToken'] ) template = "orders/charge.html" return render(request, template) charge.html {% extends "fuisce/base.html" %} {% block content %} <div class="container mt-5 text-center"> <h2 class="text-center">Thanks, you for your Orders</h2> <a href="/my-orders" class="btn btn-success">My Orders</a> </div> {% endblock %} urls.py from django.urls import path from . import views from orders import views as order_views from users import views as user_views urlpatterns = [ path('checkout/', order_views.checkout, name='checkout'), path('charge/', order_views.charge, name='charge'), path('orders/', order_views.orders, name='user_orders'), path('add_user_address/', user_views.add_user_address, name='add_user_address'), ] -
Can I have Interprocess Communication with Django Channels?
I am building an architecture where I have several Services that runs in parallel, one of them serves the client application, which communicates through Websockets, call it Frontend. I choose Django with Channels for its implementation. I have another service (implemented in Python too) that needs to communicate with the Frontend, I need to do it through network sockets using a simple custom protocol. How can I integrate those services that way? I took a look at the Cross-Process Communication docs but I did not figured out how to do it. Can I push messages to a channel from any Python process? -
Use @propert based attr as Model slug, django's views?
I am trying to use an attribute created using the @property decorator im my model as a slug field for django DetailsView, as follow: class Province(models.Model): name = models.CharField(max_length=30) code = models.CharField(max_length=10) @property def slug(self): return slugify(self.name) My url: path("map/<slug:slug>", MyView.as_view()) My view: class MapTemplateView(DetailView): template_name="myapp/map.html" context_object_name = "province" model = Province But when accessing page I get the following exception: Cannot resolve keyword 'slug' into field. Choices are: code, id, name -
Post request to external Rest Service using Django - use returned json to update model
I require some advice on the best way to implement the following details using Camunda Rest API and Django: 1) User is presented with a form - Selects the details and then does a POST request to camunda using 'http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start' the details sent in this POST request consist of 3 variables in a JSON RAW : in the form of : {"variables": {"UserID" : {"value" : "user.", "type": "String"}, "OrganisationID" : {"value" : "some value", "type": "String"} }, "businessKey" : "SomeBusinessKey" } from views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import StartProject import requests class StartProcessView(TemplateView): template_name = 'startdeliveryphase.html' def get(self, request): form = StartProject() return render(request, self.template_name, {'form':form}) def post(self,request): form = StartProject() url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = "{\"variables\":\r\n {\"Username\" : {\"value\" : \"[form.Username]\", \"type\": \"String\"},\r\n \"OrganisationInitiating\" : {\"value\" : \"[form.OrganisationInitiator]\", \"type\": \"String\"}},\r\n \"businessKey\" : {form.businessKey}\r\n }" headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) return render(response, self.template_name, {'form':form}) The response is returned as a 200 along with a JSON payload in the form: { "links": [ { "method": "GET", "href": "http://localhost:8080/engine-rest/process-instance/fbff8359-84cd-11ea-a2e1-00155d891509", "rel": "self" } ], "id": "fbff8359-84cd-11ea-a2e1-00155d891509", "definitionId": "Process_B_PerProject:1:71921815-737c-11ea-91a6-00155d891509", "businessKey": "SomeBusinessKey", "caseInstanceId": null, "ended": false, "suspended": false, "tenantId": … -
django model and templates
I'm new to django, I'm trying to make a display for an e-commerce site enter image description here I would like to display only the sub-categories corresponding to the category -
Error accessing AWS elasticache redis in cluster mode) + TLS Enabled from django service
I'm trying to connect AWS elasticache(redis in cluster mode) with TLS enabled, the library versions and django cache settings as below ====Dependencies====== redis==3.0.0 redis-py-cluster==2.0.0 django-redis==4.11.0 ======settings======= CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com:6379/0", 'OPTIONS': { 'PASSWORD': '<password>', 'REDIS_CLIENT_CLASS': 'rediscluster.RedisCluster', 'CONNECTION_POOL_CLASS': 'rediscluster.connection.ClusterConnectionPool', 'CONNECTION_POOL_KWARGS': { 'skip_full_coverage_check': True, "ssl_cert_reqs": False, "ssl": True } } } } It doesn't seem to be a problem with client-class(provided by redis-py-cluster) since I'm able to access from rediscluster import RedisCluster startup_nodes = [{"host": "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com", "port": "6379"}] rc = RedisCluster(startup_nodes=startup_nodes, ssl=True, ssl_cert_reqs=False, decode_responses=True, skip_full_coverage_check=True, password='<password>') rc.set("foo", "bar") rc.get('foo') 'bar' but I'm seeing this error when django service is trying to access the cache, is there any configuration detail that I might be missing? File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 32, in _decorator return method(self, *args, **kwargs) File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 81, in get client=client) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 194, in get client = self.get_client(write=False) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 90, in get_client self._clients[index] = self.connect(index) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 103, in connect return self.connection_factory.connect(self._server[index]) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 64, in connect connection = self.get_connection(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 75, in get_connection pool = self.get_or_create_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 94, in get_or_create_connection_pool self._pools[key] = self.get_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 107, in get_connection_pool pool = self.pool_cls.from_url(**cp_params) File "/usr/lib/python3.6/site-packages/redis/connection.py", line 916, … -
How can I make chained multiple choice fields in Django with JQuery?
I want to make a chained multiple choice field. I have working code for chained dropdown boxes below. I want to be able to choose more than one option at each level and have the next level return all records for each of the selected values. How can I make this happen? (my code is not very DRY, so appreciate any notes on that as well, but that is secondary) models.py class Nace_Level_1(models.Model): code = models.CharField(max_length=1) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_2(models.Model): parent = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE) code = models.CharField(max_length=2) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_3(models.Model): parent = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE) code = models.CharField(max_length=4) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_4(models.Model): parent = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE) code = models.CharField(max_length=5) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_5(models.Model): parent = models.ForeignKey(Nace_Level_4, on_delete=models.CASCADE, blank=True, null=True) level_3 = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE, blank=True, null=True) level_2 = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE, blank=True, null=True) level_1 = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE, blank=True, null=True) code = models.CharField(max_length=6) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name forms.py class NaceForm(forms.ModelForm): … -
multivaluedictkeyerror post django
I have a views.py where i get a list of value from user checked checkbox now i want it to store in database views.py def ResultTest(request): var = request.POST.get('selectedTests') request.session['var'] = var def PostTest(request): if request.method == 'POST': test = UserTest() var = request.session['var'] test.TestSelected = request.POST['var'] i have 2 function in ResultTest function i am getting the user checked result and i want that result to get store in database from PostTest function as i have a form which get submitted along with the result of checked checkbox . Being more specific after user checked the checkbox page redirect to next form where user get to fill a form and there is the value present which is selected by the user in previous checkbox page so now with other form details i want to save the checked result. -
psycopg2 installing within docker
I am learning django,currently while installing psycopg2 with the following command docker-compose exec web pipenv install psycopg2 binary==2.8.3 I got this error and my python version within docker is Python 3.7.7 the error message I got is Warning: Python 3.6 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path/to/python can someone help me to find out the solution or the command to specify the python version