Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Turning a Django form Choice Field into a combobox
Basically, I have a Django form where one of the fields is a choice field of the select dropdown type. What I want to do is format that field so that it's still a choice field, but I can use a text input to type into the field itself so that the only the choices that match will appear automatically. Basically something like this: https://jqueryui.com/autocomplete/#combobox Unfortunately I can't use the code in that link because I most likely don't have the correct jquery-ui. So does anyone know of a way to replicate it? Thanks. -
Django: filter JSONField with multiple nested arrays
I have a JSONField, called metadata on my model in Django. The data in that fields might looks something like this { "vis": { "plots": [ { "id": 1, "x": "foo", "y": "bar", "externalData": [ { "x": "do", "y": "re", "source": { "name": "me", "location": "some address" } }, { "x": "fa", "y": "so", "source": { "name": "FINDME", "location": "some other address" } } ] } ], "somethingElse": [] }, "moreStuff": {} } I want to be able to filter models that have "name": "FINDME" in an externalData object (at any index), inside a plots object (also at any index). I initially tried MyModel.objects.filter(metadata__vis__plots__externalData__source__name='FINDME') No good. Then I tried MyModel.objects.filter(metadata__vis__plots__externalData__source__contains={'name':'FINDME'}) No good. Then I tried MyModel.objects.filter(metadata__vis__plots__externalData__contains=[{'source': {'name':'FINDME'}}]) Still no luck. Finally, I tried MyModel.objects.filter(metadata__vis__plots__contains=[{'externalData':[{'source': {'name': 'FINDME'}}]}]) Still no hits. Clearly, I am doing this all wrong. Any ideas? -
DJango 2.0 Error in links
I wanted to learn DJango and researching I found this interesting book DJango By Example. One of the probelms is that the book is using DJango 1.8.6 and I am trying to use the v2.0, so from time to time I came with some error that you can resolved really easy. But when I tried to create a Shop with the code and instructions from the book I came with this problem: Image The code that I used was this one: view.py @staff_member_required def admin_order_detail(request, order_id): order = get_object_or_404(Order, id=order_id) return render(request, 'admin/orders/order/detail.html', {'order': order}) @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/order/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) return response urls.py re_path(r'admin/order/(?P<order_id>\d+)/$', views.admin_order_detail, name='admin_order_detail'), re_path(r'^admin/order/(?P<order_id>\d+)/pdf/$', views.admin_order_pdf, name='admin_order_pdf'), admin.py def order_detail(obj): return '<a href="{}">View</a>'.format(reverse('orders:admin_order_detail', args=[obj.id])) order_detail.allow_tags = True def order_pdf(obj): return '<a href="{}">PDF</a>'.format(reverse('orders:admin_order_pdf', args=[obj.id])) order_pdf.allow_tags = True order_pdf.short_description = 'PDF bill' I also have the html files on the correct directory but I don't think that is the problem. So if anyone knows where is where I am wrong I appreciated. Thanks :3 -
Django test will not notice "django.contrib.auth.context_processors.auth"
I'm writing a basic django test for a forms.Form type page. Here is the form: # This is the form to become a seller class BecomeSellerForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField(min_length=3, max_length=20) phone_number = forms.IntegerField(max_value=19999999999) My test consists of a basic post request and I asser my response status code is 200. However, my I get this error in my test: ValueError: modules context processor require "django.contrib.auth.context_processors.auth"to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file. And it's getting caught in the successful return statement in my views.py code: return render(request, 'accounts/become_seller_success.html', context) What confuses me is that I 100% have met this requirement in my settings file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, }, ] So why is my test fussing about it? I have been looking around but have not seen a problem/solution that is similar. Thanks a bunch for the help -
Django MVC Philosophy and using get_object_404 instead of raise404
I'm essentially confused about the motivation behind using get_object_or_404(). When I was reading the Django docs, it said, Philosophy Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist? Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling. Some controlled coupling is introduced in the django.shortcuts module. What do they mean when they say that it couples the "model layer to the view layer?" And how does it do so? -
Make a Django tables2 table header sticky when the page scrolls down
As the title says, I'm making tables in Django using django-tables2. I want it so that when I scroll down the page and the header of the table is about to go off the page, I want it to stick to the top of the page until the window scrolls up past it again. And no, I don't want to have a scrollable div within the page. Below is some relevant text: tables.py class Example(tables.Table): field1 = tables.Column() field2 = tables.Column() field3 = tables.Column() class Meta: attrs = {'class': 'table table-striped', 'style': 'display: block; overflow: auto;'} example.html <style></style> <table> <thead> <tr> <td>Field1</td> <td>Field2</td> <td>Field3</td> </tr> </thead> <tbody> <tr> <td>Text</td> <td>Text</td> <td>Text</td> </tr> </tbody> </table> <script></script> With CSS and JavaScript, does anyone have any solutions? I tried several solutions already but all of them ended up not doing anything to the headers at all. I'm using jquery-3.2.1. Thanks. -
ElasticSearch does not show properly updated document on subsequent search
I'm developing a Django app and we're using ES to manage our large inventory queries. A user has the ability to "delete" an item, but it just toggles a boolean field from False to True and our ES query only returns results where deleted is False. However, the problem is that I have one view that deletes the item, and then upon completion redirects to the inventory list page, but the item is still listed until I refresh the page. I attempted a query within the inventory view to see if the index just hadn't actually updated yet, but it is. This is essentially what the view looked like: class InventoryView(View): def get_context_data(self, **kwargs): print(requests.get('http://localhost:9200/<index_name>/item/<id>').content) # This prints out the result showing deleted = True as it should items = es_client.search(*args) print(items) # Prints out the list of items, but shows the "deleted" item with deleted = False! es_client is defined in some other file and imported: es_client = Elasticsearch(hosts=hosts) I know, I know, living in the stone age here, but we don't have the staff to upgrade everything: Django v1.8 ElasticSearch v1.7 Postgres v9.3 Python v2.7 -
How to send HTTP response in Json format in Generic Class Views [Django]
I have sub-classed Generic DetialView class in views.py and trying to figure out a way to return data in JSON format based on an argument received in the url. Here's what I have tried doing... # views.py from django.views.generic import DetailView from django.http import JsonResponse class ExtendedView(DetailView): context_object_name = 'post' model = StorageModel template_name='posts.html' def get_context_data(self, **kwargs): data = super(HacksViewPost, self).get_context_data(**kwargs) if bool(self.request.GET): data__ = JsonForm(request.GET) if data__.is_valid(): json = data__.cleaned_data['json'] if json == 'true': return JsonResponse({'data': 'data'}) return data But this gave me TypeError as it should be: TypeError at /category/extended-slug/ context must be a dict rather than JsonResponse. The url that activates the ExtendedView class is: /category/extended-slug?json=true So, the question is how could i send data in JSON Format from a Generic View Class and are there any better ways of acheiving this? -
Cannot Connect to Django from outside the Local Server
I built a basic Django project and app on Centos7, but I cannot access it externally. Check the configuration below. [root@pytoncentos7 myproject]# cat settings.py | grep ALLOWED ALLOWED_HOSTS = ['*'] And I run my server as below. [root@pytoncentos7 myproject]# python3.6 manage.py runserver Performing system checks... System check identified no issues (0 silenced). May 24, 2018 - 15:03:04 Django version 2.0.5, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Also, the firewall is not running [root@pytoncentos7 myproject]# firewall-cmd --state not running Below are the list of my ports. [root@pytoncentos7 myproject]# netstat -lptun Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 1643/python3.6 tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 876/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 982/master tcp6 0 0 :::3306 :::* LISTEN 986/mysqld tcp6 0 0 :::22 :::* LISTEN 876/sshd tcp6 0 0 ::1:25 :::* LISTEN 982/master udp 0 0 127.0.0.1:323 0.0.0.0:* 636/chronyd udp6 0 0 ::1:323 :::* 636/chronyd Also, when I try to connect from the outside to port 8000, it fails !!. But ofcourse I can telnet locally. And at the same time, I have Apache running on 80 and reachable from … -
Create ManyToMany objects inside other model's form
I have a Post model with a ManyToManyField to Tag. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() author = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): tag = models.CharField(max_length=255) slug = models.SlugField(max_length=255) Then I have the PostForm, in which I can create new Posts. class PostForm(forms.ModelForm): class Meta: model = Post fields = __all__ I would like to be able to create new Tag objects on the Post form, but instead a <select multiple="multiple"> is created as the input for Tags, and that won't let me type new tags. If I change the PostForm to include a TextInput for the tags, I can type them out, but that will fail in the backend since obviously that Tag doesn't exist (yet). tags = forms.CharField(widget=forms.TextInput) How can I achieve what I am trying to do? -
Inlineformset_factory for table with two foreign keys
I'm trying to expand the use of the official django tutorial which builds a voting app. At the moment what I'm trying to do is to allow a user to create a poll, input the poll name, the poll options and invite the users he wants by email from the already registered users. my model.py: class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) is_active = models.BooleanField(default=True) activation_date = models.DateTimeField('Activation Date', blank=True, null=True) expiration_date = models.DateTimeField('Expiration Date', blank=True, null=True) public_key = models.CharField(max_length=30, blank=True) hash = models.CharField(max_length=128, blank=True) timestamp = models.DateTimeField(auto_now=True) def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class EligibleVoters(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) email = models.EmailField(null=True) my forms.py: from django.forms import ModelForm, inlineformset_factory from django import forms from .models import Poll, Choice, EligibleVoters, PollKeyPart, User class PollForm(ModelForm): activation_date = forms.DateTimeField(required=False) expiration_date = forms.DateTimeField(required=False) class Meta: model = Poll fields = ['question_text', 'is_active', 'activation_date', 'expiration_date'] class ChoiceForm(ModelForm): class Meta: model = Choice exclude = () ChoiceFormSet = inlineformset_factory(Poll, Choice, … -
Django : Migration translation not loaded (test)
Here is my test class : class FrontTest(LiveServerTestCase): serialized_rollback=True fixtures = ['event.json'] The keywork "serialized_rollback=True" will apply migrations for each test case. My class is loading a fixture, here it is : { "model": "mezzanine_agenda.event", "pk": 5, "fields": { "comments_count": 0, "keywords_string": "", "rating_count": 0, "rating_sum": 0, "rating_average": 0.0, "site": 1, "title": "event search", "title_fr": "event search", "title_en": "", "slug": "event-search", "_meta_title": "", "description": "event search", "description_fr": "event search", "description_en": "event search", "gen_description": true, "created": "2018-05-22T09:49:07.515Z", "updated": "2018-05-24T07:58:24.273Z", "status": 2, "publish_date": "2018-05-22T09:49:07Z", "expiry_date": "2018-05-23T13:31:31Z", "short_url": "unset", "in_sitemap": true, "content": "", "content_fr": "", "content_en": "", "user": [ "admin" ], "sub_title": "", "sub_title_fr": "", "sub_title_en": "", "parent": null, "category": null, "start": "2018-05-22T09:49:04Z", "end": "2018-05-23T13:32:18Z", "date_text": "", "location": null, "facebook_event": null, "shop": null, "external_id": null, "is_full": false, "brochure": "", "no_price_comments": null, "no_price_comments_fr": null, "no_price_comments_en": null, "mentions": "", "mentions_fr": "", "mentions_en": "", "allow_comments": false, "rank": null, "prices": [] } } And i've a migration which defines the event model : class Migration(migrations.Migration): initial = True dependencies = [ ('sites', '0002_alter_domain_unique'), ('blog', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comments_count', models.IntegerField(default=0, editable=False)), ('keywords_string', models.CharField(blank=True, editable=False, max_length=500)), ('rating_count', models.IntegerField(default=0, editable=False)), ('rating_sum', models.IntegerField(default=0, editable=False)), ('rating_average', models.FloatField(default=0, editable=False)), ('title', models.CharField(max_length=500, verbose_name='Title')), … -
django the order of execution of codes that include save_m2m and os.popen?
python2.7 / I need to update the table of user,and select some invalid users into the file of data.txt. Now if I update the user named 'test_userA',and change the field of isvalid into False,but in the file of data.txt there is no the user named 'test_userA'. This is weird ! Beacuse in the database,the field of isvalid is false.And if I set the field of isvalid to True,same thing happened and in the file of data.txt there is the user named 'test_userA'. Why is the result contrary?? If someone knows this question,please show me some advice. Thank you! models.py class User(models.Model): userId = models.CharField(max_length=200,primary_key=True) isvalid = models.BooleanField(default=False, blank=True) updateTime = models.DateTimeField(default=timezone.now, null=False, blank=True) ss = models.ManyToManyField(SysA, blank=True) class UserForm(ModelForm): class Meta: model = User fields = '__all__' views.py @transaction.atomic def updateObj(request): userId = request.session['userId'] upUser = User.objects.filter(userId=userId); f = UserForm(request.POST, instance=upUser[0]); if f.is_valid(): try: newUser = f.save(commit=False) newUser.updateTime = timezone.now() newUser.save() f.save_m2m() with transaction.atomic(): newUser.ss.clear() for kj in request.POST['kjis'].split(','): newUser.ss.add(SysA.objects.get(sysId=kj)) '') os.popen("/test/test.sh" + " " +userId + " &>/dev/null").readlines() return HttpResponse("success") /test/test.sh #!/bin/bash -xv /test/manage.py query_user >/tmp/data.txt management/commands/query_user.py #coding: utf8 from django.core.management.base import BaseCommand, CommandError from test.models import * class Command(BaseCommand): def add_arguments(self, parser): pass def handle(self, *args, **options): for … -
How to create a database that saves data from raspberry pi in local PC in django?
I am running raspberry-pi that collects data from sensors. Now the data should be saved to the database that I have created using django in my PC. Both the raspberry-pi and my PC are connected locally in the same router. raspberry pi should simply send data to the database in my system and it should not create database by itself to save data. also If django code for complete process is provided, it will be satisfied as I am new to all these stuff. -
Store data from input in Django
Basically I'm new to django world and I'm trying to do smthing here I have made views.py def user(request): original = request.POST.get('originaltext', None) return render (request, 'posts/home.html', {'original' : original or ''}) and My urls.py from django.conf.urls import url from django.contrib import admin from posts import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/', views.user, name="home") and posts/home.html : <!DOCTYPE html> <html> <head> <title>Django Project</title> </head> <body> <h1>User Input</h1> <form action="{% url 'home' %}" method="POST"> <input type="text" name="originaltext" /> {% csrf_token %} <br /> <input type="submit" value="Try" /> <br /> <br /> <br /> <h3>Original</h3> {{ original }} the thing i want is when a user write something on input the informations stays on the same html page and when he types something else it's append to the list any suggestion guys ? -
Angular serve working, Angular build not updating files
I'm running a project with an Angular front-end and a Django back-end. Today when I changed some code in the templates the ng build didn't update. I have discovered that it neither updates template changes nor component changes. However, when I run ng serve instead and go to 127.0.0.1:4200 instead of the Django port 8000 the new updates versions are rendered. The way I have it set up is that I have a template that Django points to with TemplateViev : {% load static %} {% csrf_token %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>AngularWebapp</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <app-root></app-root> {% block javascript %} <script type="text/javascript" src="{% static 'runtime.js' %}"></script><script type="text/javascript" src="{% static 'polyfills.js' %}"></script><script type="text/javascript" src="{% static 'styles.js' %}"></script><script type="text/javascript" src="{% static 'vendor.js' %}"></script><script type="text/javascript" src="{% static 'main.js' %}"></script> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> {% endblock %} </body> </html> And the static directory layout looks like this in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'angular', 'static'), os.path.join(BASE_DIR, 'angular-webapp', 'dist', 'angular-webapp'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') Which is the only place I have static files, and which is where the files … -
Django ModuleNotFoundError: No module named 'myProject'
ModuleNotFoundError: No module named 'myProject' error, but I do not know the cause. I am glad if you tell me. ・ CentOS 7.2 ・ Python 3.6 ・ Django 2.0 ・ apache 2.4 I set the virtual environment as follows pip install virtualenv mkdir xxx cd xxx python3 -m venv xxx source xxx/bin/activate pip install mod_wsgi mod_wsgi-express module-config LoadModule wsgi_module "/home/username/myProject/myProject/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" WSGIPythonHome "/home/username/myProject/myProject" ■ /etc/httpd/conf.d/django.conf NameVirtualHost *:80 LoadModule wsgi_module /home/username/myProject/myProject/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so WSGIPythonHome /home/username/myProject/myProject WSGISocketPrefix /var/run/wsgi <VirtualHost *:80> ServerName xxx.com DocumentRoot /home/username WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess xxx python-home=/home/username/myProject/myProject python-path=/home/username/myProject/myProject/lib/python3.6/site-packages WSGIProcessGroup xxx WSGIScriptAlias / /home/username/myProject/myProject/wsgi.py <Directory /home/username/myProject/myProject/static> Require all granted </Directory> <Directory /home/username/myProject/myProject> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ■ wsgi.py import os,sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxx.settings") application = get_wsgi_application() -
Django Channels deny websocket connection with a custom code
So I need to deny a websocket connection with a specific code so the client can handle the rejection properly. Currently when you reject a connection with message.reply_channel({'accept':False}) the client simple gets a 403 error. I can close a connection with a code by using message.reply_channel({'close':3000}) but that requires for the connection to have been accepted in the first place. If that's the only way to do it then so be it but I feel like there should be a way to reject with a code that I simply can't find. I'm using Django Channels 1.1.8 so the 2.x release changes don't benefit me unfortunately. -
Django filter objects by CharField containing at most two words
I'm logging all user search queries in a model like this: class SearchLog(models.Model): query = models.CharField(max_length=512) datetime = models.DateTimeField(auto_now_add=True, db_index=True) To get all queries which has at most one word I make this queryset: SearchLog.objects.exclude(query__contains=" ") I want to get queries which has at most two words. is there anyway even with raw sql? -
Connecting MySQL Database to Heroku using Django
I'm having trouble connecting MySQL Database to Heroku. I followed this tutorial: https://devcenter.heroku.com/articles/cleardb. When I launch the web app, I get the error: Exception Type: OperationalError at / Exception Value: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") It seems that I am not properly telling django which database to use once I push it to heroku, and attempt to use their MySQL connector, ClearDB. I have the settings I included in my settings.py at the bottom. I also removed ?reconnect from the url before setting it as a variable as suggested by the documentation. Here is the full traceback. Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /app/profiles/templates/base.html, error at line 0 2002 1 : 2 : <!DOCTYPE html> 3 : {% load staticfiles %} 4 : 5 : {% block styles %} 6 : {% endblock %} 7 : 8 : 9 : <style type="text/css"> 10 : Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 216. self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect 194. self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/base.py" in get_new_connection 236. return Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/__init__.py" in Connect 86. return Connection(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py" in __init__ 204. super(Connection, self).__init__(*args, **kwargs2) The above exception ((2002, … -
POST to django REST endpoint with filtering
I have a django REST application, with a basic model as shown below: class Host(models.Model): hostname = models.CharField(max_length=80, unique=True, primary_key=True) datacenter= models.CharField(max_length=80, default="atlanta") status = models.CharField(max_length=80, default="live") ip_address = models.GenericIPAddressField(blank=True, null=True) At present, I can perform POST or PATCH operations on individual hosts, but these will all be named hosts within the JSON payload or in the URL itself. For example: POST /hosts/ [ { "hostname": "aragorn", "datacenter": "miami", "status": "live", "ip_address": "10.19.10.100" }, { "hostname": "gandalf", "datacenter": "miami", "status": "live", "ip_address": "10.19.10.110" } ] will create or update hosts aragorn and gandalf. I also support partial updates using PATCH/POST via hostname: PATCH /hosts/aragorn { "status": "dead" } I have a filter I use for GET requests. For example: GET /hosts?datacenter=miami&status=live Response: [ { "hostname": "gandalf", "datacenter": "miami", "status": "live", "ip_address": "10.19.10.110" } ] What I would also like to do is perform a PATCH to a subset of hosts, selected by a query filter in the URI, instead of naming the hosts explicitly either in the payload or in the URI. For example: PATCH /hosts?datacenter=miami&status=live { "status": "dead" } would set all the live hosts in the Miami datacenter to "dead" status (in this case, only gandalf). My question: … -
django-admin.py makemessages -l zh_CN no file was generated
this is my code this is output no language file generate -
Validate django form with a list of values from multiple CheckboxSelectMultiple
Using Django2.0, I have set up a form which displays all of my model objects in a list with check boxes. When this is submitted, in my request dict it stores them as a list of IDs. How do i validate these within the form? The clean() method does not get called. forms: class SampleRunSearchForm(forms.ModelForm): sample_run_id = forms.ModelChoiceField( label='Sample Run', queryset=SampleRun.objects.all(), widget=forms.CheckboxSelectMultiple, ) class Meta: model = SampleRun fields = ('sample_run_id',) def __init__(self, *args, **kwargs): super(SampleRunSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('sample_run_id', css_class='sample-run-display',), HTML('<br>'), Submit('submit', 'Report samples', css_class='upload-btn') ) self.helper.form_method = 'GET' def clean_sample_run_id(self): sr_id = self.cleaned_data.getlist('sample_run_id') for sr in sr_id: ... do something to validate... else: raise(forms.ValidationError('Error')) return(sr_id) views: class SearchSampleRun(View): samplerunform = SampleRunSearchForm template_name = 'results/samplerun_search_form.html' def get(self, request, *args, **kwargs): samplerunform = self.samplerunform() if request.GET: samplerunform = self.samplerunform(request.GET) samplerunform.is_valid() context = {'samplerunform': samplerunform} return render(request, self.template_name, context) It returns an error to my page that is it not a valid choice. the clean() method will also execute, but clean_sample_run_id() doesn't work - do i need to iterate through each ID and pass it through the form seperately for validation?! -
Django unable to handle % symbol in sql while using python's old style string formatting
I am using Django 2.0.5 and my (unchangable) legacy sqlite database has % symbol in a few column names. CREATE TABLE tbl("name" text, "col1(%)" float); When I use django model filters, the filter value is applied as a param to the sql string with % operator as: 'SELECT "col1(%)" from tbl where name LIKE "%s" ' % 'John%' Django is unfortunately not escaping the % symbol(in the column name) in such a scenario and this is causing an error at the string formatting option. Any suggestion on how to get around this? -
geodjango error importing LayerMapping
Setup: Windows 10 Python 2.7 Django 1.11 Standalone GDAL install gdal-202-1911-core.msi from gisinternals QGIS version 3 PostgreSQL 9.5 with Postgis 2.3 ERROR from django.contrib.gis.utils import LayerMapping Traceback (most recent call last): File "<interactive input>", line 1, in <module> ImportError: cannot import name LayerMapping I can open up the layermapping.py, the file is there. There needs to be something wrong with my setup here. what should I be doing to correctly import LayerMapping, why is this happening