Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make 2 or more objects of the same model on one Django admin page stack horizontally, but be in a vertical position
Yes, there are StackedInline and TabularInline, but I want to combine this 2 into 1 that objects stack horizontally, but be in a vertical position. -
How do I Design this Django Models to handle a Question, a Couple of Choices and the Answer(amongst the choices)?
This is the models file. from django.db import models from django.core.validators import MaxLengthValidator class Subject(models.Model): # This model is doing what it's supposed to name = models.CharField(max_length = 20) # Eg. Mathematics symbol = models.CharField(max_length = 5) # Eg. MTH class Question(models.Model): # This model is the one that rattles me. question_text = models.CharField(max_length = 255) choice_a = models.CharField(max_length = 255) choice_b = models.CharField(max_length = 255) choice_c = models.CharField(max_length = 255) choice_d = models.CharField(max_length = 255) CHOICES = [ (choice_a, "A"), (choice_b, "B"), (choice_c, "C"), (choice_d, "D") ] solution = models.CharField( default = choice_a, choices = CHOICES, max_length = 2, ) Here is the front-end of the model outcome You can have a look at the whole Github repo here to get a full view of the whole project. -
Convert a node.js code which sorts the data into Django
My data looks something like this. data = [ [ { second: 12, minute: 27, hour: 21, data: 'NullPointerException' }, { second: 12, minute: 27, hour: 21, data: 'NullPointerException' }, { second: 12, minute: 27, hour: 21, data: 'IllegalAgrumentsException' }, { second: 32, minute: 0, hour: 22, data: 'UserNotFoundException' }, { second: 12, minute: 17, hour: 22, data: 'NullPointerException' }, { second: 52, minute: 33, hour: 22, data: 'UserNotFoundException' }, { second: 52, minute: 33, hour: 22, data: 'UserNotFoundException' }, { second: 52, minute: 33, hour: 22, data: 'UserNotFoundException' }, { second: 32, minute: 50, hour: 22, data: 'UserNotFoundException' }, { second: 12, minute: 7, hour: 23, data: 'NullPointerException' }, { second: 52, minute: 23, hour: 23, data: 'UserNotFoundException' }, { second: 32, minute: 40, hour: 23, data: 'NullPointerException' }, { second: 32, minute: 40, hour: 23, data: 'NullPointerException' }, { second: 12, minute: 57, hour: 23, data: 'IllegalAgrumentsException' }, { second: 52, minute: 13, hour: 0, data: 'UserNotFoundException' }, { second: 32, minute: 30, hour: 0, data: 'NullPointerException' }, { second: 12, minute: 47, hour: 0, data: 'UserNotFoundException' }, { second: 52, minute: 3, hour: 1, data: 'IllegalAgrumentsException' }, { second: 32, minute: 20, hour: 1, data: 'UserNotFoundException' }, … -
How to reduce web page load time?
I have a website built using DJango. And one of the pages (http://ncov19info.tk/country) includes a huge number of images (more than 200) and it takes a lot of time to load the page (almost 1 minute). So please suggest some measures to reduce the loading time of the web page. -
Couldt not find a version that satysfies the requirement pytz
i have Linux Ubuntu 18.04. I need to install Django offline on this machine. I had some problems with pip and python, but i guess i solved it. So, i download asgiref, sqlparse and pytz for installing modules. When i install asgiref and sqlparse - it's ok, django see it, but with pytz, i have a terrible problems: django doesn't see it, andi try reinstall it a lot of time. I try to use python3.7 -m pip install --pre pytz-2020.1-py2.py3-none-any.whl but it doesn't help. So in python3.7 -m pip list it shows, that pytz install, but actually i can't to delete it. Finally, when i try (in folder with fjango installer) python37 -m pip install . I have this error https://i.stack.imgur.com/jRE6q.png Couldt not find a version that satysfies the requirement pytz -
get javascript variable value and store it to django variable and use it vice versa
I want to store the javascript values in my django variables or use it in my view query //javascript values want to store in django var js_latitude = 122.33; var js_longitude = 12.22; django_latitude = js_latitude django_longitude = js_longitude save this value to my Django variable and calculate or multiply the values then it will be displayed by view or use in my query . just like location variable and save to Django and calculate distance than also -
how to get post data in django from iterating over different id
I am creating a app which is quetion and 4 options.Each time it gives different 5 quetions.using a id in html page i am creating a radio button for each choice.Now how can save this value by post method in database. views.py def result(request,id) : if request.method=='POST': selected_choice = request.POST['choice.id'] return redirect('list_view.html') else: return render (request,'create_view.html') urls.py path('result/<id>',views.result,name='result') html page <div> {% for element in q %} <h2>{{element.id}} .{{element.question}}</h2> <form action="{% url 'app1:result' element.id %}" method="POST"> {% csrf_token %} {% for choice in c %} {% if element.id == choice.id %} <input name="{{choice.id}}" type="radio" >{{choice.choice1}}<br> <input name="{{choice.id}}" type="radio" >{{choice.choice2}}<br> <input name="{{choice.id}}" type="radio" >{{choice.choice3}}<br> <input name="{{choice.id}}" type="radio" >{{choice.choice4}}<br> {% endif %} {% endfor %}<br> {% endfor %} <input type="submit" value="submit"> </form> </div> models.py class Question(models.Model): question=models.CharField(max_length=100) def __str__(self): return self.question class Choice(models.Model): choice1=models.CharField(max_length=50) choice2=models.CharField(max_length=50) choice3 = models.CharField(max_length=50) choice4 = models.CharField(max_length=50) question = models.ForeignKey(Question, on_delete=models.CASCADE) -
React fetch error when fetching DRF hosted on heroku
I got django rest framework deployed on heroku and react app there again. React fetches api drf and when it tries it just shows the message "Error: NetworkError when attempting to fetch resource." how can i solve this problem? -
failed to retrieve tasks. database unreachable. django background tasks error
I am using django-background-tasks. My django application process_tasks process starts giving error "Failed to retrieve tasks. database unreachable." after some time. Can anyone tell reason and provide solution? -
Django Sendgrid Heroku setup
I use a Django / Sendgrid / Heroku setup which was working well but it stopped with no apparent reason. my django settings: EMAIL_HOST="smtp.sendgrid.net" EMAIL_HOST_PASSWORD="..." EMAIL_HOST_USER="..." EMAIL_PORT=587 EMAIL_USE_TLS=True with this settings, if I send simple emails with the django library... from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', from_email_address, [to_email_address], fail_silently=False, ) I get this error --> SMTPServerDisconnected: Connection unexpectedly closed I can still send emails using the sendgrid python library import sendgrid sg = sendgrid.SendGridAPIClient(apikey) sg.send(data) Is there anything I am missing? -
why does UserForm class need addtional password field if it has already 'password' attribute in Meta class?
Here is my code from forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') -
Django ORM filter() for multiple results
I have the following models: class DisputeAssignments(models.Model): case_id = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='dispute_assigned_to') user_id = models.ForeignKey('users.User', on_delete=models.CASCADE, blank=False, null=False, related_name='assigned_disputes') assignment_date = models.DateTimeField() class Case(models.Model): sn = models.CharField(max_length=100, verbose_name=_('Serial number')) user = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='cases') class FullVector(models.Model): full_feature_vector = models.BinaryField() version = models.FloatField() processed_on = models.DateTimeField() case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='full_vectors') class ShortVector(models.Model): id = models.BigAutoField(primary_key=True) detailed_fv_version = models.BinaryField() full_vector = models.ForeignKey(FullVector, on_delete=models.CASCADE, related_name='short_vectors') short_vector = models.BinaryField(null=True) class Prediction(models.Model): id = models.BigAutoField(primary_key=True) short_vector = models.ForeignKey(ShortVector, on_delete=models.CASCADE, related_name='predictions', null=True, default=None) verif_req = models.SmallIntegerField(default=1) Now, this relationship allows situations, where more than one entry from FullVector model points to the same Case entry. Moreover, there is always more than 1 ShortVector entry pointing to the same FullVector entry, and there is always one Prediction entry pointing to each ShortVector entry. Example: Case --> FullVector1 --> ShortVector1 --> Prediction1 | |-> ShortVector2 --> Prediction2 | |-> ShortVector3 --> Prediction3 | \-> ShortVector4 --> Prediction4 | \-> FullVector2 --> ShortVector5 --> Prediction5 |-> ShortVector6 --> Prediction6 |-> ShortVector7 --> Prediction7 \-> ShortVector8 --> Prediction8 I need to write a Django ORM query, which for each DisputeAssignment entry will check, if ALL Prediction entries associated with it (through Case -> different FullVector and ShortVector entries), have … -
How do I query Wagtail tags without it creating hundreds of queries, n+1 problem?
I have a handful of entries that each has dozens of "tags" when I try to fetch that data it causes hundreds of queries. While using prefetching works on all of my other models and links, it does not seem to work on this. The post below says it has something related to wagtails fake query function but it hasn't been fixed yet. Is there a way to utilize tags where I can fetch them via the api so they don't create hundreds of queries (one for each tag) making them unusable due to their slow response time? Any help you can provide would be much appreciated. A similar issue was brought up here but got no answer How to prefetch Wagtail post tags? Also, when I use prefetch it actually doubles the number of queries Here is my code: # serializer.py//////////////////////////////////// # orderable models links # Custom searializers to add custom display fields class EventCollectionSerializer(serializers.ModelSerializer): class Meta: model = CategoryEventCollection fields = ['id', 'collection_name', 'collection_event'] class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['name', 'id'] # MAIN SERIALIZER PRIMARY FOCUS class PrimaryFocusSerializer(serializers.HyperlinkedModelSerializer): # assign fields to custom serializer event_collection = EventCollectionSerializer(many=False) tags = TagSerializer(many=True) class Meta: model = … -
Filtering objects in ListView by Date - Django
So, in my project there is a listview in which i would like to show the objects containing only the current date, i am using the datetime module and overwriting of the getquery method, but the view has been showing all the elements no matter what date. View date = datetime.date.today() class AppointmentIndexView(ListView): model = Consults template_name = 'appointments_index.html' context_object_name = 'consults' paginate_by = 7 def get_queryset(self): queryset = super().get_queryset() queryset.filter(Fecha=date) return queryset -
How to get duplicate record flag with all rows
Problem: Want a flag for all rows that the same appointment is reoccurring or not in future (means: the same user at that same time) Tried: But it only outputs the duplicate ones with no id Appointments.objects.filter(appointdatetime__gt=today() ).annotate(time_only=Cast( 'appointdatetime', TimeField()) ).values('time_only', 'userid').annotate( created_count=Count('userid')).order_by('time_only').exclude(created_count=1) Output: <QuerySet [{'userid': 438, 'time_only': datetime.time(5, 0), 'created_count': 2}, {'userid': 762, 'time_only': datetime.time(5, 0), 'created_count': 5}, {'userid': 214, 'time_only': datetime.time(13, 15), 'created_count': 4}]> How can I achieve this in the main query or how can I get the appointment id list from the above query? -
Django - How do I populate the user field of a model by default in the admin panel based on the current user logged in?
I am trying to create a question-answer forum in django where only the admins are able to respond to a question asked by all the registered users. models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. class Question(models.Model): username=models.ForeignKey(User, on_delete=models.DO_NOTHING) question=models.CharField(max_length=100) date=models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.question class Comments(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.question.question, str(self.user.username)) admin.py from django.contrib import admin from . models import Question, Comments # Register your models here. admin.site.register(Question) admin.site.register(Comments) views.py from django.shortcuts import render, redirect from . models import Question, Comments from .forms import CommentForm # Create your views here. def addQuestion(request): if request.method == 'POST': username = request.user question = request.POST['question'] question = Question(username=username, question=question) question.save() # note=Note(title=title, description=description, username=username) # note.save() return redirect('/dashboard') else: return render(request, "dashboard/question.html") def viewQuestion(request, question_id): viewquestion=Question.objects.get(id=question_id) comments = Comments.objects.filter(question=viewquestion).order_by('-question_id') context = { 'viewquestion':viewquestion, 'comments':comments } return render (request, 'dashboard/questionview.html', context) As of now, the admin panel provides a drop down based on which I can select a user, but I need the model to display the authenticated admin user by default in the model before adding a … -
Getting queryset of only related models that appear in another queryset
I've got two models that are related to one another. class FAQCategory(models.Model): title = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.title class FAQ(models.Model): category = models.ForeignKey(FAQCategory, on_delete=models.SET_NULL, null=True, blank=True) question = models.CharField(max_length=100, null=True, blank=True) answer = models.TextField(max_length=10000, null=True, blank=True) I've got a queryset of faqs. faq_list = FAQ.objects.filter(user=user).exclude(answer="").exclude(question="").exclude(category=None) How do I get a queryset of the unique FAQCategory instances that are represented in the faq_list? faq_category_list = FAQCategory.objects.filter( ...appear in faq_list... ) Thanks! -
Django-select2 with nested widgets no rendering data
i have the simple example on django_select2 widget with nested data, with state and city my model form looks like this from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): # group = 'host' error_css_class = 'is-invalid' password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'class': 'form-control'}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={'class': 'form-control'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) terms_and_conditions = forms.CharField( label=_('Terms and Conditions'), widget=forms.Textarea(attrs={'class': 'form-control disabled terms-and-conditions', 'readonly':'readonly'}), help_text=_("Please read carefully the terms and conditions for the app."), required=False, ) state = forms.ModelChoiceField( queryset=State.objects.all(), label=u"State", widget=ModelSelect2Widget( model=State, search_fields=['name__icontains'], dependent_fields={'city': 'city'}, attrs={'class': 'form-control', 'width': '100%', }, ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'state': 'state'}, max_results=100, attrs={'class': 'form-control', 'width': '100%', }, ) ) class Meta: model = User fields = [ 'email', 'first_name', 'last_name', 'id_number', 'mobile', 'avatar', 'state', 'city', 'address', 'approve_emails', 'terms_and_conditions', 'accept_terms' ] widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'id_number': forms.NumberInput(attrs={'class': 'form-control', 'required': 'required'}), 'birth_date': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}), 'gender': forms.Select(attrs={'class': 'form-control'}), 'mobile': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'avatar': forms.FileInput(attrs={'class': 'form-control'}), 'bio': forms.Textarea(attrs={'class': 'form-control'}), } def clean_new_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', … -
In django how to customize model admin to save in auth_user and another unrelated model simultaneously?
In django 3.0, I have 3 model classes derieved from an abstract model class as: class AbstractPerson(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(unique=True) muser_id = models.IntegerField(null=True, blank=True) class Meta: abstract = True def save(self, *args, **kwargs): if (not self.pk) and (self.email): muser = User.objects.get(id=self.muser_id).count() if muser: u = User() u.username = self.first_name.lower() u.is_staff = True u.first_name = self.first_name u.last_name = self.last_name u.email = self.email u.save() return super(AbstractPerson, self).save(*args, **kwargs) One of the model class: Customer class has been derieved from this abstract class. What I have tried by overriding the save method of the abstract class model to save the instance in django auth user and customer model. The CustomerModelForm is defined as follows This works fine during 'Add customer'. class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = "__all__" def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).count(): raise forms.ValidationError(_("Email already exists"), code='invalid') return email But during edit Customer, it is possible that the email id of the customer along with all other attributes might also change. How to then access the corresponding auth User details for the same customer? I require to store the User 'id' value in 'muser_id' attribute of the customer instance. I have used … -
Django project will not load in CSS files
I am currently directly following the tutorial here: https://www.youtube.com/watch?v=qDwdMDQ8oX4 about setting up a blog website through Django. When I attempt to load in my CSS files, I obtain the same screen that the person in the video was achieving @38:01, when he claims the css wasn't loading in (I have restarted my server many times so that isn't the issue). For reference it should look like the screen @38:51 No colors and the header bar is mixed with the page header. I am able to open up the css through the source code on the browser, so it must be being referenced correctly; however here is my relevant code: to reference the static files in settings.py (Note I had it exactly like how it is in the video and changed it to this with no change): STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) the attempt to use the css file as a stylesheet: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stytlesheet" type="text/css" href="{% static 'blog/main.css' %}"> My project directory Also … -
How to implement django guardian to restrict user access to model instances
I'm building an app in which users will be able to upload data for specific "sites", defined by the class below: class Site(models.Model): name = models.CharField(max_length=150) code = models.CharField(max_length=10) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField() longitude = models.FloatField() Each Site will have "Data" objects associated with it, which users will need permission to create. For instance, 'User A' should only be able to upload data for 'Site A', and 'User B' to 'Site B'. How do I implement this into the Site model and on the User model side? What I would like is a way from the admin panel to easily assign users to a site (or multiple sites). -
I'm trying to get an array of objects from Django Database through AJAX but I'm not getting how to parse back to JSON
I want to get few indexes every time, pressing Next and Previous Button So here is the view: class RetrieveCrudUser(View): def get(self, request): fromIndex = int(request.GET.get('fromIndex', None)) toIndex = int(request.GET.get('toIndex', None)) print("from index: "+str(fromIndex)) print("to index: "+str(toIndex)) if fromIndex > CrudUser.objects.all().count()-1: print("entered in the if") fromIndex = 0 toIndex = 2 elif toIndex > CrudUser.objects.all().count()-1: print("entered in the elif") toIndex = CrudUser.objects.all().count()-1 users = serializers.serialize("json",CrudUser.objects.all().order_by('id')[fromIndex:toIndex]) print(type(users)) data = { 'users': users, 'fromIndex': fromIndex, 'toIndex': toIndex } return JsonResponse(data) And here, the javascript: function showNext(){ fromIndex+=3 toIndex+=3 $.ajax({ url: "{% url 'crud_ajax_retrieve' %}", data: { 'fromIndex' : fromIndex, 'toIndex' : toIndex, dataType: 'json', }, success: function (data) { fromIndex = data.fromIndex toIndex = data.toIndex let temp = JSON.parse(data.users) console.log(temp) // TODO: clear table html #tbody // TODO: for each user append to the table } }) } And this is what it prints (the temp variable) -> And it says the datatype is Object (I don't understand why it is not an array) I want to get an array of those "fields" keys as user objects. PRINT OF GOOGLE CHROME CONSOLE -
Changing the Date Format in Django
I am working in a ListView in Django where i would like to show the objects from a database that contain the current date, and i was trying to do this using a queryset and the datetime module, but the terminal throws the following error: Error django.core.exceptions.ValidationError: ["'05/19/20D/00M/2020YYY' value has an invalid date format. It must be in YYYY-MM-DD format."] Views class AppointmentIndexView(ListView): model = Consults template_name = 'appointments_index.html' context_object_name = 'consults' paginate_by = 7 queryset = Consults.objects.filter(Fecha=date.strftime("%DD/%MM/%YYYY")) Model class Consults(models.Model): #General Consult Info Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='Paciente') Fecha = models.DateField() Motivo = models.CharField(max_length=500,null=True) Padecimiento = models.CharField(max_length=500,null=True) #Main Patient Info Presion = models.CharField(max_length=20,blank=True,null=True) Temperatura = models.FloatField(blank=True,null=True) Peso = models.FloatField(blank=True,null=True) Talla = models.FloatField(blank=True,null=True) #Any Exams done before Estudios = models.ImageField(upload_to='studies',blank=True) #Interrogatory by System Digestivo = models.CharField(max_length=500,blank=True,null=True) Endocrino = models.CharField(max_length=500,blank=True,null=True) Renal = models.CharField(max_length=500,blank=True,null=True) Linfativo = models.CharField(max_length=500,blank=True,null=True) Respiratorio = models.CharField(max_length=500,blank=True,null=True) #Physical Exploration Cabeza = models.CharField(max_length=500,blank=True,null=True) Torax = models.CharField(max_length=500,blank=True,null=True) #Diagnose CIE_10 = models.ForeignKey(CIE_10,on_delete=models.DO_NOTHING,blank=True,null=True) Detalle_de_Codigo = models.CharField(max_length=500,blank=True,null=True) Diagnostico = models.CharField(max_length=500,blank=True,null=True) Procedimiento = models.CharField(max_length=500,blank=True,null=True) Analisis = models.CharField(max_length=500,blank=True,null=True) #Treatment Medicamento = models.CharField(max_length=500,blank=True,null=True) Descripcion = models.CharField(max_length=500,blank=True,null=True) Uso = models.CharField(max_length=500,blank=True,null=True) Dosis = models.CharField(max_length=500,blank=True,null=True) Acciones = models.CharField(max_length=500,blank=True,null=True) I don't know if i am doing wrong in the use of the datetime module, the view or is there any django settings i … -
update status of boolean in django based on courses id
hello i am beginner to django as i am posting the some values to front end using the django, based on user will change the status will sent back, well receiving that status to backend its creating duplicates of id's can any one to help on this I want to update those checked values( [true to false] or [false to true]) in the django not to duplicates models.py class Course(models.Model): checked = models.BooleanField(default=False) value = models.CharField(max_length=255, default=True) courseid = models.IntegerField(default=True) serializers.py class CourseSerializers(serializers.ModelSerializer): class Meta: model = Course fields = ('checked', 'value', 'courseid') views.py class CourseViewSet(viewsets.ModelViewSet): serializer_class = CourseSerializers queryset = Course.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data) -
How to apply tab in django template
I have model which contains default values good_moral = models.TextField( _('Good Moral'), default=_( '''Dear John Doe, \t\tTHIS IS TO CERTIFY THAT ...... # verbosity '''), ) I would like to output it in django template as like Dear John Doe, THIS IS TO CERTIFY .... # this should be the exact to show in the pdf with tabs, newlines work just fine with linebreaksbr but I try some method but none of them works when on the pdf. PDF: wkhtmltopdf Anyone has done this? Thanks