Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django time limit for votting
I'm new to django, couldn't find a similar example. I have a voting application, how can I set time limits so that I can vote for a limited amount of time, after which the poll will close? Thanks! models.py class Poll(models.Model): question = models.TextField() option_one = models.CharField(max_length=50) option_two = models.CharField(max_length=50) option_three = models.CharField(max_length=50) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) def total(self): return self.option_one_count + self.option_two_count + self.option_three_count -
not able to use "language_tool_python"(python module) in my live django website which i have deploy using digitalocean
After these sometimes its showing error like these: File "/myproject/projectenv/lib/python3.8/site-packages/asgiref/local.py", line 96, in del NameError: name 'TypeError' is not defined [Sat Feb 27 07:35:50.105706 2021] [mpm_event:notice] [pid 751324:tid 139824140430400] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Sat Feb 27 07:35:50.105847 2021] [core:notice] [pid 751324:tid 139824140430400] AH00094: Command line: '/usr/sbin/apache2' [Sat Feb 27 07:35:56.135397 2021] [mpm_event:notice] [pid 751324:tid 139824140430400] AH00491: caught SIGTERM, shutting down [Sat Feb 27 07:35:56.255237 2021] [mpm_event:notice] [pid 751424:tid 139981498731584] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Sat Feb 27 07:35:56.257137 2021] [core:notice] [pid 751424:tid 139981498731584] AH00094: Command line: '/usr/sbin/apache2' [Sat Feb 27 07:39:12.124903 2021] [mpm_event:notice] [pid 751424:tid 139981498731584] AH00491: caught SIGTERM, shutting down [Sat Feb 27 07:39:12.227200 2021] [mpm_event:notice] [pid 751557:tid 140119884995648] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Sat Feb 27 07:39:12.227313 2021] [core:notice] [pid 751557:tid 140119884995648] AH00094: Command line: '/usr/sbin/apache2' And sometimes.... [Sat Feb 27 07:45:43.154088 2021] [wsgi:error] [pid 751814:tid 139723339921152] [remote 103.212.140.12:54090] File "/myproject/CalConT/mysite/views.py", line 6, in [Sat Feb 27 07:45:43.154091 2021] [wsgi:error] [pid 751814:tid 139723339921152] [remote 103.212.140.12:54090] from language_tool_python import LanguageTool as LT [Sat Feb 27 07:45:43.154100 2021] [wsgi:error] [pid 751814:tid 139723339921152] [remote 103.212.140.12:54090] ModuleNotFoundError: No module named 'language_tool_python' Exception ignored … -
How to convert "None" to null in custom permission in DRF?
I'm currently learning Django Rest Framework and currently stuck on a problem which is kind of impossible for me to figure out. I'm providing you an example, just to make the picture clearer. from rest_framework.exceptions import PermissionDenied from rest_framework.permissions import BasePermission class CheckAuthentication(BasePermission): def has_permission(self, request, view): authenticated = request.auth if not authenticated: raise PermissionDenied( { "exception_data": None } ) return True Ok So, in the above example I want to response to be like the following JSON { "exception_data": null } but instead of it, I'm getting { "exception_data": "None" } is there any way I can get the desired JSON ?? -
Unable to render the HTML page in Django
I am trying to return the HTML page on the success of login but unable to render in the web. Do I need to do add in urls.py or views.py in Dashboard? the sample folder structure of my project login views.py Dashboard templates dashboard sign_up_otp_pop_up.html if login=='Success': return render(request, 'dashboard/sign_up_otp_pop_up.html', {'content':content}) else: return 400``` -
What is AH00489: resuming operations in apache?
When I restart the apache2 server I find some thing like this in log file: [mpm_event:notice] [pid 19078:tid 139998808778624] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations Some part of that I understood is that it is resuming the required operatons since we restarted apache server. I'm not clear about: AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured I'm using python3.6 as default and for my venv. I find 3.5.2 in above log. I doubt if this is causing me further issues like wsgi errors. Can some one tell me if I need to congigure it to python 3.6? If so, how should I change the configuration -
Initial response NOT contains the value of a CustomField Django
These are the packages I'm using django==3.0.5 djangorestframework==3.11.0 markdown==3.2.1 django-filter==2.3.0 Pillow==7.0.0 psycopg2==2.8.5 djongo==1.3.3 django-cors-headers==3.5.0 sqlparse==0.2.4 I have a model like below class IdField(models.Field): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def db_type(self, connection): return "char(1000)" def pre_save(self, model_instance, add): print("pre_save"+ str(uuid.uuid4())) return uuid.uuid4() def from_db_value(self, value, expression, connection): return self.to_python(value) def to_python(self, value): print("print(value)",value) return value class Parishioner(models.Model): def _age(self): return date.today().year - self.dob.year """Parishioner model""" id = IdField(unique=True, primary_key=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() age = property(_age) GENDER_CHOICES = [("Male", "Male"), ("Female", "Female"), ("Other", "Other")] gender = models.CharField(max_length=10, choices=GENDER_CHOICES) address = models.CharField(max_length=1000) fathers_name = models.CharField(max_length=500) mothers_name = models.CharField(max_length=500) baptism_certificate = models.ImageField(null=True, upload_to=upload_image) marriage_certificate = models.ImageField(null=True, upload_to=upload_image) def __str__(self): return self.first_name + " " + self.last_name When I send my POST request my endpoint api/parishioners/ I get a successful initial response like below { "id": "", "first_name": "John", "last_name": "Perera", "dob": "1988-02-27", "age": 33, "gender": "Male", "address": "No 40, Katukurunda", "fathers_name": "JohnF", "mothers_name": "JohnM", "baptism_certificate": null, "marriage_certificate": null } as you can see my "id" field is EMPTY But when I check database id filed is actually populated. Then sent a GET request again to my end point api/parishioners/ I got below response [ { "id": "9aae45d2-86fc-4058-80f6-c38fa37ef597", … -
django updateview form related model
My models.py file is as class Post(models.Model): title = models.CharField(max_length=256) body = models.TextField() category = models.ManyToManyField("PostCategory", blank=True) class PostImages(models.Model): image = models.ImageField(upload_to="..") post = models.ForeignKey("Post", on_delete=models.CASCADE, related_name="images") and forms.py class UpdateBlogForm(forms.ModelForm): class Meta: model = Post fields = "__all__" exclude = ("blogger", "view") widgets = { "language": forms.Select(attrs={"class": "form-control"}), "title": forms.TextInput(attrs={"class": "form-control"}), "body": forms.Textarea(attrs={"row": "25", "class": "form-control"}), } I've an updateview as class BlogPostUpdateView(generic.UpdateView): model = Post form_class = UpdateBlogForm success_url = "." template_name = "blog/dashboard_components/blog_dashboard_eidtpost.html" in updateview i have just my UpdateBlogForm form, any way to edit the post related images(add/delete). Any idea how to go on?! -
How to add hyperlink in html django for specific txt in td
sample data displayed in UI This is regards django in python In my column that includes urls i want to identify them and make it clickable by adding into href tag urls can be https or http and each column urls are different my concern is we are using Html python and django combination -
Django: a canconical method for a package to offer new template tags?
I'm building a package of Django extensions and one thing I'd like to include in it now are template tags (and filters). The question is, how does a package provide template tags to a Django project? I imagine in a Django app, in the templatetags directory adding a line to two to access them. Something like: from mypackage.template import tags say. Or if need actually running something to register them, possibly as built-in tags a la: https://djangosnippets.org/snippets/342/ from mypackage.template import register_tags register_tags() Before I experiment this to death (given I can't find any docs or example yet) I'm curious if there's a canonical approach to this as there are many Django extension packages. To be honest if I could reliably find one that provides template tags it could serve as an example of course. Any tips in this regard are appreciated. -
Django Rest Framework how to filter nested data?
I want to filter the nested data, and these are my serializers and views Serializers : class PenaltySerializer (serializers.ModelSerializer): employee_identity = serializers.CharField(source="employee.employee_identity") month = serializers.SerializerMethodField() year = serializers.SerializerMethodField() def get_month(self,obj): value_start_date = obj.start_date month_value = value_start_date.strftime("%b") return bulan_value def get_year(self,obj): value_start_date = obj.start_date year_value = value_start_date.strftime("%Y") return year_value class Meta: model = Penalty fields = ('id','employee','employee_identity','type','start_date','end_date','month','year') class EmployeeSerializer (serializers.ModelSerializer): penalty = PenaltySerializer(many=True,read_only=True) class Meta: model = Employee fields = ('employee_identity','full_name','penalty') Views: class EmployeeViewSet(viewsets.ModelViewSet): queryset = Employee.objects.all() serializer_class = PegawaiSerializer http_method_names = ['get','head'] pagination_class = LimitPagination class PenaltyViewSet(viewsets.ModelViewSet): queryset = Penalty.objects.all() serializer_class = PenaltySerializer http_method_names = ['get','head'] pagination_class = LimitPagination filter_backends = [filters.SearchFilter,DjangoFilterBackend] filter_fields = ['employee','type'] search_fields = ['^start_date'] class DetailDataEmployeeViewSet(viewsets.ModelViewSet): queryset = Employee.objects.all() serializer_class = EmployeeSerializer http_method_names = ['get','head'] pagination_class = LimitPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['id','employee_identity'] the result I have without date filter "results": [ { "id": 13886, "employee_identity": "A3014", "full_name": "AAAA", "penalty": [] }, { "id": 13887, "employee_identity": "A3015", "full_name": "BBB", "penalty": [ { "id": 1, "employee": 20924, "employee_identity": "A3015", "type": "low", "start_date": "2021-01-01", "end_date": "2021-01-02", "month": "Jan", "year": "2021" }, { "id": 2, "employee": 20924, "employee_identity": "A3015", "type": "low", "start_date": "2021-02-11", "end_date": "2021-02-12", "month": "Feb", "year": "2021" } ] } And the result I want if … -
Django Admin Panel: Show/Hide Fields If Specific Value Is Selected In A Dropdown
What am I doing wrong? In django admin-panel I want to show/hide field(s) based on the choice dropdown. Also the, choice dropdown lies on parent foreign-key related model and the fields that are to be shown/hidden lies in child model or as an stacked inline. I've followed this solution(stack overflow), but no success. models.py from django.db import models CHOICES = ( ('video', 'Video'), ('text', 'Text'), ('question', 'Question'), ) class Section(models.Model): content_type = models.CharField(max_length=32) @property def contents(self): return self.content_set.all() class Content(models.Model): content = models.ForeignKey(Section, on_delete=models.DCASCADE) video = models.FileField() text = models.TextField() question = models.CharField(max_length=512) admin.py from django.contrib import admin from .models import Section, Content from .forms import DropdownModelForm class ContentInline(admin.StackedInline): model = Content fieldsets = ( (None, { 'fields': (('video',),), 'classes': ('vid',) }), (None, { 'fields': (('text',),), 'classes': ('txt',) }), (None, { 'fields': (('question',),), 'classes': ('ques',) }) ) class Media: js = ('one/js/base.js',) @admin.register(Section) class SectionAdmin(admin.ModelAdmin): form = DropdownModelForm inlines = (ContentInline,) forms.py from django import forms from .models import Section, CHOICES class DropdownModelForm(forms.ModelForm): class Meta: model = Section fields = ('content_type',) widgets = { 'content_type': forms.Select(choices=CHOICES) } base.js (function($) { $(function() { var selectField = $('#id_content_type'), verified_1 = $('.vid'), verified_2 = $('.txt'), verified_3 = $('.ques'); function toggleVerified(value) { if (value … -
Why is there time delay using asyncio in django
I'm trying to make a system that judges code(python files) in given time with asyncio. This is how it works: In judge.py, it calls processor.py and write the output to a text file. processor.py basically excutes the given python file and track the time the code used. judge.py import asyncio, time async def cmd(): try: proc = await asyncio.create_subprocess_shell( "processor.py > output.txt", shell=True, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL) await proc.communicate() except asyncio.CancelledError: proc.terminate() print("X") PROCESS_TIME_BOUND = 5 acceptable_time = 0.1 async def run(): try: await asyncio.wait_for(cmd(), PROCESS_TIME_BOUND + acceptable_time) print("A") except asyncio.TimeoutError: print("B") loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) loop.run_until_complete(run()) As you can see. There's a line await asyncio.wait_for(cmd(), PROCESS_TIME_BOUND + acceptable_time) because the async function takes time to excute way longer than the time that the python file actually takes. In my computer, while the python file ends in 0.000001 seconds, the async function takes around 3.4 seconds. processor.py: import os, time, sys start = time.time() with open(sys.argv[1],'r') as f: exec(f.read()) end = time.time() print("PROCESS ENDED WITHTIN %.20f SECONDS" % (end-start)) Why and how does this time delay occur? Are there any ways to fix the time delay? Thanks in advance. -
Getting Input of Date and storing in Django Admin
I am trying to build an app where I am creating a form and getting different date inputs from user. However I was able to capture the date on which the input was taken but not sure how can I capture the date which users give input of....for example just like date of birth or something. I am writing down the code below wherever I have made the changes, form1.html <form method="POST" action="/form1/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Security Stamp Date</label> <input type="date" class="form-control" id="exampleFormControlInput1" name= "stamp_date" required> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> views.py from django.shortcuts import render, HttpResponse from inventory_app.models import Form1 import datetime from .models import Form1 if request.method == "POST": stamp_date = request.POST.get('stamp_date') form1 = Form1(stamp_date = datetime.date(stamp_date)) form1.save() return render(request, 'form1.html') models.py from django.db import models class Form1(models.Model): stamp_date = models.DateField() The error which I get after clicking the "Submit button" after inputting the date is : After going to admin panel (http://127.0.0.1:8000/admin/inventory_app/form1/) inside my app this is the error I get Thanks a lot in advance, If you need any more information please comment and I will reply to it asap. -
tradingview webhook alert in python django
I was trying to make a webhook for getting alert from tradingview it was completely new for me so can anyone help me to create a webhook in Django -
How To Match Not Related Tables in Django
I have two tables which are not related- class DedupeDataModel(models.Model): clean_name = models.CharField(max_length=200) class SalesforceDataModel(models.Model): clean_name = models.CharField(max_length=200) salesforce_id = models.CharField(max_length=50) I want to match the clean_name column in both the tables to get the salesforce_ids from SalesforceDataModel table. I have tried select_related to match the tables but since they are not related i am not getting results. Please give suggestions. Thanks in advance!! -
wsgi errors while integrating with apache configuration
I developed django application with python3.6. And when I intergrate wsgi with apache I encountered with the following errors in apache error log. My directory strucute: Finance-Management | +--fin_man_venv (this is vevn) | +--fin_man | +--manage.py | +--fin_man | +--wsgi.py [wsgi:error] [pid 5408:tid 139677118859008] [remote 49.37.170.4:34325] mod_wsgi (pid=5408): Target WSGI script '/home/ubuntu/Finance-Management/fin_man/fin_man/wsgi.py' cannot be loaded as Python module. For the above one I checked if there are any mismatch of wsgi python versions. However, I installed using: sudo apt-get install libapache2-mod-wsgi-py3. I tried this even: https://github.com/GrahamDumpleton/mod_wsgi/issues/335#issuecomment-401235042 and changed the following: find /home/ubuntu/Finance-Management/fin_man_venv/lib/python3.6/site-packages/django -name '*.py' -exec chmod 0644 {} \; find /home/ubuntu/Finance-Management/fin_man_venv/lib/python3.6/site-packages/django -type d -exec chmod 0755 {} \; wsgi file is compiled with same python version as in venv. Changed ownership for project too: sudo chown :www-data /home/ubuntu/... [wsgi:error] [pid 5408:tid 139677118859008] [remote 49.37.170.4:34325] mod_wsgi (pid=5408): Exception occurred processing WSGI script '/home/ubuntu/Finance-Management/fin_man/fin_man/wsgi.py'. [wsgi:error] [pid 5408:tid 139677118859008] [remote 49.37.170.4:34325] File "/home/ubuntu/Finance-Management/fin_man/fin_man/wsgi.py", line 2, in [wsgi:error] [pid 5408:tid 139677118859008] [remote 49.37.170.4:34325] from django.core.wsgi import get_wsgi_application I verified if wsgi.py compiles fine in venv. And it compiles without any exceptions. For the above three errors in apache log, here is my wsgi.py: import os, sys from django.core.wsgi import get_wsgi_application sys.path.append('/home/ubuntu/Finance-Management/fin_man') sys.path.append('/home/ubuntu/Finance-Management/fin_man_venv/lib/python3.6/site-packages') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fin_man.settings') … -
Customize email setting in PasswordResetView django
I found a tutorial on how to include username when resetting the password using this tutorial. My question is how to customize the email sending function in PasswordResetView ? I already have my own customized email sending function but I dont know how to connect it. Another thing is, when email is sent, the FROM portion is not using the host that I setup in my settings.py How I send email: def SendEmail(mail_subject, mail_message, mail_to): context = {} try: send_mail(mail_subject, mail_message, settings.EMAIL_HOST_USER, [mail_to], html_message=mail_message, fail_silently=False) return HttpResponse("SUCCESS") except BadHeaderError: context['message'] = "Email has encountered some problems." return HttpResponse("SUCCESS") -
How to use Modelform with foreign key in django with same foreign key with multiple tables?
Recently I am creating a resume maker website using django. How can I save data from modelforms to database by using foreign keys. I want to save education details in education table with related user information. I am not able to submit data of education form. Here's my code, Models.py from django.db import models # Create your models here. class Person(models.Model): first_name = models.CharField(max_length=25) middle_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField() mobile_no = models.IntegerField() age = models.IntegerField() dob = models.DateField() address = models.TextField() github = models.URLField(blank=True, null=True) linkedin = models.URLField(blank=True, null= True) website = models.URLField(blank=True,null = True) def full_name(self): return " ".join([self.first_name, self.middle_name, self.last_name]) class Education(models.Model): Degrees = ( ('PhD','PhD'), ('Mtech/MA/MSc/MCom/MBA','Masters'), ('BE/Btech/BA/BSc/BCom','Bachelors'), ('12th','High School') ) person = models.ForeignKey(Person,on_delete=models.CASCADE) qualification = models.CharField(choices=Degrees,max_length=25) institution = models.CharField(max_length=75) board = models.CharField(max_length=75) start_yr = models.DateField() end_yr = models.DateField() cgpa = models.FloatField(blank=True,null=True) percent = models.FloatField(blank=True, null=True) Forms.py from django import forms from django.forms import ModelForm,modelformset_factory,DateField from django.conf import settings from .models import * class PersonForm(ModelForm): class Meta: model = Person fields = "__all__" class EducationForm(ModelForm): class Meta: model = Education exclude = ('person',) views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .forms import * from .models import * forms = { "person":PersonForm, … -
Ajax adding new rows to the table and saing each rows to the db when creating new row
how to create rows automatically by using ajax and show add row button to the last field and remoe row button to all other fields and pass data to the db when we add new rows and remove curresponding data from the database when we click drop button -
My newly registered user can login to my django web app
I am new to the community. I usually am able to just find my answer, but I have been searching and searching, and can't seem to find anything similar to what I've got going on. I have a ModelForm set up to register new users. I got it to work, and send information over to the sqlite database. However, when I try to log the newly registered user in it says: "Please enter a correct username and password. Note that both fields may be case-sensitive." login.html: {% extends 'app/register.html' %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> <a href="{% url 'index' %}">Back to Homepage</a> <br> <a href="{% url 'password_reset' %}">Reset password</a> <br> <a href="{% url 'register' %}">Register</a> {% endblock %} views.py from django.contrib.auth import login from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from datetime import datetime from django.http import HttpRequest from django.shortcuts import render, redirect from django.urls import reverse from . import forms from django.contrib import auth ... def register(request): if request.method == "GET": form = forms.Registration(request.GET) return render( request, "app/register.html", {"form": form} ) elif request.method == "POST": form = forms.Registration(request.POST) if form.is_valid(): user = … -
Not showing some images in Django
I am out of my depth and would like to ask you about my challenge with some images that won't load on my project. Basically, some images that I use for banners and carousel of my website is loading but my images in the media folder is what is not showing up with error "GET /images/uploads/2021/02/11/pexels-carly-jamieson-1478450.jpg HTTP/1.1" 404 4704 . I have already done python manage.pycollectstatic plenty of times. Basically, the images that are not showing up are the ones that I need for my ckeditor image uploader. They are all in the media folder of my root directory. The images that are showing up is in my static folder under images folder. My custom css is also working fine. I'm not sure why when I upload files to ckeditor, I can see the files saves and uploaded to the folder under media but they just wont display! The thing is, this used to work before and now it just does not. My settings.py look like """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import … -
How to add username on PasswordResetView
In Django's PasswordResetView, users can reset their password by supplementing email address. How to also add username in PasswordResetView? I actually don't know where to start or how to implement this. Currently my url: from django.contrib.auth import views as auth_views ... path('reset_password/', auth_views.PasswordResetView.as_view(template_name="reset_password.html"), name="reset_password"), -
Initial migrations after cloning repo - "related model cannot be resolved"
I'm working with a few people on an app. I'm doing front end. Recently, I've messed up migrations. After trying to fix them for a few hours, I've dropped all tables, and cloned the repo again. Since there are no migrations files, I run manage.py makemigrations (for some reason it does not detect all apps, just one of them, and I have to call makemigrations manually for each of them). Then, I run manage.py migrate. I get the following error: Related model 'User.user' cannot be resolved Since User table has OneToOneField relation to User table. Also, other tables depend on each other as well. My take on this problem would be commening out all the fields that cause the problem, making migrations, uncommenting them, and making migrations again. I guess this is far from optimal though. -
Required field issues when submitting Django formset
I'm having trouble with field validation in a Django formset derived from a model. Here are relevant models in my models.py: class Qualification(Data): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) amount_approved = models.PositiveIntegerField(blank=True, null=True) expiration_date = models.DateField(blank=True, null=True) class QualificationDocument(models.Model): qualification = models.ForeignKey(Qualification, on_delete=models.CASCADE, related_name='documents') file = models.FileField(upload_to='qualification_docs/%Y/%m') name = models.CharField(max_length=128) description = models.CharField(max_length=256, blank=True, null=True) upload_date = models.DateTimeField(auto_now_add=True) My views.py file includes this to present and process the a formset that allows the user to add one or more QualificationDocuments to the database: q = Qualification.objects.get(id=q_id) QualificationDocumentFormSet = forms.inlineformset_factory(Qualification, QualificationDocument, fields=('file', 'name', 'description'), widgets={ 'name': forms.TextInput(attrs={'placeholder': 'Name'}), 'description': forms.TextInput(attrs={'placeholder': 'Description'}) }, extra=1) if request.POST: formset = QualificationDocumentFormSet(request.POST, instance=q) if formset.is_valid(): formset.save() else: formset = QualificationDocumentFormSet(instance=q) # Render formset in Django template here And the template file includes this: <form id='upload-form-{{ q.id }}' method="post" action="{% url 'submit_and_refresh' %}"> {% csrf_token %} {{ formset.management_form }} <div id="form_set"> {% for f in formset.forms %} {{ f.non_field_errors }} {{ f.errors }} <div class="doc-form"> <div class="new-qual-doc-params"> {{ f.id }} {{ f.file }} {{ f.name }} {{ f.description }} </div> <div class="new-qual-doc-delete">{{ f.DELETE }}<small>Delete</small></div> </div> {% endfor %} </div> <button type="submit" class="btn btn-block">Save</button> </form> Two issues. No required fields. This template doesn't produce required tags in inputs like … -
Auto Increment Non-primary Key Field in Django with PostgreSQL
I've got an abstract base class from which many models inherit. It defines a field called order. I've built this into the system because I often need to order my objects in arbitrary ways (for listing in template, for example). However, I often find that the order fields get away from me and I lose track (I'm allowing null=True and blank=True). I'd like to have a way to ensure that whenever an object of model type with order is created, Django looks to other objects of the same type and checks the highest order number and increments accordingly. Is this possible? I've tried making the field order auto increment (with AutoField) but Django complains saying I've got an auto field already, the primary key. I'd use the primary key ID but this is assigned arbitrarily and doesn't maintain the order I want.