Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to define the success_url in django without kwargs
I am elaborating on the tutorial in the django docs to build a voting app. What I try to achieve is to be able to delete a candidate and, at success, get back to the detailview of the election. I know I could just add another parameter to the url like (full template below) <a href="{% url 'candidate_delete' c.id object.id %}" class="btn btn-danger fa fa-trash" class></a> I would like to know whether it is possible to use a post method (although there is no form). I did some research, found the 'next' parameter, but it does not get through. It looks like it needs a form, since all examples are using the 'next' within a form. I also tried setting the success_url based on the election the to-be-deleted-candidate is ForeignKey-d to, but that generates the error: ImproperlyConfigured at /elections/candidate/delete/13/ The included URLconf '1' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This is the view: class CandidateDelete(LoginRequiredMixin, DeleteView): model = Candidate template_name = 'election/delete.html' def get_object(self): obj = super().get_object() print(self.request.POST) election = Election.objects.get(id=obj.poll_id) if not election.owner_id == self.request.user.id: raise Http404 return … -
how to create an spinner/loader without ajax in django
I want to create an spinner or some sort of ways to allow the user knows that the webpage is loading without using ajax. I found this solution but it is an old answer: Best way to display a loading spinner in Django? I am not understanding what they mean when they said add it to the display list. If anyone has an better solution or can help clarify the solution. -
How to use HTTPIE to make a request with a ListField Django Rest Framework serializer
Using Django Rest Framework I have a serializer: class UserDataSerializer(serializers.Serializer): age = serializers.IntegerField() serializers.ListField(child=serializers.BooleanField()) I can't figure out how to pass ListField data in a request in command line, using httpie. Following documentation and a cheatsheet, I tried this way: http POST <http_url> age=43 questions:='[0, 1, 0]' but I get TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' Adding double quotes for the items, as in http POST <http_url> age=43 questions:='["0", "1", "0"]' I get { "risk_questions": [ "Expected a list of items but got type \"str\"." ] } -
Django real time notification
I'm working on django project that requires a real time communication, i found on google that best way to do is using MQTT protocol, in this way i need to write my own broker by subclassing HBMQTT broker , but it seems hard to run MQTT broker and django web server on the same service, also i found channels and ASGI application its very good at local using channel layers and redis, but i can't use redis on the web host 'some limitation in the host. Some solution told me to use channels with BACKEND channels.layers.InMemoryChannelLayer but according to their docs, its not for production. is any idea? or better solution than using mqtt and channels? or i can mix HBMqtt.Broker with channels as any consumer? English is not my native language ,so I'm sorry for any errors. -
Why isn't this creating the models in batch?
I am trying to create the object blank in a batch but it is only creating one object after I fill in the form, could anyone help me with what I am doing wrong? html {% block content %} <form class="box" method = "post"> {% csrf_token %} <h1>Air Ticket Sales</h1> {{ form }} batch size: <input type="number" name="batch" value="{{ batch }}"> <input type="submit" name="" value="Create Blank"> </form> {% endblock %} model class blank(models.Model): #an integer field that automatically increments by itself as the object are created number = models.AutoField(primary_key=True) type = models.CharField(max_length=50, choices=type_choices, default='green') is_sold = models.BooleanField(default=False) is_refunded = models.BooleanField(default=False) date = models.DateField(auto_now_add=True) date.editable = True advisor = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, ) view def create_blanks(request): if request.method == 'POST': #initializes the data from the form to the value form form = blank_form(data=request.POST) batch = request.POST.get("batch", "") if form.is_valid(): for b in batch: form.save() return render(request, "create_blanks.html") else: return render(request, "create_blanks.html") else: form = blank_form return render(request, "create_blanks.html", {'form':form}) -
How Django Auto Generate DatePicker For Field
I am new in django and have c# background, I've just created a Post model which has the property publish = models.DateTimeField(default=timezone.now) after launching the site django auto created javascript datepicker for this without writing view script code (in case of c#) ,So the question is how it works behind the scene? -
How to Save io.BytesIO pdfrw PDF into Django FileField
What I am trying to do is basically: Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file) My issue is that when the create() method runs, it saves all of the fields except for the form. helpers.py import io import tempfile from contextlib import contextmanager import requests import pdfrw @contextmanager def as_file(url): with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile: tfile.write(requests.get(url).content) tfile.flush() yield tfile.name def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) ## PDF is modified here buf = io.BytesIO() print(buf.getbuffer().nbytes). # Prints "0"! pdfrw.PdfWriter().write(buf, template_pdf) buf.seek(0) return buf views.py class FormView(View): def get(self, request, *args, **kwargs): form_url = 'http://some-pdf-url.com' with as_file(form_url) as temp_form_path: submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"}) print(submitted_form.getbuffer().nbytes). # Prints "994782"! FilledPDF.objects.create(form=File(submitted_form), name="Test PDF") return render(request, 'index.html', {}) As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? -
Read 35 GB file and write into a ZIP file without creating temp file in Django
I have Django app where user selects a file then i read that file, create a write the content in temp file then create a zip out of it. I want to remove the middle step where i create a temp file before creating a zip Here is my upload.html <div class="form-container"> <form method="post" enctype="multipart/form-data" class="my-form" action="/upload-policy" id="my-form"> {% csrf_token %} <h2 class="form-header" style="color: white;">Upload Job</h2> <div class="form-group"> <label for="laf-file"></label> <input required="required" type="file" accept=".*" class="form-control" id="any_file" placeholder="Select File" name="document"> <small class="form-text"></small> </div> <button id="file-btn" type="submit" class="btn-submit btn-primary">Submit</button> </form> Django view.py def upload_job(request): archive_list = [] print(request.data) uploaded_file = request.FILES['document'] # ** document is field from html submit** filename = uploaded_file.name content = uploaded_file.read() # ****reading file**** temp_file = os.path.join(tempPath, filename) with open(temp_file, 'wb') as meta: # ****Write into temp file**** meta.write(content) archive_list.append(temp_file) # **** creating zip of the temp file**** retry_attempt = 0 while True: try: retry_attempt += 1 zipfilepath = os.path.join(tempPath, filename + ".zip") zippedfile = zipfile.ZipFile(zipfilepath, "w", allowZip64=True) for file in archive_list: zippedfile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) error = zippedfile.testzip() zippedfile.close() break except: if retry_attempt >= 3: raise else: os.remove(zipfilepath) zippedfile = None continue More impotently i also would love to know if i can do this as Ajax request … -
Django model object access in views
I have a view in django which get a value through post request and i want to get a model object using that value as an attribute. View is as: def accessObject(request): if request.method =="POST": value = request.POST.get('value') object = RandomModel.objects.get(value=value) return render(request,template,{'object':object}) I want to know if this is the correct way of doing things in production, because if value is an integer type then the view will throw an error even if object exists. Should I use type conversion every time I write this type of view in django? -
How to display videos in homepage from database in django
I've made a portfolio website with django and bootstrap framework. Now i'm trying to display multiple videos in my homepage. So through admin panel i uploaded 3 videos and in template used video tag. In model FileField for upload and also summary for video description. After setup and runserver my website homepage is showing just video description and video player and controls. There is no such videos or thumbnails to play. Please help me on that matter.enter image description here enter image description here enter image description here -
Creating PDF report in Django with visulaization/graph
I want to create a PDF report when a request is sended to the Django rest API. The things I looked into weasy print that works fine but I didn't really able to include visualization in there such as Histogram, pie/bar chart. Secondly, I looked into report lab and able to create the visualization such as Histogram but they are not good looking and kinda old fashion. I want to have a pdf with some fancy charts like created by Chart.js basically good UI PDF. -
Apply sorting on field in foreign key django rest framework
I have three models: Class Book(models.Model): book_name = models.CharField(max_length=10) author = models.Foreignkey('author', on_delete=models.cascade) Class Author(models.Model): name = models.CharField(max_length=50) addr = models.CharField(max_length=50) Class Bookinfo(models.Model): book = models.ForeignKey('book', on_delete=models.cascade) page_number = models.IntegerField() Serializers are: Class bookserializer(modelserializer): Class Meta: Model= book Fields = ("__all__") Class authorserializer(modelserializer): Class Meta: Model= author Fields = ("__all__") Class bookinfoserializer(modelserializer): Class Meta: Model= bookinfo Fields = ("__all__") Depth=2 Viewset: Class Bookinfoviewset(viewsets.modelviewset): Queryset= bookinfo.objects.all() Serializer_class= bookinfoserializer In the response I get the nested values: { Book_id:{ Book_name: Author_id: { Name: Addr: } }, Page_number: } In the backend I am using PageNumberPagination , searchfilter and ordering. In the book info view, I want to apply ordering on book_name which is inside book_id which is a foreign key. How to do that without affecting filter and pagination. Please help. I am using python 3.5 django 2.2.9 -
__init__() takes 1 positional argument but 2 were given, when adding Latex support to markdown
I'm following this tutorial to add LaTeX support to markdown, and I get this error: init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost/posts/ttttt/ Django Version: 2.2.10 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\abdom\OneDrive\Desktop\project\wagtailmd\mdx\mdx_mathjax.py in makeExtension, line 23 Python Executable: C:\Users\abdom\OneDrive\Desktop\project.venv\Scripts\python.exe Python Version: 3.7.3 Python Path: mdx_mathjax.py : import markdown import cgi class MathJaxPattern(markdown.inlinepatterns.Pattern): def __init__(self, md): markdown.inlinepatterns.Pattern.__init__( self, r'(?<!\\)(\$\$?)(.+?)\2', md) def handleMatch(self, m): # Pass the math code through, unmodified except for basic entity # substitutions. # Stored in htmlStash so it doesn't get further processed by Markdown. text = cgi.escape(m.group(2) + m.group(3) + m.group(2)) return self.markdown.htmlStash.store(text) class MathJaxExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): # Needs to come before escape matching because \ is pretty important # in LaTeX md.inlinePatterns.add('mathjax', MathJaxPattern(md), '<escape') def makeExtension(configs=[]): return MathJaxExtension(configs) wagtailmd.py : import markdown from django import template register = template.Library() @register.filter(name='markdown') def markdown_filter(value): return markdown.markdown( value, extensions=[ 'wagtailmd.mdx.mdx_mathjax', ], output_format='html5' ) thanks. -
Django Rest Framework Permissions not being called for Detail and List View
I created this custom permission class and it does not seem to be called when I make a request from the view. I event set it to return false and requests are still successful. Tried placing a print statement to see if there would be any output but no. Not sure what I'm doing wring. View: class EventEditView(RetrieveUpdateDestroyAPIView): authentication_classes = ( ) permission_classes = (EventVisibilityPerm, ) serializer_class = EventEditSerializer def get(self, request, *args, **kwargs): event = get_object_or_404(Event, slug=kwargs['slug']) serializer = EventSerializer(event) return Response(serializer.data) Permissions.py: class EventVisibilityPerm(permissions.BasePermission): """ Permission class determines whether a user has access to a specific Event """ def has_object_permission(self, request, view, obj): print('here line 15') return False **Serializer: ** class EventSerializer(serializers.ModelSerializer): class Meta: model = Event exclude = ('user', 'id') Currently testing permissions for this detail view but this permission will also need to be used on a List view. -
Django logging - logging on ValidationError not working
So I want to be able to track any ValidationErrors being raised by the def clean method on a certain form. I have the a form called AdForm, the validation on the form does work, I can see the errors in the html output. The logging also works since I get the logger info in the text file. The strange thing is, I get the notice; 2020-02-11 18:17:43,099 [INFO] .forms: AdForm is called But I don't see the raised validation error in my log files? Is there anything wrong with my settings? For some of you this might be piece of cake but I'm struggling to find my own errors, any help will be appreciated! forms.py from .models import Ad import logging logger = logging.getlogger(__name__) class AdForm(forms.ModelForm) logger.info("AdForm is called") class Meta: model = Ad fields = [ 'title', 'description' ] def clean(self): cleaned_date = super(AdForm, self).clean() title = cleaned_data.get('title') if len(title) < 4: logger.info("Title is shorter then 4 characters") raise forms.ValidationError("Title is too short") if len(title) > 24: logger.info("Title is shorter then 4 characters") raise forms.ValidationError("Title is too long") settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': … -
How to set the default urlpatterns for Django projects
Whenever I start a Django project the url patterns are like this: url(r'^admin/', admin.site.urls) I am using venv and I install the latest version of Django so shouldn't the url patterns default to?: path('admin/', admin.site.urls) In the auto comments at the top of the urls.py file it seems to be referencing Django 1.11 even though I am using 3.03: The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ -
creating an object based on some conditions in django
I have a model called Showcase that users use to showcase projects. I am trying to implement a case where any administrator in the Administrators field in the showcase can add collaborators through the Collaborator model. When I run my code below, I get name 'APIException' is not defined. models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) class Collaborator(models.Model): post = models.ForeignKey(Showcase, on_delete=models.CASCADE, related_name="collaborated_showcases") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="collaborators") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True, related_name="creative_type") role = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) serializer class CollaboratorSerializer(serializers.ModelSerializer): post = serializers.SlugRelatedField(read_only=True, slug_field='slug') class Meta: model = Collaborator exclude = ['created_on', 'updated_on'] class ShowcaseAdminSerializer(serializers.ModelSerializer): administrator = serializers.SlugRelatedField(slug_field='slug', many=True, queryset=User.objects.all()) class Meta: model = Showcase fields = ['administrator',] def update(self, instance, validated_data): users = validated_data.get('administrator') for user in users: instance.administrator.add(user) return instance views.py class collaboratorCreateView(APIView): ''' add collaborator to a showcase ''' serializer_class = CollaboratorSerializer permission_classes = [IsAdmin] def post(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) try: self.check_object_permissions(request, showcase) collaborator = Collaborator.objects.create( post = showcase ) serializer = self.serializer_class(collaborator, data=request.data, partial=True) … -
increase the column size in template
I can strech(adjust) rows through cursor but problem is i cant do the same for column (as shown in picture) here is the code i used: {% extends "base.html" %} {% block content %} <h2>New Blog</h2><br> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-success ml-2" value="save"> <a class="btn btn-primary" href="{% url 'blog_list' %}" role="button">Cancel</a> </form> {% endblock content %} -
django check if the whole website is idle
My django website connects to a sqlite database. If the website is idle for 3 minutes, I want to disconnect the database file. Can django detect if the website is idle? -
When changing s3 buckets - "The request signature we calculated does not match the signature you provided"
Really struggling with this one. I have the following config: Django/DRF Boto3 Django-storages I am using an IAM user credentials with one set of keys. I have removed all other sets of keys including root keys from my account, to eliminate keys mismatch. Original bucket name was my-staging-bucket. I created that one from django by running python3 manage.py collectstatic. So far so good, I can upload files, download files and delete them as well. Now I wanted to create a new bucket my-prod-bucket. Updated the bucket name settings in my env file. I ran python3 manage.py collectstatic and it created the new bucket without a problem. I can upload and delete however when I try to download a file I get: <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> <AWSAccessKeyId>AKIA6FUWELHPTCYOIUMP</AWSAccessKeyId> <StringToSign> AWS4-HMAC-SHA256 20200211T162650Z 20200211/us-east-1/s3/aws4_request 127b05746c0713faa86b1f1c5c1e135dca82ba5d700211ede1b63f1821bf0b18 </StringToSign> <SignatureProvided> ef92df31dde436a8c43adccb916693d944bacd5ca5258856c3bc18cc655d85bd </SignatureProvided> I'm not sure what I'm doing wrong. I cleared any aws config and env variables from my system. The only env variables are the ones inside the .env file in my local project. Now to add to that, if I delete all buckets, and set the bucket name … -
Templates not found Django
I was trying this project mentioned in "Lightweight Django_ Using REST, Websockets & Backbone [Elman & Lavin 2014-11-13]" but in this i got stuck when my templates are not found can anyone help in this my settings are import os import sys from django.conf import settings DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', '%jv_4#hoaqwig2gu!eg#^ozptd*a@88u(aasv7z!7xt^5(*i&k') ALLOWED_HOSTS = [] BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), INSTALLED_APPS=( 'django.contrib.staticfiles', ), TEMPLATE_DIRS=( os.path.join(BASE_DIR, 'templates'), ), STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', ) my views are def index(request): example = reverse('placeholder', kwargs={'width': 50, 'height':50}) context = { 'example': request.build_absolute_uri(example) } return render(request, 'home.html', context) #and urls are urlpatterns = ( url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$', placeholder, name='placeholder'), url(r'^$', index, name='homepage'), ) and my template order in the folder is - foo - templates - home.html - static - site.css -
Filter option from Enum in Django Admin
The below is my main model. It contains many fields but will concentrate on required 2 fields class CustomAuditType(models.Model): name = models.CharField(max_length=100) type = models.PositiveIntegerField(choices=choices(Type)) Enum class is class Type(Enum): Custom = 0 Generic = 1 Instructions = 2 From this main parent model I'm inheriting in other model using Proxy model inheritance class Instruction(CustomAuditType): class Meta: proxy=True Now coming to our model for which I'm using admin also class CustomAssignment(models.Model): custom_audit_name = models.ForeignKey(Instruction) value_stream = models.ForeignKey(dashboard.ValueStream, null=True, blank=True) category = models.ForeignKey(CustomAuditCategory, null=True, blank=True) user = models.ManyToManyField(User) My admin is class CustomAuditUserAssignmentAdmin(admin.ModelAdmin): list_display = ('custom_audit_name','value_stream','category') filter_horizontal = ['user'] def get_queryset(self, request): queryset = super().get_queryset(request) print('Prashant',queryset) return queryset.filter(type=Type.Custom.value) I am trying to override get_queryset to take only Custom type from CustomAuditType model which is present in type field. So the requirement is I need to only show the Custom type in CustomAuditUserAssignmentAdmin admin in field of Custom Audit Name. Ignoring Instructions and Generic from class Type(Enum) Please help me. Thank you! -
Django CheckConstraint: Elements of reverse ForeignKey lookup must not be empty
I've got these models: class Container(models.Model): ... class Meta: constraints = [ models.CheckConstraint(check=~Q(elements=None), name='container_must_have_elements'), ] class Element(models.Model): container = models.ForeignKey(Container), related_name='elements', on_delete=models.CASCADE ) I want to enforce the constraint that every Container object must have at least one Element referencing it via the foreign key relation. As you can see I already added a check constraint. However, the negation operator ~ on the Q object seems to be forbidden. I get django.db.utils.NotSupportedError: cannot use subquery in check constraint when I try to apply the generated migration. Without the negation operator the constraint seems to be valid (it only fails due to a data integrity error). Is there another way I can express this constraint so it is supported by CheckConstraint? (E.g. is there a way to check if the set of elements is not empty?) -
NoReverseMatch at /login - error with LOGIN_URL or reverse function?
I am developing an app in Django. I am developing users authentication. I have a registration.html and a login.html templates inside path: templates > authentication Everything, including the registering function, works fine, but as I try to access to login template, the browser returns: NoReverseMatch at /login 'app' is not a registered namespace I bet the problem lies in the LOGIN_URL that I added in settings.py to enable authentication system (I am following a tutorial). In fact, all the others view work fine, just the one pointing to login.html is not. Here below are all my lines relating to the authentication system: In my settings.py: LOGIN_URL = '/login' In my base.html: {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ user_form.username }}</a> <div class="dropdown-menu"> <a class="dropdown-item" href="">profilo</a> <a class="dropdown-item" href="{% url 'logout' %}">Log out</a> </div> </li> {% elif not user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Login</a> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'registration' %}">Registrati</a> <a class="dropdown-item" href="{% url 'login' %}">Accedi</a> </div> </li> {% endif %} In my app > urls.py, Inside urlpatterns list: path('authentication/registration', views_users_authentication.registration, name="registration"), path('login', views_users_authentication.user_login, name="login"), in my project > urls.py, Inside urlpatterns list: path('admin/', … -
ModelSelect2Widget gives empty dropdowns
I've created a template, view, form and model, that the models are all synced at one by foreign keys, and now I need to select 3 dropdowns depending on the choices that I have defined on the previous dropdowns, but after doing that the dropdowns are empty with no data, but the querysets are there as well as the form.media.js and the form.media.css. Bellow are the forms and models. class GoodDistributorLocationCreateForm(ModelForm): good = ModelChoiceField( queryset=Good.objects.all(), label=u"Good", widget=ModelSelect2Widget(model=Good, search_fields=['name__icontains'],), ) distributor = ModelChoiceField( queryset=Distributor.objects.all(), label=u"Distributor", widget=ModelSelect2Widget( model=Distributor, search_fields=['name__icontains'], dependent_fields={'good': 'good'}, ), ) location = ModelChoiceField( queryset=Location.objects.all(), label=u"Location", widget=ModelSelect2Widget( model=Location, search_fields=['address__icontains'], dependent_fields={'distributor': 'distributor'}, max_results=500, ), ) class Meta: """Add good distributor location form.""" model = GoodDistributorLocation fields = ['good', 'distributor', 'location', 'price'] def __init__(self, *args, **kwargs): """Initialize form for setting good distributor location request fields.""" super(GoodDistributorLocationCreateForm, self).__init__(*args, **kwargs) self.fields['good'].required = True self.fields['distributor'].required = True self.fields['location'].required = True self.fields['price'].required = True Models: class Good(models.Model): TYPE_TUKTUK = 0 TYPE_CHOICES = ((TYPE_TUKTUK, 'TukTuk'),) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) good_type = models.IntegerField(choices=TYPE_CHOICES, default=TYPE_TUKTUK) brand = models.CharField(max_length=255, blank=True) def __str__(self): """ Unicode representation for a Good model. :return: string """ return '{} - {}'.format(self.name, self.get_good_type_display()) @property def shortened_id(self): """Get shortened version of id.""" return …