Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post of data from ListBox is not being rendered to the database
I have an app that takes as one of the form fields a multiple listbox. The data is defined on the html page as "temp_groups", then in the view.py the form.cleaned_data['actual field'] is set to the extracted temp field. The data extracted appears correct (2,3) and looking at the same field after the form.save() is executed looks correct. But the data is not rendered to the database that way. It is using the value set on the actual "hidden" field on the html page. Here is the code Tried using the actual field name (group_members) but the result is only the last value selected from the list is actually posted. Also tried setting up a widget on the forms.py file where the data used in supplying comes from the query of the User object (auth_user). But this had no impact. url.py urlpatterns = [.. path('newgroups/', views.newgroups, name='newgroups'),.. forms.py class QueryGroupsForm(forms.ModelForm): class Meta: model = QueryGroups fields = ['group_name', 'group_desc', 'group_members', ] models.py class QueryGroups(models.Model): group_name = models.CharField(max_length=40, null=True, blank=True) group_desc = models.CharField(max_length=100, null=True, blank=True) group_members = models.CharField(max_length=100, null=True, blank=True) querygroups.html ... <div class="col-3"> <div class="form-group"> <label for="temp_members" class="" style="font-weight: bold;">Group Members<label> <select id="temp_members" name="temp_members" class="form-control" multiple="multiple"> {% for nextUser in … -
Django storages + Dropbox API: get files by name
I have a Django app set to use Dropbox to store media files with Django Storages package. It works fine and I can retrieve uploaded files. Now I want to do the following. I created a folder in Dropbox where I copied a bunch of PDF invoices manualy. In my database I have the invoice numbers, so I want to seek the corresponding file and show it. PDFs have the number as file name. I tried simple links using {{ MEDIA_ROOT }} but I get a path diferent tha the ones generated by Django Storages when files are uploaded. I´m not able to set the right path. Is there a way I can achieve this? Can I retrieve files by name using Django Storages and Dropbox API? Thanks! -
django rest framework dynamic url route
I'm currently doing a small project in Django (2.2.5) and djangorestframework (3.10.3). I'm having a problem getting the view connected to the router. I'd really appreciate a second pair of eyes to help me try to figure out what is wrong For the urls I have tried the following 2: router = routers.DefaultRouter() router.register(r'<chatroom>', views.ChatRoomViewSet) router.register(r'<str:chatroom>', views.ChatRoomViewSet) and then added the router to urlpatterns. The viewset is: class ChatRoomViewSet(viewsets.ModelViewSet): queryset = ChatRoom.objects.all().order_by('name') serializer_class = ChatRoomSerializer lookup_field = 'name' def get_viewset(self, request, name=None): name = self.kwargs.get('name', None) queryset = ChatRoom.objects.filter(name=name) return queryset And the serializer is class ChatRoomSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ChatRoom fields = ['url', 'name'] lookup_field = 'name' The model is: class ChatRoom(models.Model): name = models.CharField(max_length=255, default="") def __str__(self): return self.name Is there something I obviously missed? -
Show help for command from within Django management command
I want to show the output of manage.py <command> help if there are not enough meaningful args to execute the command. My code looks like: class Command(BaseCommand): def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def add_arguments(self, parser): parser.add_argument( 'args', metavar='item', nargs='*', help="item = 'users'|'data'|..." ) def handle(self, *args, **options): items = [x.lower() for x in set(args)] if not items: call_command('startapp', '--help') call_command() seems like an expensive way to call help. Is there a method that I can call on self that will do the same thing? -
How Do I Display The Category Name and Description?
How do I go about displaying the category name and short description from the category model onto the categories.html page? I ask this because I can't figure it out and I go the code from the internet so a little unclear how it works. So the code right now takes you to a page like example.com/cat-slug and then shows all the post under that category but how do I display the current category's name on that page (categories.html) as along with the category description too? models.py: class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): user = models.CharField(max_length=50, default=1) title = models.CharField(max_length=120) short_desc = models.CharField(max_length=50) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) tags = TaggableManager() content = models.CharField(max_length=1000) publish = models.DateField(auto_now=False, auto_now_add=False,) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] views.py: def show_category(request, hierarchy=None): category_slug = … -
Django prevent superuser from seeing data in /change/ page
I'm using Django 2.1.5 and have been using the list_display in ModelAdmin-based classes to limit what our superusers can see in the admin pages. There is some sensitive data that only the user should have access to. Say I have a app based on model SensitiveObject with id, name, secret, etc., I can simply exclude secret from the list_display and it will never show up in the Admin page. However, when I browse to /admin/full/myapp/sensitiveobject/ I will have a list of those object IDs and can simply go to /admin/.../sensitiveobject/<id>/change/ which will show all of the fields, including the ones that I excluded from list_display. Is there a way to limit what I'm seeing in the /change/ endpoint, as well? -
How To Solve An Error After I Install Python Manage.py Migrate?
I follow the tutorial from Traversy Media on Youtube videos. When i put the command python manage.py migrate Then i got such an error like this C:\Users\Acer\Project\djangoproject>python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\importlib\__ init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length( )) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\__init__.py", line 28, … -
Soft delete with unique constraint in Django
I have models with this layout: class SafeDeleteModel(models.Model): ..... deleted = models.DateTimeField(editable=False, null=True) ...... class MyModel(SafeDeleteModel): safedelete_policy = SOFT_DELETE field1 = models.CharField(max_length=200) field2 = models.CharField(max_length=200) field3 = models.ForeignKey(MyModel3) field4 = models.ForeignKey(MyModel4) field5 = models.ForeignKey(MyModel5) class Meta: unique_together = [['field2', 'field3', 'field4', 'deleted'],] The scenario here is that I never want users to delete data. Instead a delete will just hide records. However, I still want all non-soft-deleted records to respect unique key constraints. Basically, I want to have as many duplicated deleted records, but only a single unique un-deleted record can exist. So I was thinking to include "deleted" field (provided by django-safedelete library), but the issue becomes that Django's unique checks fail with "psycopg2.IntegrityError: duplicate key value violates unique constraint" for ['field2', 'field3', 'field4', 'deleted'] because NULL is not "equal to" NULL and it yields false in PostgreSQL. Is there a way to enforce a unique_together constraint with the Django model layout as mine? Or is there a better idea to physically delete the record, then move it to an archive database, and if the user wants the record back, then software will look for the record in the archive and recreate it? -
How can I use one database with multiple django servers?
I saw lots of information about using multiple databases with one server but I wasn't able to find contents about sharing one database with multiple servers. Using Micro Service Architectures, If I define a database and models in a django server, named Account, How can I use the database and models in Account server from another server named like Post?? What I'm thinking is to write same models.py in both servers and use the django commands --fake Then, type these commands python manage.py makemigrations python manage.py migrate and in another server python manage.py makemigrations python manage.py migrate --fake I'm not sure if this would work and I wonder whether there is any good ways. -
CRITICAL WORKER TIMEOUT
I am building an app with Docker, Django and Postgresql. I was trying to parse thourhg rows in an excel file (about 7000 rows) and got this error: web_1 | [2019-09-26 23:39:34 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:11) web_1 | [2019-09-26 23:39:34 +0000] [11] [INFO] Worker exiting (pid: 11) web_1 | [2019-09-26 23:39:34 +0000] [12] [INFO] Booting worker with pid: 12 I searched for solution and found a suggestion to increase the TIMEOUT but I don't know where to find it. Here is my yml files. version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn bookstore_project.wsgi -b 0.0.0.0:8000 # new environment: - SECRET_KEY=<secret_key> - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: docker-compose-prod-yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=<Secret_key> - DEBUG=0 ports: - 8000:8000 depends_on: - db db: image: postgres:11 heroku.yml: setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore_project.wsgi Any help is appreciated! Huy. -
Unable to update Django object when declaring only one field in template form
For some reason I can't seem to update my Django models object when declaring only one of its field versus all fields in the template form. Here are two cases that should seemingly get the same results but do not. When I pass the whole form to the template as so: {{ form.as_p }} the whole object updates. Whereas when I pass a single field to the template: {{ form.field }} the object doesn't seem to get updated. If you look at my views file this should not matter because the form is being passed the object instance. Therefore it should not matter if all fields are specified in the templates form because they should have already been passed to the form through the object instance. object_instance=get_object_or_404(object,pk=pk) if request.method=="POST": form=Form(request.POST,instance=object_instance) if form.is_valid(): new_object=form.save(commit=False) new_object.method() new_object.save() return redirect('results',pk=new_object.pk) else: form=Form(instance=object_instance) return render(request,'template.html') Please tell me where I am going wrong. I do not see why I can't update an object by rendering a template that displays only a single field from the objects form. -
How to configure Nginx and Django to redirect from http to https?
Sorry for the general asking. I encountered an wired problem when setting up https for a web server. It holds a website Using Nginx. The website files are generated by Django. I have already got the certificate. I configure it for Nginx: server{ listen 80; server_name: example.com; return 301 https://$host$request_uri; } server{ listen 443 ssl default server; listen [::]:443 ssl default_server; ssl_certficate /location/to/certificate/certificate.cer ssl_certificate_key /location/to/key/key.pem } It can be reached by https://example.com up to now. However, the problem is: When in the http version, there is a button, which I click it, it will show an login page with the http://hr.example.com/login in the address bar. However, after I configuring ssl for it, there is no login page , it only shows the homepage again with the https://hr.example.com/ showing in the address bar (in the http version, this address is also shown in the address bar after click the button before the login page appearing). If I manually added the /login after https://hr.example.com/, it will show the page: page not found 404 and the folowing info Using the URLconf defined in splash.urls, Django tried these URL patterns, in this order: [name='index'] <int:instance_id>/ [name='detail'] admin/ The current path, login, didn't match any … -
Django templates unexpectedly omit results from Elasticsearch
Django templates seemed to omit part of results returned by Elasticsearch_dsl. The Elasticsearch low-level python client works fine. If it is just {{source}} without "for loops", it works fine as well. The code is simply: {% for item in source %} {{item}} {% endif %} Expected results rendered by Django templates: {'_index': 'search', '_type': '_doc', '_id': '1', sentence:'abc'} Actual results: {'_index': 'search', '_type': '_doc', '_id':...} Any help will be appreciated. -
How Do I Display The Right Category Name and Description For That Category Page?
I was wondering how I can display the category name and short description from the category model onto the categories.html page? I ask this because I can't figure it out and I go the code from the internet so a little unclear how it works. So the code right now takes you to a page like example.com/cat-slug and then shows all the post under that category but how do I display the current category's name on that page as along with the category description too? models.py: class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): user = models.CharField(max_length=50, default=1) title = models.CharField(max_length=120) short_desc = models.CharField(max_length=50) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) tags = TaggableManager() content = models.CharField(max_length=1000) publish = models.DateField(auto_now=False, auto_now_add=False,) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] views.py: def show_category(request, hierarchy=None): category_slug = … -
Applied CSS causes anchors to be unclickable
I have come across a very odd issue, I have noticed that all of a sudden my anchors stopped working, as in became unclickable. Then I figured it must be something related to applied CSS, and when I started disabling parts of my CSS, I narrowed down the issue to this couple of lines: .content { width: 960px; margin: auto; } My page structure looks like this: <!DOCTYPE html> <html> <head> <title>CoinShop v1.0</title> <link rel="stylesheet" type="text/css" href="/static/pages/css/reset.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/navbar.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/base.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/searchbar.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/static/products/css/detail.css"> </head> <body> <div class='top-grid'> <div class='branding-grid-container'> <div class='branding-grid'> <div class='branding-grid-buttons-not-authenticated'> <a href="/help/" class='button-help'>Help</a> <a href="/accounts/register/" class='button-register'>Register</a> <a href="/accounts/login/" class='button-login'>Login</a> </div> </div> </div> <div class='nav-grid'> <div class='search-bar'> <form action="/shop/" method="GET"> <input type="text" name="q" placeholder="Search" class='search-box'> <input type="submit" value='Search' class='search-button'> </form> </div> <div class='nav-bar'> <nav> <ul id='menu'> <li class='menu-item'><a href="/">Home</a></li> <li class='menu-item'><a href="/shop">Shop</a></li> <li class='menu-item'><a href="/contact">Contact</a></li> <li class='menu-item'><a href="/about">About</a></li> </ul> </nav> </div> </div> </div> <div class='content'> <a href="/shop/1/">spam (2018)</a> <h1>spam (2018)</h1> <p>eggs</p> <p>Price: 200.00</p> </div> </body> </html> ...and all applied CSS combined looks like this: .top-grid { margin: auto; background-color: #3D005A; } .branding-grid-container { background-color: #4e0e7c; } .branding-grid { display: grid; grid-template-columns: 1fr 1fr 400px; … -
Update Django backend and angular fronted with rest framework
I'm trying to edit data stored in Django(backend) and angular(fronted), I have the insert and delete but I don't have an idea, how I can edit that data in Django from angular, I using in Django rest_framework. getUsuarios(): Promise<Usuario[]> { return this.http.get('http://127.0.0.1:8000/users?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Usuario[]) } deleteUsuario(id: number): Promise<void> { const url = `${"http://127.0.0.1:8000/users"}/${id}`; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(() => null) } createUsuario(d: Usuario): Promise<Usuario> { return this.http .post("http://127.0.0.1:8000/users/", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Usuario) } urlpatterns = [ url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor/(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), url(r'^paciente$', views.PacienteList.as_view()), url(r'^paciente/(?P<pk>[0-9]+)$', views.PacienteDetail.as_view()), url(r'^categoria$', views.CategoriaList.as_view()), url(r'^categoria/(?P<pk>[0-9]+)$', views.CategoriaDetail.as_view()), url(r'^examen$', views.ExamenList.as_view()), url(r'^examen/(?P<pk>[0-9]+)$', views.ExamenDetail.as_view()), path(r'api-token-auth/', obtain_jwt_token), path(r'api-token-refresh/', refresh_jwt_token), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
Multiple Ajax request fails after one of the requests successfully processed
I have a form to upload a picture and to do certain process on it. Since the process is time consuming I don't want to wait for the response but should be able to submit next form. In my case I am able to submit multiple form from the same web page one by one. But this issue is, when one of the request process successfully it throws an error like "Exception happened during processing of request from ('127.0.0.1', 55522)" and thus remaining process stops in the middle. I am using Djnago framework with Ajax request for this. -
How To Use Django-AutoComplete-Light Outside of Admin
I am trying to use django-autocomplete-light to create dependent dropdowns in my project as described in the 'Filtering results based on the value of other fields in the form' section of the following documentation. I am reading the docs here: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html However, I can only find examples of how to make this work in django admin. I want this to be in my form. Can someone please clarify for me if it is possible to use django-autocomplete-light outside of the admin, and if possible provide a link to an example? -
How to filter a ModelChoiceField for an InlineFormset that is nessted?
In my forms.py, I want the referenceBFlow with the modelchoicefield to only have the related BasicFlow. Currently, all the BasicFlows are being returned when I used queryset=BasicFlow.objects.all(). I would like to know how to filter the query dynamically. For instance: If I have a profile (prof1) and basicGroup (bg1), basicflow (bf1, bf2, bf3...), AltGroup (ag1). Now, in my template, if I click on the dropdown for the referenceBFlow for ag1, it should have basicflow (bf1, bf2, bf3...). If another profile, profile (prof2) and basicGroup (bg2), basicflow (bf4, bf5, bf6...), AltGroup (ag2), the referenceBFlow for ag2 should have basicflow (bf4, bf5, bf6...). models.py - class Project(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) ... class Profile(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) ... class B_FlowGroup(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) class BasicFlow(models.Model): basicflGroup = models.ForeignKey(B_FlowGroup, on_delete=models.CASCADE, null=True, blank=True) ... class A_FlowGroup(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) referenceBFlow = models.ForeignKey('BasicFlow', on_delete=models.CASCADE, null=True, blank=True) class A_Flow(models.Model): altflGroup = models.ForeignKey(A_FlowGroup, on_delete=models.CASCADE, null=True, blank=True) ... forms.py - In this .py I have nested and regular inlineformsets class B_FlowGroupForm(ModelForm): class meta: model = B_FlowGroup class AltFlowGroupForm(ModelForm): class meta: model = AltFlowGroup referenceBFlow= forms.ModelChoiceField(widget=forms.Select, queryset=BasicFlow.objects.all()) class BasicFlow(ModelForm): class meta: model = BasicFlow BasicFlowFormSet = inlineformset_factory(B_FlowGroup, BasicFlow, form=BasicFlowForm, extra=1) … -
Customizing Django's error email reporting
Prior to Django 2.2, I was using a custom middleware to catch and email all error reports, including a lot of useful information, including server name and Python traceback. In Django 2.2, similar functionality is now enabled by default. Unfortunately, it's not quite as verbose as I'd like, and it overrides my custom middleware, so now I'm getting less information. Despite the doc's claims, Django's error email does not include the Python traceback nor the error from the exception. All emails are titled "Internal Server Error" and just contain a URL and the GET and POST dictionaries. You can imagine how frustrating it is to diagnose the error "Internal Server Error" with little more than a URL. How do you disable Django's custom error emailer? The docs claim it's enabled and configured by the logging settings, but even if I remove all references to django.utils.log.AdminEmailHandler in my logging configuration, Django still sends the default error emails instead of using my middleware. Alternatively, is there any way to fix the email content so it includes something useful? This is my current logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' … -
How to update FileField filename after it's saved in Django and using S3 as the storage
I have a model that has a FileField. I want to save a generated file content before I send it to a 3th party service, after I have the response, I would like to rename it without changing the content. I think the code below would generate another file on S3 instead of renaming it to the final name. class SomeModel(models.Model): record = models.FileField() model.record.save('initial_filename', ContentFile(generated_content)) model.record.save('final_filename', model.record.read()) -
What is the recommended NOSQL database for Django Framework?
I am working on building software for analytics, I want to choose NoSQL database for my application database system. I am thinking about -
Trying to group C3.JS scatter chart Y values by X step
I am creating a metrics page for workflow and I have been asked to create a jittered scatter plot chart, that shows per step (x) how many records where there (each scatter) and how long did they take (y). This is something that is fairly easy to do in JMP but I have had a difficult time figuring out how to do it with C3.js. I have looked at examples from D3, c3 and charts.js outliersScatter = c3.generate({ bindto: '#outliersChart', data: { columns: [ ["FIDB_UPDATE", 0,1,2,3,4,5], ["SSD_BIZOPS", 5,4,3,2,1,0], ], type: 'scatter' }, axis: { x:{ tick: { rotate: -45, multiline:false, culling: { max: 1 }, } }, y: { label: 'Time' } } }); I get a chart but they are not grouped by the column names, so ideally, The X would have FIDB_UPDATE listed as the x tick, and above it would be 6 plots at a y access of 0,1,2,3,4, and 5 (see example image from JMP) -
ways to speed up .txt to db in django
I have a text file like this: AN AD Aixas AN AD Aixirivall AN AD Aixovall AN AD Ansalonga And I want to import this text file to the database. I am doing it like this. fips_codes = [] iso_codes = [] city_names = [] for line in city_file.readlines(): cc_fips = line[:2] cc_iso = line[3:5] name = line[6:] fips_codes.append(cc_fips) iso_codes.append(cc_iso) city_names.append(name) counter = 0 for item in fips_codes: country = Country.objects.get(cc_fips=fips_codes[counter], cc_iso=iso_codes[counter]) city_object = City(country=country, name=city_names[counter]) city_object.save() counter = counter + 1 is there any way to speed up this process? -
Testing checkbox in Django as field in form
I have a form with a single field which is a two level checkbox, if I select parent checkbox while no children selected, the parent with all children items will show in my json data after submit. I want to write a test to test this. I'm new to Django test, after reading Django documents, still struggle on manipulating the checkbox. My form looks like this: class RerunForm(forms.Form): items = ItemStatus( queryset=models.Container.objects.none(), widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')), help_text="Select items that you want to rerun.", ) def __init__(self, rerunqueryset, *args, **kwargs): super(RerunForm, self).__init__(*args, **kwargs) self.fields['items'].queryset = rerunqueryset class ItemStatus(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return "{} ({})".format(obj.name, obj.state) rerunqueryset is passed from view, which is like this <QuerySet [<Container: AT1>, <Container: AT1_1>, <Container: AT1_2>, <Container: AT1_3>, <Container: AT1_4>, <Container: AT2>, <Container: AT2_1> My page looks like this: In my django test, I want test: 1. check parent level item while no children checked, parent and all children names will show in json after submit 2. check parent level item, and any children item, only checked children show in json data after submit. Till now, I have codes like client and context to access my checkbox label, my question is how do I set certain checkbox to 'checked', …