Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to set datetime in navbar for all my template in django?
I have 3 htmls in my django project. - base.html - navbar.html - home.html I want set Datetime field in Navbar cause when i'm in home. i can see time there.i look for something like {{ request.user }} so i use that in Navbar. I know i can define : time = datetime.datetime.now() for define Datetime. but i cant define any context for Navbar cause that don't have def in Views.py what can i do ? tnx for response. -
How do I reload a page and maintain the scroll position using a GET request?
I'm using Django and have the following view: def index(request): if request.method = 'POST': form = TestForm(request.POST) if form.is_valid(): # Process form return HttpResponse('''see below''') # The rest of the view... Problem: What I'm trying to do is to reload the page while staying in the same scroll position. I've tried to put a couple things in the '''see below''' area of the HttpResponse: Attempt 1: return HttpResponse('<script>window.location.href = window.location.href</script>') This refreshes the whole page, and the scroll position is lost. Attempt 2: return HttpResponse('<script>document.location.reload(true)</script>') This theoretically should work (and works if I just type it into the browser console), but since it's within a Django form with a POST request, the POST request is resubmitted, resulting in an infinite loop of POST requests. Note: At least that is what I think is happening. Here is the command prompt output (only shows the first few lines): [12/Sep/2018 20:05:53] "GET /tasks/ HTTP/1.1" 200 10654 [12/Sep/2018 20:05:54] "POST /tasks/ HTTP/1.1" 200 47 [12/Sep/2018 20:05:54] "POST /tasks/ HTTP/1.1" 200 47 [12/Sep/2018 20:05:54] "POST /tasks/ HTTP/1.1" 200 47 Question Is there a way to BOTH reload the page at the correct scroll position AND use a GET request rather than a POST request? -
Nested polymorphic_inline_formsets gives AttributeError: 'NoneType' object has no attribute 'get_real_instance_class'
Thank you creating this django package. I am trying to create a nested inline formset with the innermost being the polymorphic inline formset https://django-polymorphic.readthedocs.io/en/stable/formsets.html this my polymorphic inline formset Oformset=polymorphic_inlineformset_factory(MBF, MO, formset_children=(PolymorphicFormSetChild(LO), PolymorphicFormSetChild(DO), PolymorphicFormSetChild(BO), PolymorphicFormSetChild(AO), ),fields='__all__', can_delete=False, extra=0) I created a regular baseinlineformset and added the Oformse, polymorphic_inlineformset, to it. I get "model = defaults['instance'].get_real_instance_class() # allow proxy models AttributeError: 'NoneType' object has no attribute 'get_real_instance_class' " for the form.nested in the is_valid() The form.nested is None in this context, when it should have given a PolymorphicFormSetChild from Oformset that was create. class MyBaseFormset(BaseInlineFormSet): def add_fields(self, form, index): super(BaseScenarioFormset, self).add_fields(form, index) form.nested=Oformset(instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, prefix='modelobject-%s-%s' % (form.prefix, Oformset.get_default_prefix()) ) def is_valid(self): result =super(BaseScenarioFormset, self).is_valid() if self.is_bound: for form in self.forms: result=result and form.nested.is_valid() return result def save(self, commit=True): result=super(BaseScenarioFormset, self).save(commit=commit) for form in self: form.nested.save(commit=commit) return result formset that will hold the polyinlineformset ModelBasicFormSet=inlineformset_factory(UCP, MBF, fields=['modelNum','interactor', 'action', 'validationStep'], formset=MyBaseFormset, can_delete=False,extra=0) update view to display the nested inline polymorphic formset class ModelUCUpdateView(UpdateView): def get_context_data(self, **kwargs): context = super(ModelUCUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['modelbasicflow_form']=ModelBasicFlowFormSet(self.request.POST, self.request.FILES, instance=self.object, queryset=ModelBasicFlow.objects.all(), prefix='modelbasicflow') else: context['modelbasicflow_form']=ModelBasicFlowFormSet( instance=self.object, queryset=ModelBasicFlow.objects.filter(useCase=self.object), prefix='modelbasicflow') return context -
how to troubleshoot queryset requirement in django form
I'm working a Django 2.0 website, and trying to build out a django form: forms.py: class NewMemberstatusform(forms.Form): rank = forms.ModelChoiceField(queryset=models.Rank.objects.all(), widget=forms.ModelChoiceField( attrs={ 'class':'form-control' } )) unit = forms.ModelChoiceField(queryset=models.Unit.objects.all(), widget=forms.ModelChoiceField( attrs={ 'class':'form-control' } )) activate = forms.ChoiceField(choices=YesNo.YESNO_CHOICES, label="Enable Member to see their information", widget=forms.ChoiceField( attrs={ 'class':'form-control' } )) My problem is that it does not compile correctly. I receive this error saying I'm missing the queryset in the rank field, but as you can see, it's clearly in the class. What am I missing? Thanks class NewMemberstatusform(forms.Form): File "/Users/sinistersparrow/PycharmProjects/ifthqcom/app_svcrecord/forms.py", line 126, in NewMemberstatusform 'class':'form-control' TypeError: __init__() missing 1 required positional argument: 'queryset' -
Web Application Brain Storming
I am developing my first full website with web app. I will be hosting the app on my home server and I am starting to brainstorm what I will use to develop it. Initially I was thinking Django because I could get it up and running quickly, based on what I’ve read. Essentially what I will be using the app for is to calculate pricing for a combination of different services that I offer (or will offer in my construction business). I know a lot of languages on their own, specifically python and that is why I chose Django but I am all about learning new stuff. So I wanted to see if I could get some input on how others might tackle this problem. I will need 4 things: Admin input to define the scope of work. These are integer variables such as square footage of home, square footage of countertop space, number of can lights, number of bathrooms, etc this can be done on backend, on an admin page that I build, or one that’s already built with Django User to fill out a questionnaire where they answer what quality or type of work wanted. I.e. 3-4 tiers … -
Django Reverse Foreign Key filter
I have what I think is a not-normal case, but as I'm new to this Django filled world I could be wrong. # Create your models here. class Country(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=2, default="US") def __str__(self): return self.name class State(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=2, default="ME") country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self): return self.name class ProjectSite(models.Model): name = models.CharField(max_length=100) city = models.ForeignKey(City, on_delete=models.PROTECT) def __str__(self): return self.name The above is a subset of the app models. When I create a list of all of the "ProjectSites", I want to sort them by Country-State-City, preferably in a way ahead of time so I can create dynamic tabs for the above but I'll start small. If I try: queryset = ProjectSite.objects.all() I end up with the ProjectSites, but I can't come up with an elegant way to pass that information to the template, just subsets of each project in each city. I'd like to end up with at least a list like: Country 1 State City 1 Project A Project B City 2 Project C Country 2 Is there a proper way to filter into an … -
How to fix massive lag on django development server?
OVERVIEW: Hi, I have massive lag on my development server as long as I am offline. I'm using windows 10 pro. I have a website on my local environment at 127.0.0.1:8000/. I have a fairly high end laptop that can play high graphics games on it with no problems, and no lag, such as fortnite. But my local development server is super slow, and does not stop being slow unless I get online (even though I'm using the development server). This problem started back in may of this year, and back then I asked some other programmers who had no clue how to fix it. It had never been that way before, and I don't want to be online all the time... EXAMPLE OF PROBLEM: For a developed project while I'm offline: python manage.py runserver, paste 127.0.0.1:8000/ into the browser, wait ~10 seconds, then the background color shows up (no text yet), ~10 secs later some pics show up with some textless elements that have background colors, ~8 seconds after that the text shows up in portions of those elements, and ~10 secs after that the webfont and the rest of the page finally shows up. For a fresh, brand … -
Django - check if user is authenticated for every url
On my html, I can check if the user is logged in by using the following syntax: {% if user.is_authenticated %} <div id="display_something">...</div> {% else %} <p>Please Log in</p> {% endif %} But what should I do if I want to check if the user is authenticated for every html file I am rendering? Do I have to copy and paste that {% if ... %} block for every single html file? What is the Django's way of handling this issue? What's the good practice? -
How to convert a query to django ORM Query
I am trying to figure out how I can convert the following query into a Djangon ORM query. I am using Django 2.1 Python 3.5 on windows, I am trying to run the query against a Oracle database SELECT m.msg_no, q.seq, To_Char(m.date_created,'yyyy/mm/dd hh24:mi:ss'), To_Char(SYSDATE,'yyyy/mm/dd hh24:mi:ss'), q.name, Round((round(SYSDATE - m.date_created,6)*1440),1) AS msg_age FROM message m INNER JOIN queue q ON m.queue = q.seq WHERE m.date_created >= (SYSDATE - 13/24) AND m.status1 = 0 AND m.direction = 0; I have two models, would like to know how to best, the tables Message and Queue are relate by Queue primary key SEQ and Message foreign key QUEUE, so SEQ == QUEUE in Message table: from django.db import models # Create your models here. class Queue(models.Model): SEQ = models.IntegerField(primary_key=True,) NAME = models.CharField(max_length = 50) INPUT_DRIVER = models.IntegerField() OUTPUT_DRIVER = models.IntegerField() DIRECTION = models.IntegerField() ORIGINATOR = models.IntegerField() DESTINATOR = models.IntegerField() PRIORITY = models.IntegerField() INPUTEXEC = models.CharField(max_length = 100) OUTPUTEXEC = models.CharField(max_length = 100) USERID = models.CharField(max_length = 8) TMSTAMP = models.DateTimeField(max_length = 7) QUEUE_TYPE = models.CharField(max_length = 16) class Meta: db_table = "QUEUE" # class Message(models.Model): MSG_NO = models.IntegerField(primary_key=True,) MSG_TYPE = models.IntegerField() DIRECTION = models.IntegerField() SESSION_NO = models.IntegerField() SEQUENCE_NO = models.IntegerField() REF_SESSION = models.IntegerField() REF_SEQUENCE … -
Running a Scrapy Spider simultaneously with Django Website
my goal is to run a scrapy spider and collect information for my Django website. Whenever I try, it does not work as they both use twisted and the scrapy spider needs to run on the "main stream". How can I run them seperately but relay information from my spider to my website? Thanks in advance. -
How can I display an AutoField in a ModelForm?
Question: How can I display an AutoField in a ModelForm. I have a need where a Form is generated and displayed. Based on the input, I need to read the AutoField's value and search for it in my database. My form: class CheckinPatientMetaForm(ModelForm): class Meta: model = customer exclude = [ 'gender', 'maritalstatus', 'occupation', 'bloodgroup' ] My model: class customer(models.Model): # Need autoincrement, unique and primary cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35) age=models.IntegerField() gender_choices = (('male', 'Male'), ('female', 'Female')) gender = models.CharField( choices=gender_choices, max_length=10, default='male') maritalstatus_choices = ( ('married', 'Married'), ('unmarried', 'Unmarried')) maritalstatus = models.CharField( choices=maritalstatus_choices, max_length=10, default='Unmarried') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='') email = models.CharField(max_length=50, default='', blank=True) address = models.CharField(max_length=80, default='', blank=True) city = models.CharField(max_length=25, default='', blank=True) occupation = models.CharField(max_length=25, default='', blank=True) bloodgroup_choices = (('apos', 'A+'), ('aneg', 'A-'), ('bpos', 'B+'), ('bneg', 'B-'), ('opos', 'O+'), ('oneg', 'O-'), ('abpos', 'AB+'), ('abneg', 'AB-'), ('unspecified', '-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=3, default='-', blank=True) class Meta: unique_together = ["name", "mobile", "age"] def __str__(self): return self.name views.py: def checkin_patient(request): results = '' if request.method == 'POST': form = CheckinPatientMetaForm(request.POST) print("POST data",request.POST) else: form = CheckinPatientMetaForm() return render(request, 'clinic/checkin.html', {'rnd_num': randomnumber(), 'form': form, 'SearchResults': results}) Relevant part of my template: <form class="" … -
Django Query : Compiling data with `seconds` difference in TimeField
I have the following model in my Django application : class PeopleCount(models.Model): """ A webapp model classs to store People Count Details. """ timestamp = models.DateTimeField(auto_now=True) people_count_entry = models.IntegerField(blank=True, null=True) people_count_exit = models.IntegerField(blank=True, null=True) store = models.ForeignKey(Store, blank=True, null=True) profile = models.ForeignKey(Profile) camera = models.ForeignKey(Camera) recorded_time = models.DateTimeField(null=True, blank=True) def __str__(self): return "People Count {}".format(self.timestamp) class Meta: verbose_name = "People Count" verbose_name_plural = "People Count" ordering = ['-recorded_time'] I want to print out the values of PeopleCount where if the difference between the time of enlisting of two objects is less than 1 seconds I can aggregate their values. For example: Let's say I get PeopleCountObjA -> at 11:30:21 (where people_count_entry was 4) And then I get another value PeopleCountObjB -> at 11:30:22(where people_Count_entry was 2) I should get answer as Group Count should be 6 The time 11:30:21 and 11:30:22 refers to recorded_time field from the model. I tried using the aggregate query but unable to put in filter for delta difference of one second. Hope I am clear with the question. TIA -
i can't create a post_detail and post_list
i am a error to create my list_posts and detail_post ! my code at list_posts : def blog(request): list_posts = Post.objects.filter(status = 'published').order_by('-published_at')[:] context = { 'list_posts':list_posts } return render(request, 'mysite/doc_2.html', context) and my code at detail_post: edef detail(request, year, month, day,slug): post = get_object_or_404(Post, status='published', published_at__year=year, published_at__month=month, published_at__day=day, slug=slug) context = { 'post':post } return render(request, 'mysite/ws-post.html', context) and my code in my app_name.urls: re_path(r'^(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/(?P<slug>[-\w]+)$/',views.detail,name='detail'), and my code in url's my html list_posts is : <a class="l-ws-more" href="{% url 'blog:detail' year=post.published_at.year month=post.published_at.month day=post.published_at.day %}"> and my error is : NoReverseMatch at /blog/ Reverse for 'detail' with keyword arguments '{'year': '', 'month': '', 'day': ''}' not found. 1 pattern(s) tried: ['blog/(?P<year>\\d{4})-(? P<month>\\d{1,2})-(?P<day>\\d{1,2})/(?P<slug>[-\\w]+)$/'] please answer my question and error's pictures ==> enter image description here -
How do I make a field optional to enter, in a django ModelForm?
Scenario: I instantiate a ModelForm and pass it to a template which displays the form. When POST is submitted, code tries to search the database by any of the given inputs. I dont require all inputs to be entered as in the Model. I just need one (or more, if user desires to do an AND search) to be entered. Question: How can I make any of the ModelForm fields optional, where in the Model, the field isnt optional. The field isnt optional in the Model because I have another ModelForm based on the same Model, where user is required to enter all his details. My model: class customer(models.Model): # Need autoincrement, unique and primary cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35) age=models.IntegerField() gender_choices = (('male', 'Male'), ('female', 'Female')) gender = models.CharField( choices=gender_choices, max_length=10, default='male') maritalstatus_choices = ( ('married', 'Married'), ('unmarried', 'Unmarried')) maritalstatus = models.CharField( choices=maritalstatus_choices, max_length=10, default='Unmarried') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='') email = models.CharField(max_length=50, default='', blank=True) address = models.CharField(max_length=80, default='', blank=True) city = models.CharField(max_length=25, default='', blank=True) occupation = models.CharField(max_length=25, default='', blank=True) bloodgroup_choices = (('apos', 'A+'), ('aneg', 'A-'), ('bpos', 'B+'), ('bneg', 'B-'), ('opos', 'O+'), ('oneg', 'O-'), ('abpos', 'AB+'), ('abneg', 'AB-'), ('unspecified', '-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, … -
(Django) File not updating after it is closed
I have asked a few questions here (and I'm sorry for asking so many, promise this should be the last one!) related to a Django project I am working on which displays the contents of a file in a form, and you can edit the file with the form, when you submit it the project writes to the file and the changes are automatically reflected. So I have gotten the project to display the contents of a calendar text file in the form, and I have been able to get the form content into my Python script for manipulation. The issue I am having is writing that content to a file, because for some reason, the changes never commit themselves until after I restart the server (this is not ideal, as this should be able to run continuously). I suspect this has something to do with the file still remaining open for some reason after it is "closed". I attempted to fix that by creating functions for all read and write actions (that close the file as well) so I can call them every time I need to read/write. The issue still persists. I really am stuck here (hours of … -
How to filter queryset of a foreignkey field in Django Admin
I have a scenario like this, I have 3 models. Category, Subcategory and Posts. -Category is One to Many to Subcategory and Subcategory is One to Many to Posts. My models.py looks quite like this(minified version). class Category(models.Model): cat=models.CharField(max_length=10) class SubCategory(models.Model): subcat=models.CharField(max_length=10) class Posts(models.Model): cat=models.ForeignKey(Category) subcat=models.ForeignKey(SubCategory) title=models.CharField(max_length=10) Now, I want to publish a post from admin in which I only want the queryset of subcategories based on selected dropdown from category. Like, if I select Django from dropdown in "Add Posts" section in admin, it should only give me subcategories which were linked to Django(or whatever I choose from dropdown). I have tried searching a lot and the best I could find is render_change_form. But the problem with render_change_form is, it requires condition for filtration which I don't have as I want the Category from the form itself(based on dropdown selection). I am not really sure if it's even possible in django, let me know if I failed to explain any part, I will do the needful edits. -
How to decrease result amount in django sitemap index
According to the django site, when using django sitemap index, once results are over 50,000 entries a new sitemap is paginated and created. The problem is that 50,000 is crushing my system, even with caching. How can I decrease the sitemap entries to something more manageable like maybe a few thousand. -
materialize select with django-smart-selects
django-smart-selects is working on both backend and frontend. Calling: Jquery 3.1.1, materialize.css and materialize.js for only once. Initializing $('select').formSelect(); Checked HMTL output for many times and every item seems at right place. Materialize has class for to reset to browser-default and it is working only by this way. (city.widget.attrs['class'] = 'browser-default') <div class="input-field col s12"> <i class="material-icons prefix">location_on</i> {{form.country}} <label>Country</label> </div> <div class="input-field col s12"> <i class="material-icons prefix">location_on</i> {{form.city}} <label>City</label> </div> Asking for, how to use materialize framework with dependant select fields without using "browser-default" like above? thx in advance. -
Linking each item group of a Foreign Key reverse lookup
I am trying to set up a reverse lookup for Lesson objects off of Unit objects. Here's the Lesson object: class Lesson(CreatorModel): title = models.CharField(null=False, blank=False, max_length=128) unit = models.ForeignKey('Unit', on_delete=models.CASCADE, null=True, blank=True, related_name='lessons') So I can do a reverse lookup off a unit object with unit.lessons I am trying to get a comma separated list of Lesson objects in my Unit List table. Here's the column that I've tried, that doesn't work: lessons = tables.Column(linkify=lambda record: record.lessons.all()) It only shows me wrongly linked queryset objects: [<Lesson: Test Lesson>] -
Django Many-to-Many Relation to same model representation
I'm building a simple API with Django and DRF and I have a model that references itself in a ManyToMany field, let's call it Table. It looks something like this Table(models.Model) name = models.CharField(max_length=50) children = models.ManyToManyField('self', blank=True) I then create some tables in the database; TableA, TableB and TableC. Now, let's say that TableB and TableC are supposed to be the children of TableA. The problem I'm having is that when I do TableA.children I correctly get TableB and TableC back, but when I do TableB.children it also returns TableA which I don't want. I know that this is an expected behaviour, but how would I go about implementing this, so that I can specify the children in the way I've described? -
How to send mail with tags HTML
please I'm trying to put some styles when I send a few emails to notificate who those subscribe on my system. But, the tags HTML go to email without styles. Anyone can help me? PS: The configuration and code for email it's working. models.py: def notify_subscribers(self): subject = "New post on XYZ about: " + self.title emails = tuple( (subject, Post.create_subscriber_notification_email(subscriber), settings.DEFAULT_FROM_EMAIL, [subscriber.email_address]) for subscriber in Subscriber.objects.all()) send_mass_mail(emails) @staticmethod def create_subscriber_notification_email(subscriber): message_content = "Check out Catarse newest insights at " + settings.DOMAIN + reverse('post:homepage') + " !" footer = "If you like to unsubscribe, go to the followed link: "\ + generate_unsubscribe_link(subscriber.email_address) message = "Dear {name},\r\n{message_content}\r\n\r\n{footer}".format(name=subscriber.first_name, message_content=message_content, footer=footer) return message -
Can I access the data from SQLAlchemy database writing a separate backend on Django Rest Framework?
Consider that someone wrote a user backend. So the backend consists of users and their houses. The backend uses SQLAlchemy to store the users and their houses (so a user can have multiple houses). Both users and houses have their unique IDs. Now, I want to write a separate backend in Django Rest framework in order for the users to be able upload the house pictures for their houses. Will it be possible to do that? To be more specific, my thought is to connect to that SQLAlchemy database and whenever the user types a url (.../user34/house55/) my code triggers my model which retrieves the Token and extracts the user ID and house ID and gets ready for the POST from that specific user. So when the user uploads the image, my backend simply saves a new field in SQLAlchemy. Or would that be impossible as the user backend does not have a field for that? -
Troubles pulling up the Date from my object
I have the following model set up: class ReceiverActions(models.Model): date_paid = models.DateTimeField(default=datetime.now) and I am trying to grab just the date. When I run this in my shell: ReceiverActions.objects.get(identifier="JLWY25B4").date_paid.date I get the appropriate date : 2018-08-12 but when I try to call it in my views: ra = list(ReceiverActions.objects.filter(seller_inventory = ss).values().order_by('id')) .... rec_id = [x for x in ra if x['seller_inventory_id'] == inventory['id']][0] info['paid_date'] = str(rec_id['paid_date.date()']) I am getting undefined. I have also tried ['paid_date__date'] and ['paid_date.date'] Does anyone know why this is not working? -
Django redirect to HTTP_REFERER after changing the language using
so basically i am wondering if there's any way to make django redirect to the same page after changing the language. My urls.py : from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( # Paths, prefix_default_language=True ) i.e: When i visit /fr/login and change the language to english, it should be /en/login and not /en ( basically the homepage ) and LOL i am not asking for any give me the code please thing. -
Django URL custom parameters on Base Class View
nice to be here again :D I have writen a class based views based on generic.base.view to get information about users profiles, that are comming from different models and db tables, that will be applied both in viewing some user information on a social network and by the own user on edditing his own profile. Here is the view: class ProfileView(PageTitleMixin, generic.View): template = "common/profile.html" template_name = "Perfil" page_title = _('Profile') active_tab = 'profile' success_url = reverse_lazy('usrxtnsion:profile') def get_queryset(self): return User.objects.filter(username=self.kwargs['username']) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) account_info = Profile.objects.get(pk=self.request.user.profile.pk) user_info = User.objects.get(pk=self.request.user.pk) ctx['user_fields'] = self.get_profile_fields(self.request.user) ctx['profile_fields'] = user_info.profile_set.all() ctx['address_fields'] = user_info.useraddress_set.all() ctx['account_fields'] = account_info.account_set.all() ctx['username'] = self.request.user.username return ctx def get_profile_fields(self, user): field_data = [] # Check for custom user model for field_name in User._meta.additional_fields: field_data.append( self.get_model_field_data(user, field_name)) # Check for profile class profile_class = get_profile_class() if profile_class: try: profile = profile_class.objects.get(user=user) except ObjectDoesNotExist: profile = profile_class(user=user) field_names = [f.name for f in profile._meta.local_fields] for field_name in field_names: if field_name in ('user', 'id'): continue field_data.append( self.get_model_field_data(profile, field_name)) return field_data def get_model_field_data(self, model_class, field_name): """ Extract the verbose name and value for a model's field value """ field = model_class._meta.get_field(field_name) if field.choices: value = getattr(model_class, 'get_%s_display' % field_name)() else: value …