Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form missing fields
I'm trying to get a simple form working. Oddly, other forms I wrote in this app are working fine, but this one wont show the fields. Can anyone tell me what I'm missing? Here are the files views.py: def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/tracker/all/') else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) models.py class Note(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) note_text = models.CharField('Notes', max_length=2000) note_date = models.DateField('Date Entered') forms.py class NoteForm(forms.Form): class Meta: model = Note fields = ['note_text', 'note_date' ] template (noteform.html) <form action="/tracker/newnote/" method="post"> <div id="fields"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </div> </form> One other note, I have commented out the div id called "fields", to rule out CSS as the issue. -
Reverse Language Translation in Django
I'm building an API using Django Rest Framework that needs to support multiple languages, we're trying to use the Django translation framework, and using the answer from here I've decided how to implement translatable choicefields. However my issue is for the reverse case. Say I have a model like this: from django.utils.translation import ugettext_lazy as _ class Payment(models.Model): OPEN = 0 CLOSED = 1 BALANCE = 2 STATUS_CHOICES = ( (OPEN, _('open')), (CLOSED, _('closed')), (BALANCE, _('balance')), ) status = models.IntegerField(choices=STATUS_CHOICES, default=OPEN, verbose_name=_("Status")) This works fine for returning the information to the user, we use the stored status value and translate it before returning. However, I also want the user to be able to POST a new payment object using any language. So if the user wants to create an open transaction, they can send {'status':'open'} but they can also send it in Spanish as {'status':'abierto'}. Is there a way to handle this automatically? Basically I want to get the reverse of the ugettext_lazy function. -
styling django-userena templates
I have installed django-userena to manage profiles and accounts on my django app. It seems it is not fully configured and I am still working on. One of the problems that I am trying to solve is to figure out how to style the templates. For instance, this is the address for login on a development server: http://127.0.0.1:8000/accounts/signin/ and here is the sign in page, so my question is: How can I style the templates? It seems the templates should be styled by twitter bootstrap or maybe there are some css files that I can place them in my css folder? -
Django, upload image error
In my aplication, the users can change their profile data, like full name, gender, profile image and other stuff. The problem is when the user want to keep the same profile picture and the file input is empty. How do I support that in my view. Here is my html updateProfile.html <form action="{% url 'updateprofile' %}" enctype="multipart/form-data" method="POST">{% csrf_token %} <input type="file" id="logofile" name="avatar" accept="image/gif, image/jpeg, image/png" value=""> <input type="text"name="full_name"> <input type="date"name="birthdate"> </form> Here is my views.py updateprofile def updateprofile(request): #HERE IS WHERE I CHECK IF I CHANGE THE IMAGE OR NOT BUT THIS NOT WORKS IF THE FILE INPUT IS EMPTY if request.FILES['avatar']: avatar = request.FILES['avatar'] full_name=request.POST['full_name'] birth_date= request.POST['birthdate'] c = user.objects.get(id=request.session['account_id']) c.full_name = full_name c.avatar = avatar c.save() return redirect('userprofile') If I change the file in the file input everything works well. But If I don't upload a new Image and leave the file input in blank I have an error. How do I check if there is file or not in the POST request? please help -
how to filter search on contenttype in django
I have a listapiview, and I want to search in a model object. Say the model is ContentTypeObj and there are 3 models limit to it. The 3 other models have a GenericRelation to it. I am trying to perform a search on the ContentTypeObj. So far it is returning me everything. the search api class ContentTypeObjAPIView(ListCacheResponseMixin, generics.ListAPIView): serializer_class = ContentTypeObjSerializer permission_classes = (AllowAny,) pagination_class = SmallResultsSetPagination list_cache_key_func = ListKeyConstructor() filter_backends = ( DjangoFilterBackend) filter_fields = ('object_ct__genrelation') search_fields = ("object_ct__genrelation__location__city_city") def get_queryset(self): queryset = ContentTypeObj.objects.all().order_by('-time_stamp') return queryset ContentTypeObj model class ContentTypeObj (models.Model): object_ct = models.ForeignKey(ContentType, related_name='explore_objects', verbose_name='Object type',limit_choices_to={'model__in': ('model1', 'model2', 'model3')}) object_id = models.PositiveIntegerField(db_index=True, verbose_name='Object ID') obj = GenericForeignKey('object_ct', 'object_id') owner = models.ForeignKey(User, related_name='explore_objects') time_stamp = models.DateTimeField(verbose_name='Timestamp') and the models would have an extra field for the GenericRelation. class Model1(models.Model): ... genrelation = GenericRelation(ContentTypeObj) class Model2(models.Model): ... genrelation = GenericRelation(ContentTypeObj) -
Django admin linking me to a template
When programming locally on my development server, the site is functioning as expected. But when I go to my production site, a handful of the links in mysite.com/admin link me to a random template that's extending my base.html, rather than the typical database/form UI. For example, I expect this: But instead, I am getting: Any help would be great. -
Set a time for when object to be posted in Django admin?
I want to implement a feature where you can select a date for when a post can go public in the Django admin. Is there a way we can set this in Django? What's the best practice to do this? -
Error on inspectdb model creation django
I am using django with mssql. I already have a existing database and want to create django model for the tables in that database. I followed this django book instruction for inspectdb. http://django-book.readthedocs.io/en/latest/chapter18.html When i enter the command python manage.py inspectdb > interface/models.py I get following error Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 547, i n _execute_command recordset = self.cmd.Execute() File "<COMObject ADODB.Command>", line 3, in Execute File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 28 7, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Server Native C lient 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 6 2, in execute return self.cursor.execute(sql) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 647, i n execute self._execute_command() File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 558, i n _execute_command self._raiseCursorError(klass, _message) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 488, i n _raiseCursorError eh(self.connection, self, errorclass, errorvalue) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 103, i n standardErrorHandler raise errorclass(errorvalue) sqlserver_ado.dbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Se rver Native Client 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) Command: SELECT * FROM [Attribute] where 1=0 Parameters: … -
'Welcome' message from Nginx shown when I run my wsgi Django project + Nginx + Gunicorn
I'm beginner in Django and I've finished my first project. I have an Ubuntu server in Digital Ocean and this is what I've done: My project nginx configuration file: server { server_name domain.com; access_log off; location /static/ { alias /opt/myenv/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } My project is located in /opt/myenv/myenv/ When I execute gunicorn myproject.wsgi it looks like it's running Listening at: http://127.0.0.1:8000 (1481) But when I access into my IP, I just see an Welcome message from Nginx. What is happening? (Sorry my bad english) -
How to filter a QuerySet to max members of each group in django?
The model is something like this: class Application(models.Model): application_id = models.IntegerField() version_id = models.IntegerField() # some other attributes where application_id and version_id together determine an Application entry, in that one application may have several versions, and an entry with the largest version_id is the application's current version. And the goal is to find the current versions of all applications. The SQL (in MySQL) is something like: SELECT * FROM application AS app WHERE version_id = (SELECT max(version_id) FROM application WHERE application_id = app.application_id); How to achieve this? Please note that the object here is to filter the QuerySet, rather than only fetching the largest version_id, which would be as simple as using a GROUP BY, or in django a values() followed by an annotate(). I'm interested in the other attributes of the current version as well. -
Is it possible to do arithmetic operation on OuterRef expression?
I'm building an Experience booking system in django and I've the following models. class Experience(models.Model): name = models.CharField(max_length=20) capacity = models.IntegerField() class Booking(models.Model): experience = models.ForeignKey(Experience) occupied = models.IntegerField() Each experience has a limited number of capacity and when user perform booking, it will be added to the Booking table with occupied number. Now how will I find the experiences which are not occupied completely? available_experiences = Experience.objects.all().exclude(id__in=Subquery(Booking.objects.filter(occupied__gt=OuterRef('capacity') - request_persons).values_list('experience', flat=True))) Here, request_persons is the number of required vacancy in an experience. This is not working and showing an error like 'ResolvedOuterRef' object has no attribute 'relabeled_clone'. Is it possible to do arithmetic operation on OutRef() expression like F()? Without adding request_persons, the above code works. Why it is not possible to add a value to the OutRef() expression? NOTE: My actual code is much complex one and it will be really great to get an answer without modifying the entire structure of the above code. -
Django 1.11: Issues with utf8 writing to file on windows
I am trying to write some text into a file with data from django objects (CharField) and some formatting. The problem is with accentuated characters (é in the example below). On Linux I have no problems. However, on windows 7, I am getting extremely confusing behaviours. This (open call without encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() produces: SxE9l,Séoul while this (open call with encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w', encoding='utf8') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() which produces: Séoul,Séoul Of course, the expected result is: Séoul,Séoul and this is what I get on Linux with the same database. So the weird thing is that each of those options gets different parts right and wrong. In one case the ORM retrieved value is wrong. In the other it is the string object created in the source code that is wrong. I can't find a way to get both right. All the files are encoded in UTF8 (as reported by notepad++). The python version is 3.5.4 The MySql database has all encodings in UTF8 and an SQL query on the user table shows the … -
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
Had a problem running locally project! Maybe problem with virtual environment? settings.py: import os import dj_database_url INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap_pagination', 'main', ] if os.environ.get('DEBUG', False): INSTALLED_APPS += ['django_extensions'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'main.middleware.DeviceAuthMiddleware', ] WSGI_APPLICATION = 'cl.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases if os.environ.get('DEBUG', False): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASES = { 'default': dj_database_url.config(), } PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DATAMUSE_URL = 'https://api.datamuse.com/words?sp=' I got the error message when trying to python manage.py runserver or python manage.py migrate. Here is the screen for the error: -
Django page for selecting model instances and adding them to a list
I am a beginner with Django, and my JS/HTML/CSS knowledge is intermediate. I have two models defined in models.py: One model Product that has some basic descriptive Fields (name, description, ...), and another model Category, that has a ManyToManyField products. I want to build a page where a user can select Products with checkboxes, and then add them to a category by pressing an "Add" button. Upon pressing, what should basically happen is: category.products.extend( selected_products ) # This only so that I know to which category a product has been assigned, not too urgent for product in selected_products: product.categories.append(category) Here is an image of what sort of page I am aiming for: https://i.imgur.com/BWs0eV0.png I am not asking for a full working example (unless there already happens to be one available of course). All I am looking for is some pointers on how to proceed creating this. I know how to create the list and the sidebar, but combining this with buttons per list element is new to me. Should the proposed page be essentially 1 giant form, and should I define it in forms.py? Should I be using the Django CheckboxInput widget? Is there a recommended structure for this type … -
Django Tutorial Help - "Not Found: /polls/index.html"
Working through the Django tutorial and have run into a problem I cannot figure out. Help would be appreciated. What am I missing here? Run this the tutorial a couple times now double checking all work, and code seems to match. Error: "Not Found: /polls/index.html" mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] polls/views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're … -
ProgrammingError at / relation does not exist
I can not find answer in other places. (Sorry for asking again but) what is wrong? Did anyone have such an error? ProgrammingError at /register/ relation "user_user" does not exist LINE 1: SELECT (1) AS "a" FROM "user_user" WHERE "user_user"."userna... I extended user abstract model and error saying no relation When i extend user in sqlite3 no errors such this but postgre is full databse error class User(AbstractUser): social_username = models.CharField(max_length=100, null=True, blank=True) views.py def registration(request): if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) messages.success(request,'You were successfully registered %s' % user.first_name) return HttpResponseRedirect('/') messages.error(request, 'Something went wrong while authenticating') return render(request, 'project/register.html', {'form': form}) else: form = RegisterUserForm() return render(request, 'project/register.html', {'form': form}) settings.py AUTH_USER_MODEL = 'user.User' -
Django Change Profile Picture with a button
I'm currently trying to change the user profile picture using a simple button! Here is my work so far: views.py class UserProfileView(View): form_class = UpdateCustomUserPictureForm template_name = "accounts/user_profile.html" def get(self, request, *args, **kwargs): form = self.form_class(instance=request.user) context = { 'form': form, 'user_reviews': request.user.reviewed.all() } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): pass template <div class="image-container employee-image circle" style="max-width:150px; max-height:150px; margin:0 auto"> <img class="image" style="height:100%; width:100%; object-fit:contain" src="{{ user.profile_picture.url }}" alt=""> <div class="overlay"> <a class="text" style="text-decoration:none" href=""><font size="2rem">Modifica</font></a> </div> </div> forms.py class UpdateCustomUserPictureForm(forms.ModelForm): profile_picture = forms.ImageField( widget=forms.FileInput(attrs={'class': 'form-control'}), required=False ) class Meta: model = User fields = ('profile_picture',) def __init__(self, *args, **kwargs): super(UpdateCustomUserPictureForm, self).__init__(*args, **kwargs) self.fields['profile_picture'].label = "Immagine del profilo" How can I upload and change the picture by clicking on "Modifica"? This is the result i want to obtain: -
Web Frameworks: Frontend vs Backend
I'd like to know what characterizes/differentiates a frontend web framework from a backend web framework. For instance, Django is a backend framework while Angular is a frontend framework, but why? I can make an entire application using Django, so why is it not considered a frontend framework too? -
Template form does not render in Django
I have a form that I want to display. It looks like this: #the template to be filled with the form: #base.html {% load staticfiles %} <html> <head><title>{% block title %}{% endblock %}</title></head> <body>{% block content %}{% endblock %}</body> </html> The concrete page: #home.html {% extends 'base.html' %} {% block title %}Main{% endblock %} {% block content %} <h2>Home page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} The VIEW #views.py def home(request): context = locals() template = 'home.html' return render(request, template, context) The URLs: from django.conf.urls import url from .views import home as home_view urlpatterns = [ url(r'^home/$', home_view, name='home'),] This does not draw the {{ form.as_p }} it only draws the submit buttonAny ideas why? -
Filter on variable of ManyToMany-field inside Django Template
I have a job-object and a content-object. A job object gets created when a user wants to retrieve a set of content-objects in exchange for credits. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) class content(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) job_id_list_not_provided = models.ManyToManyField(JobId , related_name='JobIdFailed', blank=True) free_content = models.CharField(max_length=500, null=True, blank=True) paying_content = models.CharField(max_length=500, null=True, blank=True) For all content-objects part of the job, the JobId-object is added to the job_id_list - not keeping credit levels in mind. Different user can all run multiple jobs on the content objects. For too-big jobs exceeding the credit amount of the user, the content-objects that would push the credit level below zero, get also the JobID-object added to the job_id_list_not_provided field of the content-object. For a a specific user, we can retrieve the two sub-sets of found and not-found content-objects with following queries: views.py: found_results_list = results_list.filter(job_id_list_not_provided__user= None).distinct() not_found_results_list = results_list.filter(job_id_list_not_provided__user=request.user).distinct() My challenge: Result lists are over 100-objects in size, so I would like to use pagination to get a nice view on my page When not considering pagination, I could simply pass the 2 lists (found and not found) and loop over each list with a template … -
Django 2.0 - DateArchiveView date object for template
My app has ArchiveIndexView, YearArchiveView, MonthArchiveView and DayArchiveView. Except in ArchiveIndexView, I wanna add a Back link which will point back to its successor in all the views. So in the template of MonthArchiveView, I did it like this: <a href="{% url 'year_archive' date_list.0.date.year %}">Back</a> which would point back to YearArchiveView. But in DayArchiveView, there is no date_list attribute as of Django 2.0 documentation so how can I implement date object to be used in the template? -
django like button counting irregularly
I have a django application where I implemented a like button for posts posted on the blog. I recently discovered that when ever a like button is clicked by a registered user, the like increases exceedingly. Instead of the number of likes to get increased by 1 it increases by maybe 90+ and when the button is clicked agin for it to change to unlike it still increases so the like function becomes uneven. Below is my code for the like function Html {% with total_likes=obj.likes.count likes=obj.likes.all %} <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ obj.id }}" data-action="{% if request.user in likes %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} like {% else %} unlike {% endif %} </a> JQuery <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "posts:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // … -
DRF annotate Count on many-to-many through table gives more occurrences than when you use _set.all().count()
I have these models: class Topic(BaseModel): name = models.CharField(max_length=60) public_name = models.CharField(max_length=60, blank=True, null=True) class Content(BaseModel): title = models.CharField(max_length=120) series = models.CharField(max_length=120, blank=True, null=True) season = models.CharField(max_length=45, blank=True, null=True) episode = models.CharField(max_length=45, blank=True, null=True) tags = models.ManyToManyField(tags_models.Tag, through='ContentHasTags') topics = models.ManyToManyField(topics_models.Topic, through='ContentHasTopics') class ContentHasTopics(BaseModel): content = models.ForeignKey(Content) topic = models.ForeignKey(topics_models.Topic) order = models.IntegerField(default=99) class Meta: unique_together = ('content', 'topic',) ordering = ('order',) The problem I have is that if I use the next function: @property def get_contents_count(self): return self.contenthastopics_set.all().count() In many cases I have 7 as a result (and is true), but when I use the annotate query like this for Django Rest Framework (in the viewset), it gives me like 28 results, some other topics have 5 contents using the _set.all().count(), but annotate gives me 10 as a result, and so on. queryset = models.Topic.objects.all().annotate( themes_count=Count('themehastopics') ).annotate( contents_count=Count('contenthastopics') ).annotate( tags_count=Count('topichastags') ) How is the right way to annotate the query with the Count correctly added? -
Django save multiple view variables
I'm trying to save URL parameters to my model. Already tried many things and currently getting argument error. Can't find proper documentation on this most likely because I am not sure what the proper search term is. All I need to do is save webhook POST to my URL. I will use @require_POST decorator to require POST only. Atm this is not the issue. The issue is simply saving the webhook. models.py from django.db import models from django.contrib.auth.models import User class Webhook(models.Model): clientAccnum = models.CharField(max_length=120, blank=True) clientSubacc = models.CharField(max_length=120, blank=True) eventType = models.CharField(max_length=120, blank=True) eventGroupType = models.CharField(max_length=120, blank=True) subscriptionId = models.CharField(max_length=120, blank=True) time_stamp = models.DateTimeField(blank=True) time_stamp_local = models.DateTimeField(blank=True) views.py def webhook(request): template_name = 'payment/index.html' hook = Webhook.save() hook.client_acc_num = request.GET.get('clientAccnum') hook.client_sub_acc = request.GET.get('clientSubacc') hook.event_type = request.GET.get('eventType') hook.event_group_type = request.GET.get('eventGroupType') hook.sub_id = request.GET.get('subscriptionId') hook.time_stamp = request.GET.get('timestamp') hook.time_stamp_local = timezone.now() hook.save() return render(request, template_name) -
Django admin TabularInline disable fields based on values
I am looking to disable fields in Django Admin TabularInline forms. My model has an optional end_date field which should, if set disable the input fields to avoid further modifications of values. Currently I tried modifying get_formset, but I am unable to get the values to finally disable fields using e.g.: formset.form.base_fields['contract_number'].disabled = True I am using the following code: class ServerLicenseInline(admin.TabularInline): model = ServerLicense autocomplete_fields = ('contract_number',) ordering = ('start_date', 'end_date') extra = 0 can_delete = False def get_formset(self, request, obj=None, **kwargs): formset = super(ServerLicenseInline, self).get_formset(request, obj, **kwargs) ... I was looking in obj and formset to find the values but without chance right now. Does someone have an idea how to achieve this? Thanks!