Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove default view permission in Django?
Trying to remove a view permission after 24 hours. Since view is now a default permission, I'm not sure how to add and remove it. I want to assign it when the model object Purchase is updated and attach it to a user and then remove it after 24 hours. I'm using guardian "remove_perm", but not working. # middleware.py from guardian.shortcuts import remove_perm class PremiumMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user = request.user u_p = Purchase.objects.get_object_or_404(user=user).values_list("datetime_done") if u_p.datetime_done != "": if u_p.datetime_done > datetime.datetime.now(): remove_perm('view', user, Purchase) return response Then, I get this error. I'm just not sure how to remove this default "view" permission and add it properly. 'Manager' object has no attribute 'get_object_or_404' -
Manifest: Line: 1, column: 1, Syntax error on Chrome browser
I have a react app that built through npm run build. GET and POST request from the front-end to back-end gives status 200 but I am getting a weird error that may cause all the images from my files not appear on localhost. I have already tried to reinstall node, added 'manifest_version': 2 as it is the current version of chrome manifest. Manifest: Line: 1, column: 1, Syntax error. Below is my index.html file <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><title>Django React Boilerplate</title><link href="/static/css/2.87ad9c80.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(l){function e(e){for(var r,t,n=e[0],o=e[1],u=e[2],f=0,i=[];f<n.length;f++)t=n[f],p[t]&&i.push(p[t][0]),p[t]=0;for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(l[r]=o[r]);for(s&&s(e);i.length;)i.shift()();return c.push.apply(c,u||[]),a()}function a(){for(var e,r=0;r<c.length;r++){for(var t=c[r],n=!0,o=1;o<t.length;o++){var u=t[o];0!==p[u]&&(n=!1)}n&&(c.splice(r--,1),e=f(f.s=t[0]))}return e}var t={},p={1:0},c=[];function f(e){if(t[e])return t[e].exports;var r=t[e]={i:e,l:!1,exports:{}};return l[e].call(r.exports,r,r.exports,f),r.l=!0,r.exports}f.m=l,f.c=t,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(r,e){if(1&e&&(r=f(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var n in r)f.d(t,n,function(e){return r[e]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var r=window.webpackJsonp=window.webpackJsonp||[],n=r.push.bind(r);r.push=e,r=r.slice();for(var o=0;o<r.length;o++)e(r[o]);var s=n;a()}([])</script><script src="/static/js/2.e5ee7667.chunk.js"></script><script src="/static/js/main.9f678b97.chunk.js"></script></body></html> It appeared that the error starts from the beginning of my index.html file. -
List users connected to django-channels Group (channels 1.x)
So, I got as far as finding the group_channels function, but this doesn't seem to store user info. Example: channel_layer = get_channel_layer() context['players_list'] = channel_layer.group_channels('lobby') I get {'players_list': ['daphne.response.WbZyUfNixL!sbzfJEzdPp', 'daphne.response.KfDHQnHLdw!DpoOqdGute', 'daphne.response.JqlcVVMuny!xHLDSaCzUz', 'daphne.response.mWrYVXDKoI!AjkyadSsPe']} as a response. How can I list users connected to Group('lobby')? Thanks in advance -
How to add content_panels when I edit Page
I am developing my wagtail blog site. I want to add the feature what SnippetChooserPanel is shown dynamicaly. When I create a Blog editing page, I want to edit 1/3 SnippetChooserPanel. When I edit a Blog editing page, I want to edit 3/3 SnippetChooserPanel. However, I could not resolve it... I removed 2 SnippetChooserPanel,"B" and "C" in blog/models.py. I can edit only "A" SnippetChooserPanel -> it is OK. I added code in blog/wagtail_hooks.py -> However, SnippetChooserPanel could not see. It is blog/models.py content_panels = Page.content_panels + [ MultiFieldPanel( [ SnippetChooserPanel("A"), # SnippetChooserPanel("B"), # SnippetChooserPanel("C"), ], heading=_("ABC information"), ), ] It is process of 2 and blog/wagtail_hooks.py. If I added @hooks.register("before_edit_page") ... ... Page.content_panels = Page.content_panels + [ MultiFieldPanel( [ SnippetChooserPanel("B"), SnippetChooserPanel("C"), ], heading=_("ABC more information"), ), ] ... ... I can not do it well.. Does anyone can help me? -
How do I serve dynamic images in Django?
I have a Django app that pulls images from emails and creates thumbnails that I want to display in a view. Since these are not static files, and not files uploaded by users, where should I store them and how do I get a URL that can be placed into the src tag so the client browser will download it? I'd like to be able to have the view display the image from a template with code something like this: <img src="{{ path }}" /> where path evaluates to the URL of the image file. I'm fairly new to Django so I'm sure I must be missing something obvious. -
The 'X-Accel-Redirect' option does not work on Windows
I'm developing on Windows and trying to deploy to Ubuntu. But I found a problem here. If you look at the source code below, it works well on Ubuntu, but on Windows you can see that the file contents are empty. What's the suspected problem? (The code below can download the file validly. parent == dir, filename == filename + extension) @login_required def download_file(request, parent, filename): response = HttpResponse() response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) response['X-Accel-Redirect'] = '/static/download/{0}/{1}'.format(parent,filename) print(response['X-Accel-Redirect']) return response -
How do I updated my Django database only when new scraped information is seen?
I have a project that I need to create where when a user navigates to the index page, it displays the current news that python scrapes from a website and add it to my models database and then pass it through as a context to my html template. What I have done is in my views.py file is upon the index page request, python goes to scrape the information and adds it to my database but it does this every time the user makes a GET request to this url. How can I make it so that python is only scraping and updating the database when there’s new news in the website that it’s scraping from and not just adding to the database pre-existing elements -
How to get radio button value from FORM in view.py file
I wanna get the radio button value in view.py file, I'm getting all the values except for radio button value I tried to get data using POST and GET method but both didnt work for me //code Rating 1 2 3 4 5 TypeError at /reservation User() got an unexpected keyword argument 'radoption' -
How to do Exact query Django-Haystack
I'm trying to fix my Django-haystack search results to only return outputs of the exact query. The principal usecase is that a user enter is destination and get only the results that matches this given place. But the problem I have now is that when a user try for example, a query for "Mexico", the search results also returns information in "Melbourne" which is far from being user-friendly and accepted. I just don't know what to try anymore, I've been stuck with this problem since the beginning of the week. Please help. Here's my code: My forms.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', '') super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs My search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from .models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') title = indexes.CharField(model_attr='title') description = indexes.EdgeNgramField(model_attr="description") destination = indexes.EdgeNgramField(model_attr="destination") #boost=1.125 link = … -
Unable to generate post request django class based view with parameters (TemplateResponsemixin, View)
I am not sure why but the post request of this view return Method Not Allowed (POST): / in the terminal and a error 405 on the webpage. views.py class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'core/manage/module/formset.html' course = None def get_formset(self, data=None): """ Create a ModuleFormSet object for the given Course object with optional data. """ return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course':self.course,'formset':formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('core:manage_course_list') return render(request, self.template_name, {'course': self.course,'formset': formset}) urls.py path('<pk>/module/', views.CourseModuleUpdateView.as_view(), name='course_module_update'), forms.py ModuleFormSet = inlineformset_factory(Course, Module, fields=['title','description'], extra=2, can_delete=True) Any help would be much appreciated. -
Create a CRUD using Django Class-based for a multi-step form?
Is it possible to create a CRUD using Django Class-based (CreateView, ListView, etc ...) for a multi-step form? If not, would anyone have an example of a CRUD of a multistep form? Thanks if anyone helps, I have no idea how to handle this kind of form in Django. -
Is it possible to click a button on a html page from a separate html page?
I have two custom html pages: 'first.html' and 'second.html'. In 'second.html' I have a hidden div. I want to click a button on 'first.html' that will unhide the div in 'second.html'. I want both pages to be open at the same time in different windows/tabs. This is a Django project so I tried to create a def in views.py that will open 'second.html' when the button on 'first.html' is opened. Doing this will just open 'second.html', but I need both pages to be opened at the same time. -
Cannot access to Django admin page with valid username and password in Chrome. But in firefox, it works fine
During an Udemy lecture, I tried to access the Django admin page, but I couldn't enter the page with valid userID and password in chrome. Also, the stylesheet is not applied to the index page. However, in FireFox, it perfectly works. Is there any special thing I should do for Chrome? Please let me know what I do for Chrome. Here are my codes which are setting.py and views.py Thanks in advance in views.py from django.shortcuts import render from django.http import HttpResponse from first_app.models import AccessRecord, Topic, Webpage def index(request): webpages_list = AccessRecord.objects.order_by('date') date_dict = {'access_records': webpages_list} # my_dict = {'insert_me' : "I am from views.py in first_app"} # return render(request, 'first_app/index.html', context=my_dict) return render(request, 'first_app/index.html', context=date_dict) in setting.py """ Django settings for first_project project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR=os.path.join(BASE_DIR, "static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a=@bj_n7#+65&sop)#o=5nm^po8j35d@c)e#ca)85#i(_wjdz6' # SECURITY … -
Row Select Not Working in Django Using JS
I have a table, in which I would like the user to be able to select rows - i.e. upon clicking on the row, it would become active. I took some javascript example from online and amended it to my code, but it is still not working. Any advice what I need to change? I used active instead of selected because bootstrap is being leveraged in this example. .html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="50%"> <thead> <tr> <th></th> <th style="width:3%;">Reference</th> <th style="width:7%;">Ultimate Consignee</th> <th style="width:7%;">Vessel</th> <th style="width:7%;">Booking #</th> <th style="width:5%;">POL</th> <th style="width:15%;">DOL</th> <th style="width:5%;">POE</th> <th style="width:5%;">Pickup #</th> <th style="width:5%;">Sales Contact</th> <th style="width:5%;">Trucking Co</th> <th style="width:2%;">Total Cases</th> <th style="width:2%;">Total FOB</th> <th style="width:5%;">Freight Forwarder</th> </tr> </thead> <tbody> {% for orders in orders %} <tr> <td> <a href="{% url 'edit_shipment' orders.pk %}" class="btn btn-default btn-sm" role="button">Edit</a> </td> <td>{{ orders.reference }}</td> <td>{{ orders.ultimate_consignee }}</td> <td>{{ orders.vessel }}</td> <td>{{ orders.booking_no }}</td> <td>{{ orders.POL }}</td> <td>{{ orders.DOL }}</td> <td>{{ orders.POE }}</td> <td>{{ orders.pickup_no }}</td> <td>{{ orders.sales_contact }}</td> <td>{{ orders.trucking_co }}</td> <td>{{ orders.total_cases }}</td> <td>{{ orders.total_fob }}</td> <td>{{ orders.freight_forwarder }}</td> </tr> {% endfor %} </tbody> </table> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <script src="jquery.min.js"></script> <script src="jquery.fulltable.js"></script> <script … -
No Processed matches the given query,Pk returning weird errors?
I'm working on a Django project where users can add patients and patients can have images uploaded by users and these images can have processed images. so I made a list view has a simple detail view containing the patient data and the uploaded images but whenever I try making a navigation link to the processed images I get weird errors like No Processed matches the given query and Reverse for 'result' with arguments '('',)' not found. 1 pattern(s) tried: ['patients/result/(?P[0-9]+)$'] and when i enter the link manully There's no images appear , and to keep in mind I render the processed images the same way that the uploaded images is rendered but both of them isn't similar in how are they refered to in the admin as one of them is assigned by path. The first is uploaded by a normal form and the second is assigned by a function that returns a path. models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages, on_delete=models.CASCADE,related_name='processed') analysedimage = models.ImageField(upload_to=analyses_directory_path,blank=True) views.py def ResultDetails(request, pk=None): result = get_object_or_404(models.Processed,pk=pk) context = { 'result' : result } template = "patients/album.html" return render(request,template,context) template … -
Celery + Locks = Bad Runtime
I'm using Celery with my Django project. I use redis to lock tasks to one-at-a-time. This results in a totally wrong runtime (3 tasks received, 10 seconds each means the last one will have a runtime of 30s because it's from when task was received and not from when the task was run). How can I set the time celery starts counting runtime from manually? -
How to Handle When Request Returns None
I have a list of IDs which corresponds to a set of records (opportunities) in a database. I then pass this list as a parameter in a RESTful API request where I am filtering the results (tickets) by ID. For each match, the query returns JSON data pertaining to the individual record. However, I want to handle when the query does not find a match. I would like to assign some value for this case such as the string "None", because not every opportunity has a ticket. How can I make sure there exists some value in presales_tickets for every ID in opportunity_list? Could I provide a default value in the request for this case? views.py opportunities = cwObj.get_opportunities() temp = [] opportunity_list = [] cw_presales_engineers = [] for opportunity in opportunities: temp.append(str(opportunity['id'])) opportunity_list = ','.join(temp) presales_tickets = cwObj.get_tickets_by_opportunity(opportunity_list) for presales_ticket in presales_tickets: try: if presales_ticket: try: cw_engineer = presales_ticket['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' -
django-pyodbc: my odbc driver on my old machine worked but now I'm getting a error saying my driver "doesn't support modern datatime types"
I'm trying to develop an app in Django. I recently got a new work machine and that is the only thing that has changed. My last computer was running Windows 7. The server is running Windows 7 enterprise. My new computer is running Windows 10 pro. My database is being run in SQL Server 2012. I'm using the django-pyodbc-azure package. Error: django.core.exceptions.ImproperlyConfigured: The database driver doesn't support modern datatime types. here's my database setup: DATABASES = { 'default': { 'NAME': 'auth', 'HOST': 'x.x.x.x', 'PORT': '', 'ENGINE': 'sql_server.pyodbc', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, }, 'EZCORP': { 'NAME': 'database', 'HOST': 'x.x.x.', 'PORT': '', 'ENGINE': 'sql_server.pyodbc', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'dsn': 'mydsn', }, }, } -
What are the practical differences between django-python3-ldap and django-auth-ldap?
I have a functioning Django REST Framework project, which uses basic and JWT authentication. I'd like to add LDAP support to the project, but I found two very similar packages: django-python3-ldap Depends on ldap3 django-auth-ldap Depends on python-ldap We need to support Python 3.6, 3.7, and PyPy3.6 on Linux, macOS, and Windows. Both packages seem to do the same job and both seem to still be maintained. What are the practical considerations or functional differences between these two packages? Are there important features that one has over the other? Does one integrate better with Django REST Framework than the other? -
Django login and functioning
I am really new to Django and I am trying to make a little Time Attendance application. However, I am a bit confused. I've always heard that Django is the go-to for new developers but I think I'm doing something wrong here. I want to understand how Django works. More specifically, I would really appreciate help if you guys could help me understand the follow: So, I've watched countless YouTube videos regarding Django. In all of them, people put path("login/", LoginView.as_view(template_name='folder/htmlLoginFile.html'), name="loginNameForThatView") in their app's urls.py inside the urlpatterns. Then they proceed to edit their htmlLoginFile.html, put a form inside it with a post method and in there, they ptthese two lines {% csrf_token %} {{ form.as_p }} and running that server and going to that link shows a magical login form that actually works. What everyone fails to mention is a) How the back-end works. How does it read the data inside the input tags of that form, how Django actually receives data from the input tags in HTML. b) How does one make their own forms and how do they connect their forms to their own databases. I understand that this may be a lot to ask but … -
Conntect Django with sql server
How can i connect My proyect Django in visual studio to my sql server with SQL server Authentication. Python 3.7 Django 2.2.4 -
how continuously run function on page request
I want to use third party's REST API providing real-time foreign exchange rates in my django app which should continuously show changing exchange rates. my code works but only on every page reload. but I want my code to be running continuously and showing exchange rate on page even if the page is not reloaded def example(request) RATE__API_URL = 'REST API url' while True rate = requests.get(RATE__API_URL).json() b = rate['rates']['EURUSD']['rate'] context = {'b': b} return render(request, 'example.html', context) code is running and does not show any errors -
Django calling model save twice producing index error
I have the following code for generating thumbnail. def make_thumbnail(dst_image_field, src_image_field, size, name_suffix, sep='_'): """ make thumbnail image and field from source image field @example thumbnail(self.thumbnail, self.image, (200, 200), 'thumb') """ # create thumbnail image image = PImage.open(src_image_field) image.thumbnail(size, PImage.ANTIALIAS) # build file name for dst dst_path, dst_ext = os.path.splitext(src_image_field.name) dst_ext = dst_ext.lower() dst_fname = dst_path + sep + name_suffix + dst_ext # check extension if dst_ext in ['.jpg', '.jpeg']: filetype = 'JPEG' elif dst_ext == '.gif': filetype = 'GIF' elif dst_ext == '.png': filetype = 'PNG' else: raise RuntimeError('unrecognized file type of "%s"' % dst_ext) # Save thumbnail to in-memory file as StringIO dst_bytes = BytesIO() image.save(dst_bytes, filetype) dst_bytes.seek(0) # set save=False, otherwise it will run in an infinite loop dst_image_field.save(dst_fname, ContentFile(dst_bytes.read()), save=False) dst_bytes.close() class Image(models.Model): path = models.ImageField(upload_to=photo_image_upload_path,blank=False, null=False) thumb = models.ImageField(upload_to='', editable=False, default=None, null=True) def save(self, *args, **kwargs): # save for image super(Image, self).save(*args, **kwargs) print("#1") ext = self.path.name.split('.')[-1] make_thumbnail(self.thumb, self.path, (150, 150), 'thumb') print("#2") # save for thumbnail and icon super(Image, self).save(*args, **kwargs) print("#3") This leads to the output: #1 #2 duplicate key value violates unique constraint "media_image_pkey" DETAIL: Key (id)=(7) already exists. The image is uploaded to this model through a primary model and references … -
Django Admin throwing "generator StopIteration" error while creating User
I have defined a custom user model by extending the django's AbstractUser. So when i try to create the user from djano admin page it get the generator stopiteration error. Below is the trace back. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/users/user/add/ Django Version: 1.8 Python Version: 3.7.3 Installed Applications: ['posts.apps.PostsConfig', 'users.apps.UsersConfig', 'common.apps.CommonConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/core/handlers/base.py" in get_response 125. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/middleware/csrf.py" in process_view 174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/core/handlers/wsgi.py" in _get_post 137. self._load_post_and_files() File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/request.py" in _load_post_and_files 260. self._post, self._files = self.parse_file_upload(self.META, data) File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/request.py" in parse_file_upload 225. return parser.parse() File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/multipartparser.py" in parse 149. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/multipartparser.py" in __iter__ 628. yield parse_boundary_stream(sub_stream, 1024) File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/multipartparser.py" in parse_boundary_stream 567. chunk = stream.read(max_header_size) File "/home/rohit/.virtualenvs/django-env/lib/python3.7/site-packages/django/http/multipartparser.py" in read 337. out = b''.join(parts()) Exception Type: RuntimeError at /admin/users/user/add/ Exception Value: generator raised StopIteration This only happens when creating the user with Django Admin, otherwise from django shell it works just fine. This is how my Custom User model looks like class User(AbstractUser): description = models.TextField('profile summary', null=True, blank=True) location = models.CharField('Location', max_length=50, null=True, … -
Django multiwidget for CharField form field
I'm trying to understand how to write a multiwidget for a form field in Django. I have a checkbox field and then a CharField which I would like to enable/disable with Javascript based on whether the checkbox field has been selected, so am trying to add an 'id' to both fields. I understand that this requires a multiwidget but I'm struggling to understand how to go about this. from django import forms PRIORITY_CHOICES = [('high', 'High'), ('low', 'Low')] class UploadForm(forms.Form): gender_select = forms.BooleanField(label='Even Gender Distribution', required=False, widget=forms.TextInput(attrs={'id':'gender_select'})) gender_priority = forms.CharField(label='Select Priority', required=False, widget=forms.Select(choices=PRIORITY_CHOICES)) Just like the 'gender_select' field, I need to add the following to 'gender_priority': forms.TextInput(attrs={'id':'gender_priority'}) but as far as I understand, I can only include one widget. How would I go about including more than one?