Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I write this command "python2 main.py" I get those problems
Traceback (most recent call last): File "main.py", line 122, in <module> driver = webdriver.Chrome() File "/usr/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__ desired_capabilities=desired_capabilities) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir -
I keep receiving ValueError on my Django Python Forum application
I'm trying to create a form where users can add a new topic within a category. Then the users will be able to comment on each topic. Everything was working up until I tried adding the form page for new_topic The error I receive: ValueError at /new_topic/ The view speak_space.views.new_topic didn't return an HttpResponse object. It returned None instead. Heres the code for my view.py and urls.py files: view.py from django.shortcuts import render, redirect from .models import Category from .models import Topic from .forms import TopicForm def index(request): """The home page for speak_space""" return render(request, 'speak_space/index.html') def categories(request): """Show all categories.""" categories = Category.objects.order_by('date_added') context = {'categories': categories} return render(request, 'speak_space/categories.html', context) def category(request, category_id): """Show a single category(tribe) and all of its topics(convos).""" category = Category.objects.get(id=category_id) topics = category.topic_set.order_by('-date_added') context = {'category': category, 'topics': topics} return render(request, 'speak_space/category.html', context) def topics(request): """Show all topics within a category(tribe).""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'speak_space/topics.html', context) def topic(request, topic_id): """Show a single topic(convo/post) and all of it's replies.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'speak_space/topic.html', context) def new_topic(request): """Add a new conversation topic.""" if request.method != 'POST': # No … -
Using django-twilio package forgery protection is creating forbidden 403 error
I am using django-twilio package for forgery protection django-twilio forgery protection docs I have a django texting app that is being used to both send automated messages directly through my cellphone messenger and also from my website while logged in. When DJANGO_TWILIO_FORGERY_PROTECTION = False, both platforms using my django texting app work. When DJANGO_TWILIO_FORGERY_PROTECTION = True, only cellphone messenger works, and website gets 403 Forbidden. How can this be fixed while maintaining as much security as possible and keeping the same app as functional for both cellphone messenger and website. I know issue is to do with @twilio_view decorator send-text.html <form action="{% url 'text-send' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="text" name="Body" required> <input type="submit" > </form> Here is my texting app: @twilio_view def sendtext(request, reviewpk): if request.method == "POST": ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) message_body = request.POST['Body'] client.messages.create( to= "+13231342344", from_="+14571342764", body=message_body ) return confirm_things(request) def confirm_things(request): if 'HTTP_X_TWILIO_SIGNATURE' in request.META: resp = MessagingResponse() resp.message("good job message was sent") return HttpResponse(str(resp), content_type='text/xml') return HttpResponseRedirect(reverse('dashboard')) urls.py urlpatterns = [ path('textsend/', views.sendtext, name='text-send'), path('dashboard/', views.dash, name='dash'), ] -
How to validate multiple user ids in m2m field
I have on models name 'company' and user model has foreign-key of 'company'. now I have one model name 'group' which is m2m with the user. I am getting a comma-separated id's of the user in request but now I have to check that those ids belong to the requested user's company if yes then pass else remove them. I have customized validate method in serializer it works but for that, I have to use for loop and make a query in models its kind of slowing down response. so I am looking for another alternative solution like how can i use this validation in permission (BasePermission) or somewhere else to avoid loop and queries. -
The view SugarNoter.views.Index didn't return an HttpResponse object. It returned None instead
Whenever a New user is going to register, after that I get this error. even I return HttpResponse The view SugarNoter.views.Index didn't return an HttpResponse object. It returned None instead. views.py def Index(request): if request.method=='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') passwd = form.clean_password2() user = auth.authenticate(username=username, password=passwd) auth.login(request, user) return redirect(f'users/{str(request.user)}') else: context = { 'form':UserCreationForm() } return render(request, 'index.html', context) html file {% load crispy_forms_tags %} <div class="container"> <div class="col-sm-6 my-5 mx-auto"> <div class="card align-items-center justify-content-center"> <div class="card-body"> <form method="POST"> {% csrf_token %} {{ form | crispy }} <button type="button" class="btn btn-danger" onclick='window.location="login"'>Login</button> <button type="submit" class="btn btn-success">Sign Up</button> </form> </div> </div> </div> </div> What should I do? -
Unable to embed the image file in the template uploaded by user
I am trying to load the uploaded image in the template. The image is getting correctly uploaded and the url is also correct but I am still getting the 404 error. The error is:- Failed to load resource: the server responded with a status of 404 (Not Found) template {% if complaint.media %} <img src="{{ complaint.media.url }}" height="100px" width="100px" > {% endif %} settings.py MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' models.py class Complaints(models.Model): media = models.ImageField(upload_to='complaints_image',blank=True) forms.py class ComplaintForm(forms.ModelForm): class Meta(): model = Complaint fields = ('department','heading','text','media',) -
django two foreignkey filtering
I already tried this to my views "fees = SchoolFeesMasterList.objects.filter(Education_Levels=studentenroll.Education_Levels)" and this "fees = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels)" and none of them work. \\model class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) \\views def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType}) else: . . . return render(request, 'Homepage/EnrollmentForm.html', {"students": students, "edulevel": edulevel, "payment": payment, 'sched': sched, 'subj': subj, "year": year, "doc": doc,"education":education,"payments":payments}) can you guys help me on how to filter the StudentsEnrollmentRecord(Education_Levels) to SubjectSectionTeacher(Education_Levels) because it is really hard to understand the django-filter, i waste already 2 days for this error. I just want to filter the SubjectSectionTeacher(Education_Levels) using StudentsEnrollmentRecord(Education_Levels) -
Sanitizing markdown using bleach
I'm using Django with markdown and bleach to sanitize markdown. Most xss tricks are filtered now using Bleach however, I can't find a way against this: <img src="" onerror=alert(/XSS/) /> or hello <a name="n" href="javascript:alert('xss')">*you*</a> Users can use things like: [Hello](javascript:alert\('xss'\)) What's the best way to sanitize this in Python/Django ? -
cannot install Django under virtualenv
when I type command :"pip install django", show error message: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied when I try command :"pip install django --user",show error message: ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. I want to install Django under virtualenv on my Mac ,but as the summarize show , my permission denied me , and I make sure I am the root user . (newVENV10112019) braveru@BraveRudeMacBook-Air bin % pip install django Collecting django Using cached https://files.pythonhosted.org/packages/b2/79/df0ffea7bf1e02c073c2633702c90f4384645c40a1dd09a308e02ef0c817/Django-2.2.6-py3-none-any.whl Collecting pytz (from django) Using cached https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl Collecting sqlparse (from django) Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Installing collected packages: pytz, sqlparse, django ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Users/braveru/CodingNow/VENV/newVENV10112019/lib/python3.7/site-packages/pytz' Consider using the --user option or check the permissions. (newVENV10112019) braveru@BraveRudeMacBook-Air bin % pip3 install django --user ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. I try all the way that is search from google , and I also re-install my MacOS , the same will happen . -
How can I build a form like that ?? (I’m usine Django)
enter image description here I really don’t Know how to get something like that with django models -
My django not works properly, version 2, i can't understand?
my problem starts when i try to include my files with a extension .urls here the code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('' include('hello_world.urls'), ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["personal_portfolio/templates/"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request" "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] my admin.site.urls file: >> https://localhost.com my hello_world.urls file: >> <h1>hello world</h1> -
One model to have children and parents objects in Django
I am trying to create a tool that replicates the use of an EXCEL sheet. The ideal use is to have: -Sections (Parent objects) -Fields to be filled (Children objects of given section) Ideally, I am looking for this to be in one Model class called Car specifications (for example). A typical object of this would have a one-to-one relationship with model Car. Each Car Specification object would have Sections, e.g Car Headlights, and there are a number of fields to be filled for Car Headlights section (e.g type, size, manufacturer..etc). It can be text, date, file.. or even another model object(s). My question is: What would be the best way to approach this? I apologies if my terminology usage is wrong, I'm still a python-django beginner :) Thank you in advance! An example Excel sheet might look like this: 1.0 Car Headlights 1.1 Headlight type: 1.2 Headlight shape: 1.3 Compatible models: this is a list/one to multi relationship 2.0 Windows# 2.1 Glass type: 2.2 Country of origin: 2.3 Tint level: And so on -
Django model for table with foreign keys to multiple tables in one column
I have inherited a table that has data that has foreign keys to different tables that share a column. The dedupe_sig column is a virtual column with a uniqueness constraint where the place names are sorted. It's used to ensure that you don't try to store both Toledo S Ann Arbor and Ann Arbor N Toledo: the table with the directions says that S and N are opposites. location_type place1 relation place2 dedupe_sig --------------- ------------- ---------- -------------- ---------------------------------- city Youngstown SE Cleveland city Cleveland Youngstown neighborhood Campus S Clintonville neighborhood Campus Clintonville region Midwest NW The South region Midwest The South city Cincinnatti NE Lexington city Cincinnatti Lexington state Ohio E Indiana state Indiana Ohio state Illinois S Wisconsin state Illinois Wisconsin What I'd like to know is if there's a sane way for me to add this table to my Django models? It seems like it should be a ManyToManyField, but I'm not sure how to handle implementing it without changing the schemata (either by making separate join tables for the different location types or by moving all the location data into a single table that links to itself for arbitrary nesting hierarchy). -
Boolean condition doesn't work in django template
i'm trying to add in my template a simple "s" to a string depending on the number of answers : The house contains {{nb_results2}} {% if nb_results2 >= 2 %}rooms{% else %}room{% endif %} {{nb_results2}} appears in my page (it's a str of a count), but whatever the number is, only "room" is displayed. Is it something related to the string nature of my nb_results variable ? Thanks for your help ! -
How to delete a kwargs argument if it is empty?
I am working with arguments, variables that I go through GET and I receive in my view to do my queryset, the problem is, if I receive an empty argument does not work, I explain more with code. My url example: http://127.0.0.1:8000/my_view/?val1=xd&val2=lol&sox= My view.py val1 = request.GET.get('val1', None) val2 = request.GET.get('val2', None) foo = request.GET.get('lol', None) filters = { 'code_field': val1, 'tiempo_field__lte': val2, 'code_id__exact': foo, } my_query = Babies.object.filter(**filters) In this example sox is empty, that's why it doesn't work for me I think, what would be the elegant way if an argument comes empty is not taken in the query. -
Image getting saved twice in media folder django Imagefiled PIL
I am trying to resize the image in form's save method that extends modelform. I open the image and resize it then saves it using PIL in the save method of form. But in the media folder that has all the save images it saves two images one that is resized and other that was original. I guess that must be because of the form's save getting called after PIL's save has been called. Is there a way to save only the resized image. def save(self): mymodel = super().save(commit=False) checkpath = mymodel.picture1 image = Image.open(checkpath) image = image.resize((33,33), Image.ANTIALIAS) image.save(checkpath.path) mymodel.save() It saves two images in media folder first is a.jpg that is the orignal name of the image and other is akjdsfj.jpg random name. The second must have been formed when model's save got called. Is there a way to stop this behaviour and save only one image that is resized. -
Django run external py script on html click
since im beginner to Django framework and python language. I need help. I need to run external python script from html button also to get value from html and show the output back to web page. Example workflow: Input text : "hello", click "submit" on html button. Run world.py : receive "hello" as variable. Add "world" Post it back to the same html page and shows "helloworld" . -
Django dynamic forms - How to setup dynamic forms click event
Basically, I am rendering a template and passing a python dictionary to the template that contain some image urls obtained from the model. My task is to when user clicks on any image. It submits that image url back to views.py file without refreshing the page and then it calls an api in view which generates a grey scale image which is passed as JsonResponse in django template. And then I show it by using document.getElementById('classified_image'). My problem is how do I setup the id of form/list and how to make a single click event to handle them view.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.http import HttpResponse, JsonResponse from django.views.generic import View from example import function_used_in_app, open_image from classifier.models import UserImage import json class HomeView(View): def get(self, request): template_data = { 'images': UserImage.objects.all(), 'ids': UserImage } ids = Counter() return render(request, 'classifier/base.html', template_data) def post(self, request): if request.FILES.get('uploaded_image'): image = request.FILES["uploaded_image"] UserImage.objects.create(image=image).save() original_image = UserImage.objects.all().last().image.url else: original_image = request.POST['selected_image'] function_used_in_app(open_image(original_image[1:]), 0.4, 0.5, 0.6, 0.1, 0.2) classified_image = '/media/classified_images/example_gray.png' print(original_image) print(classified_image) return JsonResponse({'error': False, 'message': 'Uploaded Successfully', 'original_image': original_image ,'classified_image': classified_image}) base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta … -
How can I block calls from unknown domains/IP to my REST API?
I want to block calls to my Django REST API (www.backend_django.com) from unknown origins, for example, I have a website under the domain "www.example.com" I want to allow only to this site to be able to do request to my API. In order to do this, I have configured Django-Cors-Headers in the following way: DEBUG = False ALLOWED_HOSTS = ["www.backend_django.com", "backend_django.com"] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'https://backend_django.com', 'https://www.backend_django.com', 'https://example.com', 'https://www.example.com', ) CSRF_TRUSTED_ORIGINS = [ 'backend_django.com', 'example.com'] In order to test it, I have done a call from Postman using my computer and have successfully done a request still to the API. Did I set up something bad in the settings? How can I archive this? -
Github Oauth Web Flow CORS
I have a project that consist of a Django rest server back-end and a vue js front end. I am trying to authenticate with GitHub using their oauth2 web flow. So far I seem to get blocked by CORS or Github returns not found. I have tried a different couple approaches but so far have had the best results with the following: In my front end I authenticate with GitHub which returns an temporary code. I then post the code to my back-end which then makes a request to get an access token from GitHub which returns a CORS error. I am assuming this is because the front-end and back-end servers are on different domains which is causing problems. The interesting thing to me is if I copy the code and then make the call in postman it works fine and returns the access code. Why does it work in postman which isnt on the same domain and what I am doing wrong? Some points that maybe of interest: I have Django CORS installed my GitHub callback points to my front-end I tried making all the calls from the front end but still get blocked by CORS The CORS error … -
Click on username and get redirected to the profile
I'm writing an application and I want to be able to click on the username and go to the profile of the user. I have searched a lot around and didn't find anything that I wanted. I have something like this: I want that when I press on Admin, I will be redirected to the profile with all the information that is saved through the Model that I created. class Farmer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=50) age = models.IntegerField() province = models.CharField(max_length=100) company_name = models.CharField(max_length=30) phone_number = PhoneNumberField(null=False, blank=False, unique=True) products = models.CharField(max_length=200) def __str__(self): return self.name.username How can I achieve something like this? I thought that I need to write a function inside my views.py but I'm stuck and don't know how to go further. def profile(request): # something here.. return render(request, 'home_page/profile.html') -
Automate Elasticsearch index creation on django app startup
I want to automatically check and create (if not existing) the elasticsearch index of my app on startup, this is my current situation which is not working: echo "Checking if Elasticsearch index is setup" { cat <<EOF | python /manage.py shell from elasticsearch import Elasticsearch HOST_URLS = ["elasticsearch:9200"] es_conn = Elasticsearch(HOST_URLS) INDEX_NAME = "posts" res = es_conn.indices.exists(index=INDEX_NAME) if res == True: print("Elasicsearch index seems already setup, skipping") else: print("Elasicsearch index not setup yet, creating ...") import subprocess subprocess.Popen("y | python manage.py search_index --rebuild", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() EOF }>/dev/null which again results in: "the '{}' indexes? [n/Y]: ".format(", ".join(index_names))) | EOFError: EOF when reading a line python manage.py search_index --rebuild comes from: https://github.com/sabricot/django-elasticsearch-dsl/ -
Django migrate value invalid literal
I have problem with Django migrate function. I was trying to add new field to my user model and it looks like this. class UserProfile(models.Model): """ Model to represent additional information about user """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) bio = models.TextField( max_length=2000, blank=True, default='' ) # we use URL instead of imagefield because we'll use 3rd party img hosting later on avatar = models.URLField(default='', blank=True) status = models.CharField(max_length=16, default='', blank=True) name = models.CharField(max_length=32, default='') balance = models.BigIntegerField(default='0') def __str__(self): return self.user.username balance is new what I added, and after that I'm receving messages like Operations to perform: Apply all migrations: accounts, admin, auth, authtoken, contenttypes, forums, posts, sessions, threads Running migrations: Applying accounts.0005_userprofile_balance...Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) … -
problem writing/understanding Django Custom managers
I have problems with Django's custom managers. It may be simple but I did not understand the managers very well. here is my code : class Season(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() # Default Manager custom_obj = SeasonManager() # Custom Manager in (managers.py) def __str__(self): return self.title class Lesson(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() season = models.ForeignKey(Season, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Video(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() view = models.PositiveIntegerField(default=0) lesson = models.ForeignKey(Lesson, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) video_file = models.FileField(upload_to='tutorialApp/videos') video_length = models.CharField(max_length=32) def __str__(self): return self.title The structure is like this: every season has some lessons, each lesson has some videos and each video has a length. I want to write a manager that shows the sum of video lengths in a season. ( a manager that shows how many minutes of videos there are in a season … -
Is there documentation for class option for Django fieldset?
In the Django admin docs, it mentions fieldsets. The example they specify a class collapse. This class will make the fieldset collapsible in the admin page. I found 2 other examples of a classes one could use. I found looking for a list of other classes I can use is wide or extrapretty. Other than these examples I have not been able to find anything else about the class option in the fieldset.