Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invalid literal for int() with base 10: - django - python
I was trying to make the author of a news be automatically picked when the news is created. This is my code: Model: from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class News(models.Model): news_title = models.CharField(max_length=420, help_text="Insert only the news title, be specific and short!") pub_date = models.DateTimeField('date published') article_text = RichTextField() news_author = models.CharField(User, max_length=250, editable = False, default='unknown') class Meta: ordering = ["news_title", "-pub_date"] verbose_name = "News" verbose_name_plural = "News" def get_absolute_url(self): return reverse('model-detail-view', args[str(self.id)]) def __str__(self): return self.news_title Admin: from django.contrib import admin # Register your models here. from .models import News admin.site.site_header = "SoLS UCP Admin Panel" class NewsAdmin(admin.ModelAdmin): list_display = ('news_title', 'pub_date', 'news_author') def save_model(self, request, obj, form, change): if getattr(obj, 'news_author', None) is None: obj.news_author = request.user obj.save() admin.site.register(News, NewsAdmin) The thing is that I put null = True to the author and the database fucked up the old news, so I removed and applied a default on it but I got this error.. so I deleted all older news directly from phpmyadmin, but no success, the error is still there: ValueError: invalid literal for int() with base 10: 'andrei' There are also more before … -
dyld: Library not loaded: @rpath/libpython3.6m.dylib
Trying to use uWSGI + nginx with Django, but getting the following error: dyld: Library not loaded: @rpath/libpython3.6m.dylib Referenced from: /Users/halsdunes/.pyenv/versions/3.6.2/bin/uwsgi Reason: image not found Abort trap: 6 Not sure what I need to do, is this an issue with pyenv? -
network agents interaction solution
I have a django-based administration panel (minimal functionality, not based on any third-party projects) that is used to communicate via http with a service/daemon that runs on a different machine and basically processes task given by admin panel (tasks like locally run some app, kill some app, press a key). Daemon also interacts with applications that are run on that machine and it collects some states etc. to send it to the admin panel. At the moment the daemon is written in C++ (boost.asio is used for http interactions). What i'd like to ask is are there any combinations of third-party libraries or frameworks/design pattern that provide all the functionality i need? I need to establish some uniform protocol and get a good scalable solution and also don't want to reinvent the wheel, as it seems like it all can come to a point when i'm sitting developing http client/server architecture on a real low level, then extend my applications to provide interface for interaction with a daemon, than i rewrite my administration panel and so on. Thanks! -
query python code from a web page and output back to web page
I'm sure this is basic for many of you. I'm new to programming and have used Python 2.7 to create a script that takes in command line variables from a user (postcodes, cities, dates etc), searches various Excel files (circa 5m records) and returns the resulting query as a .csv file (which is then mail merged to send letters out). It works fine, though I run it from the command line, locally. I now would like to create a web page so that my friend can also use it. They would type in, or select from drop-downs, the variables, hit submit, the script would run on a remote server and return the resulting list to (a) the web page and (b) offer to download as a csv. I've been looking around to try and work out the various 'bits of LEGO' I need to pull it together to take it from a single-user command line experience to a multiple user web-based one. I'm more than happy learning the packages, just not sure which direction to go. I've tried initial looks at Django, Javascript, html, sqLite, but not sure how I should proceed. I'd of course like to re-use the Python … -
Subclass timedelta within Django model field
I have extended datetime.timedelta for some previous work to add the division operator. Having started using a DurationField in one of my models I would like to create a custom version which uses my extended timedelta class so that objects returned after a query include my custom timedelta class. What is the correct approach to implement this? I've been editing the DurationField class itself whilst I figure out how to do the above before taking the next step to figure out how to add a custom model field. Code as follows: class TimeDeltaExtended(datetime.timedelta): def __div__(self, divisor): return TimeDeltaExtended(seconds=self.total_seconds()/divisor) def __mul__(self, multiplier): return TimeDeltaExtended(seconds=self.total_seconds()*multiplier) def __add__(self, other): if isinstance(other, int) and other is 0: return self else: datetime.timedelta.__add__(other) class DurationField(Field): ... def to_python(self, value): if value is None: return value if isinstance(value, TimeDeltaExtended): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) ... However when I use this code queries still return normal TimeDelta objects. Is this even the area I should be looking at? Environment Python 2.7, Django 1.11 -
python manage.py: No module named 'admin_tools'
I'm trying to run this command on my django project: python manage.py makemigrations --empty my_app_name to create a new empty migration. When I try to run this command in poweshell, I get this message: PS C:\Travail\workout\workout-backend\workout_rest> python manage.py makemigrations --empty record Traceback (most recent call last): File "manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Ben\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'admin_tools' The error is: ImportError: No module named 'admin_tools' What am I doing wrong? I'm on Windows 10 and I'm using VS2017 to developp my Django app. -
Need to store values from URL then send this values using post method
I need to store some values from a GET method than send this values using the POST method in a form. How can i do that? it is possible? I Already get the values from GET method and works fine, but when i try to use the payload in the POST it goes wrong because the payload dict doesnt exist in the POST if request.method == 'GET': payload = { "sessId": request.GET['sessId'], "userName": request.GET['userName'], "sessionLifetime": SESSION_TIMEOUT, "idleTimeout": IDLE_TIMEOUT, } if request.method == 'POST': logic with the payload requests.post(url,payload) Thanks. -
Multiple models validation in the same View - Django 1.11
I'm looking for a strategy to validate the uniqueness of the keys of four models that have relationships with each other before finally being able to save them in the database. In other words, I would like to check the uniqueness of the keys so that there is no inconsistency in the database when using the Model.save() method, and only use it when all the unique keys are really unique. Following the view below as an example, the fields cnpj, address, and number respectively in LegalPerson, Email and Phone, must be unique. class StoreRegistrationView(View): ''' Classe responsavel pelo cadastro de lojas ''' def post(self, request): if request.method == 'POST': #import pdb; pdb.set_trace() form = StoreForm(request.POST) if form.is_valid(): lp = LegalPerson( cnpj = form.cleaned_data['cnpj'], corporate_name = form.cleaned_data['corporate_name'], fantasy_name = form.cleaned_data['fantasy_name'], state_inscription = form.cleaned_data['state_inscription'], municipal_inscription = form.cleaned_data['municipal_inscription'], ) lp.save() address = Address( street = form.cleaned_data['street'], neighborhood = form.cleaned_data['neighborhood'], number = form.cleaned_data['number'], complement = form.cleaned_data['complement'], city = form.cleaned_data['city'], estate = form.cleaned_data['estate'], country = 'Brasil', cep = form.cleaned_data['cep'], latitude = form.cleaned_data['latitude'], longitude = form.cleaned_data['longitude'], person = lp, ) address.save() email = Email( address = form.cleaned_data['email'], person=lp, ) email.save() phone = Phone( number=form.cleaned_data['phone_number'], person=lp, ) phone.save() # Mensagem de sucesso que será disponibilizada para o … -
Limit ForeignKey models by count
This is my model and I want to limit the number of photos that a user can upload to just 10. I want to do it one place so it works in the admin and user facing forms. Can someone help me out here? class StarPhotos(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) PHOTO_CATEGORY = ( ('HS', "Head Shot"), ('WP', "Western Party Wear"), ('IP', "Indian Party Wear"), ('SW', "Swim Wear"), ('CW', "Casual Wear"), ) category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW') # This FileField should preferaby be changed to ImageField with pillow installed. photos = models.FileField(max_length=200, upload_to='images/',) def __str__(self): return "Images for {0}".format(self.user) -
django-admin runserver works fine, but cannot run urls.py without getting import error
I am following the djangobook website. I am just starting out, and my project structure looks like this: mysite mysite __init__.py settings.py urls.py views.py wsgi.py manage.py The outer mysite lives in a directory that is on the pythonpath. Therefore, if I want to import something from views.py in a python console, I have to construct an import: from mysite.mysite.views import hello However, the actual implementation that currently works when running the server is: from mysite.views import hello If I try to import hello by using this single mysite relative import in a console, it will fail. How come it does not fail when I execute: django-admin manage.py runserver ? -
celery logging in django
I have gone through a lot of questions regarding this on SO, but most of the questions are missing the parameters or implementation methods. So, I'm not able to debug this. My simple requirement is I want to log all(django and celery) messages to a single file. This is my LOGGING dict in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)s - %(funcName)s() ] %(name)s: %(message)s' }, }, 'handlers': { 'default': { 'level': 'INFO', 'formatter': 'standard', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': 'logger.log', 'when': 'midnight', 'interval': 1 } }, 'loggers': { '': { 'handlers': ['default'], 'level': 'INFO', 'propagate': False } } } CELERYD_HIJACK_ROOT_LOGGER = False Then I have defined this function: @shared_task def tester(): import logging logging.info("Log this!!") tester() is writing to the log file. tester.delay() is not writing to the log file. What am I missing in this simple thing? -
MultipleObjectsReturned - django
get() returned more than one Malwares -- it returned 2! Is the error that i'm getting whilst trying to write and run some lovely django code. It appears to be triggered by the following command Malwares.objects.update_or_create(name=name) What am I doing wrong here! I'm happy to provide more code from other parts of the program if that will aid in resolution of this issue. -
Custom permission return always true, django
Sorry for my english. Now i learning django rest and i try create custom permisssion for user. Fox example permission: "big" and "small". My user model class User(AbstractUser): is_active = models.BooleanField(default=False) email = models.EmailField(blank=False, unique=True) avatar = models.ImageField(upload_to='avatar/users', blank=True) class Meta: permissions = ( ("big", "this is big boy"), ("small", "this is small"), ) then i added permission to user something like this: permission = Permission.objects.get(name='big') user.user_permissions.add(permission) user.save() created custom class, it class check permission: class IsBigBoy(permissions.BasePermission): def has_permission(self, request, view): return request.user.has_perm('users.big') and in view i create test class for check my custom permission class MySuperTestRequest(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated, custom_permissions.IsBigBoy) serializer_class = CreateSomethingSerializer def post(self, return Response({"detail": "good"}, status.HTTP_200_OK) Problem: return request.user.has_perm('users.big') it code always return true -
How To Calculate days Between Two Dates In Django
I want to calculate days difference between two dates in Django. i am trying this code: My Model : dateDeDebut = models.DateTimeField(auto_now_add=False, auto_now=False) dateDeFin = models.DateTimeField(auto_now_add=False, auto_now=False) My classViewSet : class MyClassViewSet(viewsets.ModelViewSet): serializer_class = MyClassSerializer permission_classes = (IsAuthenticated, ) def perform_create(self, serializer): if (condition): diff = (self.request.data.get('dateDeFin') - self.request.data.get('dateDeDebut')).days #never executed print(diff) And I get this error : unsupported operand type(s) for -: 'unicode' and 'unicode' -
Django docker with local volumes
I'm experiencing some difficulties with running my Django docker with local volumes. When I run it normally(without binding to local folders it works fine. But when I want to run it with this binding it gives me an error "python: can't open file 'manage.py': [Errno 2] No such file or directory". I'm running it under windows but the same problem is also under Mac OS. The path is 100% correct. (I'm using Kitematic) Does anyone came across this issue? -
How can I override username validation in Django 1.11?
I have a custom user model in my Django 1.11 site, along with django-registration. On my registration form, I prompt for a username and passphrase. I have added MinimumLengthValidator and custom WordCountValidator validation to the passphrase field in settings.py (see below) -- these validation rules are rendered in the registration form automatically. Now I want to change the username validation with three rules: length, must start with a letter, may only contain alphanumeric characters. I don't mind combining these into a single rule. I tried adding username_validator to the class and setting that, but nothing happens -- probably because I'm inheriting from AbstractUser not User (related 1.10 bug?). How can I add a single, or multiple, validation rule to my username field? Simplified appearance of form: Username: [ ] Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. Passphrase: [ ] Your password must contain at least 15 characters. Passphrase must contain at least three words. Use spaces between words. Passphrase confirmation: [ ] Enter the same passphrase as before, for verification. settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 15, } }, { 'NAME': 'custom.validators.WordCountValidator', 'OPTIONS': { 'min_words': 3, } }, ] models.py class User(AbstractUser): objects … -
Why django test --keep-db works with postgres database but not with default sqlite3
I'm testing Django (v1.11.4) application in two setups of database: 1) postgres database running in docker container or 2) sqlite3 as (defaulut database) When running tests with --keep-db option I observe different behavior for these two setups: for postgres --keep-db works as expected (there is no database creation and running test is fast) but for sqlite3 database --keep-db seems not working (for each run of the test there is creation of database). Is it possible to have --keep-db working with sqlite3? If so any idea what settings might affect behavior described as above? -
Django filter testing
class BusinessPartnerFilter(SilBaseFilter): active = django_filters.BooleanFilter( name='date_deactivated', lookup_expr='isnull') parent_name = django_filters.CharFilter(name='parent__name') unmapped = django_filters.BooleanFilter(method='check_if_unmapped') Ive added the field 'unmapped' above and created the method filter below. Can someone please help write tests for the filter.. I'm stuck class Meta(object): model = models.BusinessPartner fields = [ 'name', 'bp_type', 'slade_code', 'parent', 'national_identifier', 'active', 'parent_name', 'unmapped' ] def check_if_unmapped(self, queryset, field, value): if value: exclude_bps = [record.id for record in queryset if record.mapped == 0 and record.unmapped == 0] return queryset.exclude(id__in=exclude_bps) return queryset -
Wagtail multi-language NoReverseMatch
I am trying to implement multi-language support to a website. I am using wagtail-modeltranslation. After installing it, when I try to edit the home page from the admin I am getting this exception: NoReverseMatch at /admin/pages/2/ Reverse for 'wagtail_serve' with arguments '('/home/',)' not found. 1 pattern(s) tried: ['en/((?:[\\w\\-]+/)*)$'] The ursl.py are correct: urlpatterns += i18n_patterns( url(r'', include(wagtail_urls)), ) I can edit the slug in the back panel, however I have tried to add a slug from the class e.g: promote_panels = Page.promote_panels + [ FieldPanel('slug'), ] I see that it is trying to reach en/ version in the admin and I don't get it why? -
Graphite SQLite3 DatabaseError: attempt to write a readonly database
I'm running graphite under apache, with SQLite database, with correct folder permissions $ cd /var/lib/ $ ls -l | grep graphite drwxr-xr-x 6 _graphite _graphite 97 Aug 18 21:47 graphite and graphite.db file also has correct file permission and ownership like this, $ ls -l graphite/graphite.db -rw-r--r-- 1 _graphite _graphite 79872 Aug 18 21:47 graphite/graphite.db When I access graphite-web on browser, I get following error, Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/dist-packages/graphite/composer/views.py", line 35, in composer profile = getProfile(request) File "/usr/lib/python2.7/dist-packages/graphite/user_util.py", line 25, in getProfile return default_profile() File "/usr/lib/python2.7/dist-packages/graphite/user_util.py", line 41, in default_profile 'password': '!'}) File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 424, in get_or_create return self._create_object_from_params(lookup, params) File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 457, in _create_object_from_params obj.save(force_insert=True, using=self.db) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 589, in save force_update=force_update, update_fields=update_fields) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 617, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 698, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 731, in _do_insert using=using, raw=raw) File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 921, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 921, in execute_sql … -
OnClick HTML button : call Javascript function + location.href (Django)
How can I put 2 operations in my onclick parameter, one calling a Javascript function, the other giving location.href with Django tags ? I want to make something appear on the page before redirecting to another page. I want to do something like this : onclick="chargement();location.href='{% url 'resumefic' upload.0.pk %}';" but this isn't working... I can't put the location.href in a JS function as I'm using Django tags... Can someone help ? -
Testing Django Email for error handling reporting
I'd like to setup an automated mailing system that notifies the Admin user when an Exception has been raised in a Django App. For now, I'd simply like to test the Email notification system and have followed numerous tutorials and tips here and here and here and here, in addition from a few other sites. I'm using a local Django development environment (not in a live production scenario), with Python 3.5 and Django 1.8. I am on my home network (no proxy involved etc.) settings.py ADMINS = ( ('My Name', 'myhotmailaccount@hotmail.com'), ) #EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' MAILER_LIST = ['myhotmailaccount@hotmail.com'] EMAIL_HOST = 'smtp.live.com' EMAIL_HOST_USER = 'myhotmailaccount@hotmail.com' EMAIL_HOST_PASSWORD = 'myhotmail_password' EMAIL_PORT = 465 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'noreply@hotmail.com' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'default': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': SITE_ROOT + "/logfile.log", 'maxBytes': 1024*1024*5, #5 MB 'backupCount': 5, 'formatter': 'standard', }, 'request_handler':{ 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': SITE_ROOT + "/django_request.log", 'maxBytes': 1024*1024*5, #5 MB 'backupCount': 2, 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', } }, 'loggers': { '': { 'handlers':['mail_admins', 'default'], 'level':'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['request_handler'], 'level': 'DEBUG', 'propagate': False, … -
multiple django projects on one application in webfaction
I am using a webfaction server and i am new to the server side. Now i had three django projects with three domains and one application in webfaction. So is any way that i can run three django projects with three different domains in one application. i had changed httpd.conf by placing virtual host in it. But it did not work. thanks in advance This is what i had been tried KeepAlive Off SetEnvIf X-Forwarded-SSL on HTTPS=1 ServerLimit 1 StartServers 1 MaxRequestWorkers 5 MinSpareThreads 1 MaxSpareThreads 3 ThreadsPerChild 5 #WSGIDaemonProcess application processes=2 threads=12 python-path=/home/device_name/webapps/application:/home/device_name/webapps/application/project_name:/home/device_name/webapps/application/lib/python2.7 #WSGIProcessGroup application #WSGIRestrictEmbedded On #WSGILazyInitialization On #WSGIScriptAlias / /home/device_name/webapps/application/project_name/project_name/wsgi.py # Virtual hosts setup NameVirtualHost * <VirtualHost *> ServerName application.com WSGIDaemonProcess application processes=5 python-path=/home/device_name/webapps/application:/home/device_name/webapps/application/project_name:/home/device_name/webapps/application/lib/python2.7 threads=1 WSGIProcessGroup application WSGIRestrictEmbedded On WSGILazyInitialization On WSGIScriptAlias / /home/device_name/webapps/application/project_name/project_name/wsgi.py </VirtualHost> <VirtualHost *> ServerName dreamhomeconsultancy.in WSGIDaemonProcess APPLICATION_NAME_www processes=5 python-path=/home/device_name/webapps/application:/home/device_name/webapps/application/civilengg:/home/device_name/webapps/application/lib/python2.7 threads=1 WSGIProcessGroup civilengg WSGIRestrictEmbedded On WSGILazyInitialization On WSGIScriptAlias / /home/device_name/webapps/application/civilengg/civilengg/wsgi.py </VirtualHost> -
cx_freeze: import error: no module named html.parser
I wrote a django project. And now trying to get an exe file from it. I use cx_freeze to manage.py file and I got the .exe file. But when I run this exe file in the cmd, I got the error, no module named html.parser. There is no problem when I run import html.parser in python cmd. I am stuck with the problem for a two whole days and I really appreciate your help. django 1.11 python 3.4.1 windows the django project can correctly run on my windows computer. enter image description here -
Dynamic select inputs, how to rerender form?
I have a form with two select inputs, which retrieve data from an api. Although I can render the first one dynamically I'm not sure how to rerender the form after retrieving the data for the second input (which depends on the first). The issue seems to be when I return render from if request.is_ajax(): I'm not sure what should be returned here and how this should mounted with JQuery(if it needs to be). Currently I'm just returning the whole updated page/template and new form, but the browser has only sent an ajax request. views.py @require_http_methods(['GET', 'HEAD', 'POST']) def current_service_view(request): postcode = request.session.get('postcode', None) fuel_type = request.session.get('service_type', None) payment_method = request.session.get('payment_method', None) form = CurrentServiceForm(postcode, fuel_type, payment_method) if request.is_ajax(): supplier_id = request.GET.get('supplier', None) form = CurrentServiceForm(postcode, service_type, payment_method, data=request.POST, supplier_id=supplier_id, ) render(request, 'pages/signup_current_service_functional.html', {'form': form}) if request.method == 'POST': form = CurrentServiceForm(postcode, fuel_type, payment_method, data=request.POST, ) if form.is_valid(): request.session.update(form.cleaned_data) return redirect('users:usage') return render(request, 'pages/signup_current_service_functional.html', {'form': form}) forms.py class CurrentServiceForm(forms.Form): postcode = forms.CharField(max_length=100) # may not have this in the end. supplier = forms.ChoiceField() service = forms.CharField(max_length=100) def __init__(self, postcode, service_type, payment_method, supplier_id=None, *args, **kwargs): super().__init__(*args, **kwargs) region = get_region(postcode) suppliers = get_suppliers(region, service_type,) supplier_choices = [('', '---- Please select your …