Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Collection, storage, and visualization of third party data using Django?
This question is based on a previous one I recently asked. I have tried to make this question as detailed as possible. My goal: I am creating a web app that allows for exploratory analysis of ocean buoys. User selects a buoy and some graphing options (e.g., monthly averages, filters to swell size, etc.) and a graph is made showing the resulting data for that buoy. Approach: User identifies a buoy through a web form or some type of selector and chooses options for the plot (e.g., monthly averages across all time). Data is queried for the selected buoy. Data is converted into a pandas dataframe of buoy time series data. Pandas processes the data based on the option selected by the user (e.g., calculates monthly averages). Plotly creates a chart The chart is sent to the templates.py in the views.py file, and the chart is rendered on the webpage. My problem: Collecting the data is difficult. The archived data for all buoys exists on NOAA's NDBC webpage and there is no simple API for accessing this archived data. Rather, it is stored on multiple pages in multiple CSVs. Thankfully, some open source code already exists for accessing this data. … -
Django templates: using include to pass a form template; how to write the form?
I simply would like to create a form, throw it in a template, and use the include keyword to include it in my home.html file. What am I doing wrong ? # forms.py class OrderForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) # views.py def orderView(request): template = 'orders.html' if request.method == 'GET': form = OrderForm() else: form = OrderForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com'] except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'orders.html', {'form': form}) <!-- templates/orders.html --> <form method="post"> {% csrf_token %} {% form.as_p %} <button type="submit" class="btn btn-primary">Send</button> </form> <!-- templates/home.html --> ... <div class="orders"> {% include 'orders.html' %} </div> ... -
How to access selected data inside template in django?
I want to display selected user name. <select class="form-control" name="user_id"> {% for user in user_list %} <option value="{{ user.id }}">{{ user.id }}</option> {% endfor %} </select> <div> "I want to display name of selected user here" </div> How Can I access selected data in template? -
Importing excel data to django database in parent child format
My requirement is to save the excel data in the django DB using import which I could do using below code. But next I want to save the data in a one to many relationship. ie. I want a unique key to be generated and saved in Main_page model and corresponding to that my uploaded excel file data should share the same primary key in the Upload model. For eg. If the main_page has id 1, so for my complete excel data uploaded i want the data to share the same key. What changes or any link should i learn or go through. I am stuck since last few days but no luck. Thanks in advance models.py class Upload(models.Model): sheet_key = models.ForeignKey(Main_page) Student_Name = models.CharField(max_length=100) Total_Marks = models.IntegerField() Marks_Scored = models.IntegerField() class Main_page(models.Model): sheet_key = models.AutoField(primary_key=True) date = models.DateField() views.py class UploadFileForm(forms.Form): file = forms.FileField() def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) # Check if the form is valid if form.is_valid(): request.FILES['file'].save_to_database( # Save the file data to the database name_columns_by_row=1, model=Upload, mapdict=['Student_Name', 'Total_Marks', 'Marks_Scored', 'Status', 'Date', 'College_Name', 'Phone Number']) # Columns to be mapped return HttpResponse("OK") else: # If the form has errors show the error. … -
Django/Axios/React/Keras, upload image, classify image, return to user
class View(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): plants = Plants.objects.all() serializer = PlantSerializer(plants, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): plants_serializer = PlantSerializer(data=request.data) filename = request.FILES[request] logger.warning("test") img = image.load_img(filename, target_size=(224, 224)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = img/255 with sess.as_default(): with graph.as_default(): preds = model.predict(img) preds = preds.flatten() maximum_value = preds.max() for index, item in enumerate(preds): if item == maximum_value: classification = classification_list[index] Hi there, I'm working on a project that uses React front end and Django backend, and we cannot figure out how to pass in an image uploaded with the help of Axios in the front end for processing with Keras in the backend. We had it working when using Django, but we're having trouble reading the user uploaded file for processing. Any tips about how to handle this would be much appreciated. We took on a project without fully understanding backend or the complexity of many moving components. -
Tags containing spaces surrounded by quotes
I'm writing a simple notetaking app, and I have implemented tags on my notes. I'm using django-taggit for server-side implementation and bootstrap4 tag input plugin for front-end. I'm having an issue with something adding quotes around my tags that contain spaces and I cannot determine what, whether it is django-taggit or the bootstrap plugin. This is a pic of how my UpdateView looks like: so when I'm adding tags that contain spaces, they're added as they should (no quotes), however when I come back later to them (say, in UpdateView), the quotes are displayed. I have tried to print the tag in Django shell but I can't see the quotes that are being added: >>> Note.objects.get(pk=1).tags.all()[2].__str__() 'hello world' So I'm thinking the issue must be in the bootstrap plugin. How can I overcome the issue? There's quite a bit of code to this so I wasn't sure what pieces to include, if you need something, just let me know. Thanks. -
Django admin site get id to show in html
I just want that if the admin select the students, it will get the id and show in the html template admin.py @admin.register(studentDiscount) class studentDiscount(admin.ModelAdmin): list_display = ('Students_Enrollment_Records', 'Discount_Type','my_url_field') ordering = ('Students_Enrollment_Records',) search_fields = ('Students_Enrollment_Records',) def my_url_field(self, obj): return format_html("<a href='https://www.school.ph/enrollmentform/?StudentID=pk'>Report</a>", obj.Discount_Type) my_url_field.allow_tags = False my_url_field.short_description = 'Report' this is my models.py class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) -
Downloaded compressed data (`gz`) from django server using ajax is inflated and broken
I'm trying to download a .gz file from a django server (Python 3.7) using Ajax request. This is the minimal django view function and Ajax function to request download on client, compress a folder and send it (server) and receive the data on the client: from pathlib import Path def downloadfile(request): folder = Path().home().joinpath('workspace') tar_path = Path().home().joinpath('workspace.gz") tar = tarfile.open(tar_path.as_posix(), "w:gz") tar.add(folder.as_posix(), arcname='workspace') tar.close() try: with open(tar_path.as_posix(), 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/gzip') response['Content-Disposition'] = 'attachment; filename="workspace.gz"' except IOError: response = HttpResponse('File not exist') return response This is the Ajax function on the client side: $(function () { $('#downloadfile').submit(function () { $.ajax({ type: 'POST', url: 'downloadfile', success: function(response){ download(response,'workspace.gz', 'application/gzip'); } }); return false; }); }); function download(content, filename, contentType) { var a = document.createElement('a'); var blob = new Blob([content], {'type':contentType}); a.href = window.URL.createObjectURL(blob); a.download = filename; a.click(); } A sample gzipped folder that is 36.5 KB will be inflated to 66.1 KB when downloaded and it clearly can't be extracted. What I know: The file is healthy and extractable on server side. The data is transferred and downloaded on the client but inflated and broken. The respone variable in the JavaScript function looks like binary … -
Django signals post_save
class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Discount_Type != instance.Discount_Type: studentDiscount.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None discount = studentDiscount.objects.filter(Discount_Type=instance.Discount_Type) if created: studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=discount.first()) this is the picture of my (StudentsEnrollmentRecord) in my studentDiscount model why (Students_Enrollment_Records field) only save in my studentDiscount (just like in the picture shows) i want the result like this -
django-import-export - Importing ManyToMany from JSON file
I'm trying to import a JSON file that contains a many-to-many relationship but am hitting some problems. This is my code: book.json { "title": "The Lord of the Rings", "categories": [ "Fantasy", "Action", "Adventure" ] } models.py from django.db import models class Category(models.Model): guid = models.CharField(max_length=36) display_name = models.CharField(max_length=50) description = models.TextField() def __str__(self): return self.display_name class Book(models.Model): title = models.CharField(max_length=200) categories = models.ManyToManyField(Category) def __str__(self): return self.title resources.py from import_export import resources from import_export.fields import Field from import_export.widgets import ManyToManyWidget from .models import Book, Category class BookResource(resources.ModelResource): categories = Field(widget=ManyToManyWidget(Category)) class Meta: model = Book import_id_fields = ('title',) importer.py from resources import BookResource from models import Book with open("book.json", 'r') as f: book = '[' + f.read() + ']' result = BookResource().import_data(tablib.Dataset().load(book), raise_errors=True, dry_run=True) This seems to run through without errors, and adds the new book to the database. The problem is that it doesn't create a new entry in the book_categories table (PostgreSQL). I think I'm definitely missing a step somewhere because I haven't defined how to find the correct category database entries, given I the list of display_name strings. Am I on the right track here? -
How long did it take you to integrate Stripe (Django)?
This is a fairly general question. I'm integrating Stripe to my website to handle subscriptions / upgrades. I've never done it before, and it has taken me about 1.5 days to integrate it into my Django-based website, including all the templates, upgrade/downgrade pages and changing my User models in Django. My main bottlenecks have been JavaScript/jQuery as I have just no experience with it, and obviously figuring out the API, although I must say the documentation was excellent. How long should it have taken me? How long did it take you, for those who've done it before? Just asking out of interest/curiosity. Thanks! -
Custom Django Rest Framework authentication validating when 'None' is returned
I am working on implementing JWT for authentication. Of course, this means I have to do some custom authentication. According to the docs, "If authentication is not attempted, return None." So, I have code that checks for an authorization header (where the JWT resides) and returning "None" if an authorization header does not exist. This means that authorization was not attempted (and according to the docs) I should return None. However, Django is saying that the user is authorized: Root/authentication/TokenAuthentication/TokenAuthentication from rest_framework import status from django.http import HttpResponse from rest_framework.authentication import get_authorization_header, BaseAuthentication from django.contrib.auth.models import User import jwt, json class TokenAuthentication(BaseAuthentication): def authenticate(self, request): auth = get_authorization_header(request).split() if not auth: return None Login.py @api_view(['POST']) def login_view(request): if not request.data: return Response({'Error': "Please provide username/password"}, status="400") username = request.data['username'] password = request.data['password'] try: user = User.objects.get(username=username) if not user.check_password(password): raise User.DoesNotExist except User.DoesNotExist: # if user not found or password is wrong return Response({'Error': "Invalid username/password"}, status="400") if user.is_authenticated: print("user is authenticated") # THIS GETS PRINTED else: print("User is not authenticated") Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ #'rest_framework.authentication.BasicAuthentication', 'Root.authentication.TokenAuthentication.TokenAuthentication' ] } The line if user.is_authenticated: print("user is authenticated") Is running everytime when None is being returned. Any help would be … -
passing multiple value from select element that has the same class to django views
I have a problem to pass multiple value that has the same class in select element(because i use ajax to load the value of the option element) example : <div class="form-group"> <button class="btn btn-theme" onclick="appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> {% for data2 in obj %} <option value="{{data2}}">{{data2}}</option> {% endfor %} </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick="appendFilterBox()">Add</button> <label class="control-label col-md-3">Filter</label> <div class="col-md-4" id="filtbox"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> {% for data2 in obj %} <option value="{{data2}}">{{data2}}</option> {% endfor %} </select> </div> </div> </div> </div> How can i pass all this value that has the same class? because i want to pass 2 value to the views django , and want to print it in console -
Ignoring file in Github and Django
Me and my friend are both working on a project in Django. We are beginners with both GitHub as well as Django. We have managed to use .gitignore to ingore certain files. This is how the .gitignore looks like : .DS_Store groupProject/__pycache__ marketplace/__pycache__ marketplace/migrations/__pycache__ marketplace/templatetags/__pycache__ db.sqlite3 The only issue that we have is that when we try to push we get an error saying that there is a merge conflict for this file 'db.sqlite3' . I have added this file in .gitignore and for some reason it still decides to read it? What should we do? -
How to overwrite a file with same name when uploaded to Django FileField?
I want to overwrite the contents of a file if the filename is the same when an user uploads a file in Django. I have gone through many stackoveflow questions but haven't found what I wanted. Following is my model: class Upload(models.Model): profile = models.FileField(upload_to="uploads/") Code to upload files: files = {'newprofile': open('profiles/blah.jmx', 'rb')} x = requests.post(url, files=files) Any pointers would be appreciated. -
Query Django JSONFields that are a list of dictionaries
Given a Django JSONField that is structured as a list of dictionaries: # JSONField "materials" on MyModel: [ {"some_id": 123, "someprop": "foo"}, {"some_id": 456, "someprop": "bar"}, {"some_id": 789, "someprop": "baz"}, ] and given a list of values to look for: myids = [123, 789] I want to query for all MyModel instances that have a matching some_id anywhere in those lists of dictionaries. I can do this to search in dictionaries one at a time: # Search inside the third dictionary in each list: MyModel.objects.filter(materials__2__some_id__in=myids) But I can't seem to construct a query to search in all dictionaries at once. Is this possible? -
Programatically create nested plugins to display data on Django CMS
I have been trying to retrieve multiple arrays of data from firebase, turn the data into multiple plugins and then pass those into one of my templates. I have been trying to find information on the docs about it but all I can find is this. As well as another individual posted a similar question with a link to a blog but given my little experience with Django CMS I am unable to determine if I have a similar scenario. The code that I have so far is the following. Any guidance would be greatly appreciated, thanks! cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext_lazy as _ from . import models class FeaturedBoxPlugin(CMSPluginBase): model = models.FeaturedBox module = _('My Project') name = 'Featured Box' render_template = 'featured_box.html' allow_children = False class BoxPlugin(CMSPluginBase): model = models.Box module = _('My Project') name = 'Box' render_template = 'box.html' allow_children = False plugin_pool.register_plugin(FeaturedBoxPlugin) plugin_pool.register_plugin(BoxPlugin) models.py from django.utils.encoding import python_2_unicode_compatible from cms.models import CMSPlugin @python_2_unicode_compatible class FeaturedBox(CMSPlugin): title = models.CharField( blank=True, max_length=200, ) image_id = models.CharField( blank=True, max_length=200, ) books = models.CharField( blank=True, max_length=200, ) author = models.CharField( blank=True, max_length=200, ) date = models.CharField( blank=True, max_length=200, ) @python_2_unicode_compatible class Box(CMSPlugin): … -
App does not include some of the files on Heroku
Everything works fine in my local development environment. I don't get a Chrom-Dev console error, but on Heroku my app doesn't find some files. I am using Whitenoise and in my template these files are defined as static: Local dev environment Heroku app This function is defined as follows: async function run() { // load the models await faceapi.loadMtcnnModel(`{% static 'models/mtcnn/mtcnn_model-weights_manifest.json' %}`); await faceapi.loadFaceRecognitionModel(`{% static 'models/fr/face_recognition_model-weights_manifest.json' %}`); await faceapi.loadTinyFaceDetectorModel(`{% static 'models/fd/tiny_face_detector_model-weights_manifest.json' %}`); navigator.mediaDevices.getUserMedia({audio: false, video: true}).then(stream => { video.srcObject = stream; video.play(); }).catch(e => console.warn(e)); } The models are in the following location: What exactly should I configure, can I tell Whitenoice to include these files in the collectstatic command? Or am I missing something else? I don't even see the Models folder in the Chrome Dev Tool in the Source tab. Even in the local development environment, although on the local development all work, but not on Heroku. Link to the heroku app: https://gibbface.herokuapp.com/app/ Link to the GitHub repo: https://github.com/khashashin/gibbface -
Adding a separate field to a form in django template in view
So this is what I want to do: I have a model, that I created a form to fill using forms.Form. But one of the variables is a string but is entered in 3 separate fields in HTML, then concatenated in the view. To simplify the question, I'm gonna post this example model: class Example(models.Model): var1 = models.CharField(max_length=10, default="XXXX-A-1") var2 = models.CharField(max_length=15) var3 = models.IntegerField() str bla bla bla And this is the example form: class ExampleForm(forms.Form): var2 = forms.CharField(max_length=10) var3 = forms.IntegerField() def clean(self): cleaned_data = super(ExampleForm, self).clean() var2 = cleaned_data.get('var2') var3 = cleaned_data.get('var3') if not var2 or not var3: raise forms.ValidationError('Please fill all fields') And this is the template: <form enctype="multipart/form-data" id="regForm" method='POST'> {% csrf_token %} <div class="row"> <div class="col-sm"> <div class="tab"> <label for="formGroupExampleInput">Please Enter Var1</label> <div class="row"> <div class="col"> <input type="text" class="form-control" placeholder="Part 1 of var1" name="var1-part1"> </div> <div class="col"> <select class="custom-select" name="var1-part2"> <option value="A">A</option> <option value="B">B</option> <option value="D">D</option> </select> </div> <div class="col"> <input type="text" class="form-control" placeholder="Part 3 of var1" required="false" name="var1-part3"> </div> </div> {{ form|crispy }} </div> </div> </div> </form> Finally this is the view: @login_required def exampleview(request): var1_part1 = request.POST.get('var1-part1', False) var1_part2 = request.POST.get('var1-part2', False) var1_part3 = request.POST.get('var1-part3', False) var1 = var1-part1 + '-' + … -
Django Queryset - rename original values and re-use original value names
I'm completing a challenge for a job and I'm a little confused with this endpoint's response and I'm running out of time (had almost no internet connectivity for a week and the deadline is tomorrow). I have the following models: Attribute AttributeValue ProductAttribute I need to get all attributes that are linked to a given product ID. I have managed to get the values but I can't give them the correct names in the response. This is what I'm trying to do (code in get_attributes_from_product function): src/api/viewsets/attribute.py from django.db.models import F from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from api import errors from api.models import Attribute, AttributeValue, ProductAttribute from api.serializers import AttributeSerializer, AttributeValueSerializer, AttributeValueExtendedSerializer import logging logger = logging.getLogger(__name__) class AttributeViewSet(viewsets.ReadOnlyModelViewSet): """ list: Return a list of attributes retrieve: Return a attribute by ID. """ queryset = Attribute.objects.all() serializer_class = AttributeSerializer @action(detail=False, url_path='values/<int:attribute_id>') def get_values_from_attribute(self, request, *args, **kwargs): """ Get Values Attribute from Attribute ID """ attribute_id = int(kwargs['attribute_id']) # Filter queryset to find all values for attribute response = AttributeValue.objects.filter(attribute_id=attribute_id).values( 'attribute_value_id', 'value') # Return response if response.exists(): return Response(response, 200) else: return Response(response, 204) @action(detail=False, url_path='inProduct/<int:product_id>') def get_attributes_from_product(self, request, *args, **kwargs): """ Get all … -
How to migrate existing models to Wagtail Page models
I have a existed model,which is EmsanWorks(models.Model). I would like to have a same page model, so I copy a new model and named it EmsanWorksPage and changed models.Model to Page. class EmsanWorksPage(Page): id_works = models.AutoField(primary_key=True) name_r = models.CharField(max_length=255) name_o = models.CharField(max_length=255) title_r = models.TextField() title_o = models.TextField() title_t = models.TextField() birth_y = models.CharField(max_length=20) birth_c = models.ForeignKey(EmsanPays, models.DO_NOTHING, db_column='birth_c',related_name='page_emsanpays_birth_c') gender = models.CharField(max_length=6) dest = models.CharField(max_length=255) media_spec = models.CharField(max_length=255) year = models.TextField() # This field type is a guess. commission = models.CharField(max_length=255) performer = models.CharField(max_length=255) first_perf = models.CharField(max_length=255) duration = models.CharField(max_length=255) perf_c = models.ForeignKey(EmsanPays, models.DO_NOTHING, db_column='perf_c') context = models.TextField() instr = models.TextField() cycle = models.CharField(max_length=255) media_w = models.CharField(max_length=255) setup = models.CharField(max_length=255) prod_loc = models.TextField() prod_per = models.TextField() perf_tech = models.TextField() perf_media = models.TextField() publisher = models.CharField(max_length=255) audio = models.CharField(max_length=255) prog_notes = models.TextField() reception = models.TextField() editor = models.CharField(max_length=255) phono = models.CharField(max_length=255) comment = models.TextField() timestamp = models.DateTimeField() modif = models.TextField() afficher = models.CharField(max_length=3) restricted_editors = models.TextField() class Meta: managed = False db_table = 'emsan_works' However, after migrate I got this error OperationalError at /admin/emsanapp/emsanworkspage/ (1054, "Unknown column 'emsan_works.page_ptr_id' in 'field list'") -
Django - How to store and render a Pandas dataframe/CSV for each model entry?
I have a model that represents a single patient. It stores information such as the patient_name (CharField), weight (IntegerField), height (IntegerField) etc. I extended the save method save(self, *args, **kwargs) to perform a series of calculations/functions (e.g. calculate BMI) to save back to the model. For the extended save() method, it also runs a function that calculates weekly weight loss goals in pandas and saves to CSV (named by patient_name) in a media folder. I'm trying to figure out the best way to display that CSV data back for each patient. Currently, I'm using the DetailView CBV to serve up a detail page for each patient with their new computed model fields (e.g. <p>{{ object.patient_name }}'s calculated BMI is {{ object.bmi }}</p>) There are three ideas I have but I'm not sure if they will work or how to implement it. 1 - I could generate an HTML table instead of CSV, is there a way to render custom HTML snippets from a media folder based on a trait of the model or primarykey id {% media|object.patient_name %}? 2 - I could try to save the pd.DataFrame, CSV (or the string text representation of an HTML table) to a new … -
How to create search box in Django. it is for our project. ooooooooooooooooooooooooooooooooooo
I want to use the search box in Django to our website project. could you write step by step? what do I write on my HTML, views, URL, models etc? -
Django template iframe card information
I have a payment gateway that returns redirect url for getting card information when supplied with right authentication credentials. Now I am comparing two possibilities for displaying this url to users: Redirecting user to given url Loading content of redirect url in django template as iframe From design and end user's aspects, it is obviously better to include content as iframe. However, I suppose that there is security concerns in this option. Is it secure to load such content as iframe in django template? Which measures should be taken to avoid possible security problems? Note: Payment processor didn't provide any clause about iframe in its documentation. -
Display Django Field properties, such as min_value and max_value, in the Template
I have a Django Form with an IntegerField. I give the IntegerField a min_value and a max_value. I would like to DISPLAY that min_value and max_value for the user, so I'm trying to include it in the template next to the input field itself. Seems like this should not be so hard, but it isn't working. :-( Below, the "print" statement in views.py works just fine. So I know that one can access the min_value from the field with just ".min_value". But the min_value in the template does not show up in the browser. Thoughts anyone?? In forms.py class MyForm(forms.Form): somenumber = forms.IntegerField(min_value=0, max_value=12) In views.py: form = forms.MyForm() print(form.fields['somenumber'].min_value) ... context = {'form':form} ... In template: {{ form.somenumber.min_value }}