Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check if field is valid for prefetching
Given models: class Parent: ... class Child: parent = models.ForeignKey(Parent, on_delete=models.CASCADE) parent_id = models.IntegerField() Is there a way to check that parent is valid for prefetch - without actually running the query and crashing? Given a list like ['parent', 'parent_id'] I want to do something like: Child.prefetch_related(['parent', 'parent_id']) where it ignores parent_id. -
How to Sum a column from a JSON field in string format? DJANGO
How to Sum a column from a JSON field in string format? DJANGO I have done it in several ways. Could we help with this problem? I am very grateful for everyone's attention. Thanks. transaction = Transactions.objects.all().annotate(amount=KeyTransform('amount','metadata')).aggregate(Sum('amount')) print(totalAmount) django.db.utils.ProgrammingError: function sum(jsonb) does not exist APP | LINE 1: SELECT SUM("amount") FROM (SELECT("libertyblue_transaction"... APP | HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
I did python upgrade from 2.7 to python 3.5.2 , but gunicorn is not working in Linux 6.10 - 0 instances are running - failed
we upgraded virtual environment too , through svn revision number we updated all requirements we have both 2.7 and 3.5.2 python versions in the system . is this making issue ? -
In Django, why blank=True in the model is not making the form field not mandatory?
In the django documentation there is information that by declaring a model field of type CharField as blank=True, the form will not require filling in the respective field. However, in my project that is not working. To make a field not mandatory in the form, the only alternative I found was to define it as required=False. I am using Django 3.0.2. -
How would I unit test this function that takes request as a param?
Hello I am brand new to unit testing and I just cant wrap my head around it. This is the simplest function I need to test and I am clueless as how to even do that. I know I need to pass a mock request object I think but beyond that I'm pretty lost. Could use some guidance. def get_all_zones(request): user = request.user all_site = get_objects_for_user(user, 'sitehotspot_portal', klass=SiteHotspot).values_list('uid', 'name') all_site = [list(i) for i in all_site] all_area = get_objects_for_user(user, 'areashotspot_portal', klass=AreasHotspot).values_list('uid', 'name') all_area = [list(i) for i in all_area] all_sphere = get_objects_for_user(user, 'spherehotspot_portal', klass=SphereHotspot).values_list('uid', 'name') all_sphere = [list(i) for i in all_sphere] all_zones = all_area + all_site + all_sphere return(all_zones)``` -
How to check permissions on currently-viewed model in Django admin template
How do you check whether the logged in user has add/change/etc permissions for the currently-viewed model? I'm trying to override object-tools-items in admin/change_list_object_tools.html with custom buttons, but I can't seem to figure out how to check if the user can make changes for that model to decide whether the button appears or not. -
How to change file name to a random 60 characters string during file upload in S3Boto3Storage?
How to change file name to a random 60 characters string during file upload in S3Boto3Storage? I use models.FileField from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION -
Django throws OperationalError : index row requires 35424 bytes, maximum size is 8191
I have a model class Question(models.Model): number = models.IntegerField(default=1) question = models.TextField(null=True,blank=True) exam = models.ForeignKey( "Exam", related_name="questions", on_delete=models.CASCADE, ) marks = models.IntegerField(default=1) audio = models.FileField( upload_to='audios/', blank = True, null = True ) class Meta: unique_together = [ # no duplicated number per exam ("exam","question", "number"), ] ordering = ("number",) def __str__(self): return self.exam.name+ '-'+ self.question I want to save questions using this model. I have used a rich text editor for the question field and base64 encoded audio for the audio field. Whenever I try to add a new instance with a large rich text (i.e contains image) Django throws an exception saying index row requires 35424 bytes, maximum size is 8191\n",. I even tried to upload a new instance from django admin panel and the error it gave is: OperationalError at /admin/exam/question/14/change/ index row requires 35424 bytes, maximum size is 8191 Request Method: POST Request URL: http://127.0.0.1:9025/admin/exam/question/14/change/ Django Version: 3.0.1 Exception Type: OperationalError Exception Value: index row requires 35424 bytes, maximum size is 8191 Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /usr/local/bin/python Python Version: 3.7.6 Python Path: ['/backend','/usr/local/lib/python37.zip','/usr/local/lib/python3.7','/usr/local/lib/python3.7/lib-dynload','/usr/local/lib/python3.7/site-packages'] Server time: Thu, 13 Feb 2020 15:07:35 +0000 -
DRF throw django.core.exceptions.ImproperlyConfigured why override get_queryset
Django Rest Framework throw: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "customuser-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. when I try to override get_queryset . My User serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): """ Represent User Serializer class. """ teacher_account = TeacherSerializer(required=False) student_account = StudentSerializer(required=False) account_type = serializers.IntegerField(required=True) class Meta: model = CustomUser fields = ['url', 'username', "password", 'email', 'first_name', 'last_name', "account_type", 'teacher_account', 'student_account'] email_validator = UniqueValidator(queryset=CustomUser.objects.all(), message="A user with that email already exists.") extra_kwargs = { "password": {"write_only": True}, "email": {"required": True, "validators": [email_validator]} } @staticmethod def setup_eager_loading(queryset): queryset = queryset.select_related('teacher_account', 'student_account') return queryset users/models.py: class StudentAccount(models.Model): """ Represent student's account model. """ classes = models.ManyToManyField('classroom.Class', related_name="students") class TeacherAccount(models.Model): """ Represent teacher's account. use get_subject_name from {root}/utils.py for get name of the subject. """ subject_id = models.PositiveSmallIntegerField("Предмет", choices=SUBJECTS_CHOICES, blank=False, default=0) class CustomUser(AbstractUser): """ Represent Custom user model, inherited from AbstractUser account_type = 0(teacher) or 1(student) """ student_account = models.OneToOneField(StudentAccount, on_delete=models.CASCADE, blank=True, null=True, related_name="user") teacher_account = models.OneToOneField(TeacherAccount, on_delete=models.CASCADE, blank=True, null=True, related_name="user") account_type = models.PositiveSmallIntegerField(default=1) first_name = models.CharField("-", max_length=30, blank=False) last_name = models.CharField("-", max_length=150, blank=False) My views.py: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users … -
Dropdown list in recursive loop
I have one search bar. In that search bar i want to display two dropdown list simultaneously. First i have to select a value from one dropdownlist in which values of second dropdown list is hidden and if value is selected, i have to immediately display second dropdown list by hidding values of first dropdown list and this should happen in a loop <div class="card-header" style="background: #c0c0c0;"> {% load tag_labels %} {% tag_labels as alltags %} <div style="display:inline;"> <select id="selection" style="width:40%" onchange="changeFunc1()" multiple> <option value="0" disabled hidden>Filter multiple tags</option> {% for tags in alltags %} <option value={{forloop.counter}} hidden>{{ tags }}</option> {% endfor %} </select> <select id="logic" onchange="changeFunc2()" style="height:40%"> <option value="0" disabled>Select Operator</option> <option value="and">And</option> <option value="or">Or</option> <option value="in">In</option> <option value="not in">Not In</option> </select> </div> -
How i can add choice field related to other model and pass id current objects?
I have the form: class PersonForm(forms.ModelForm): amount = forms.DecimalField(label='Сумма') cars = forms.ModelChoiceField( queryset=CarProductData.objects.all() ) class Meta: labels = { 'last_name': 'Фамилия', 'first_name': 'Имя', 'middle_name': 'Отчество', 'amount': 'Сумма к списанию', } fields = ['amount', ] and i want to get queryset inside admin.ModelAdmin related to current object, something like this: def get_form(self, request, obj, **kwargs): from django import forms from taxi_billing.models import CarProductData form = super().get_form(request, obj, **kwargs) form.cars = forms.ModelChoiceField( queryset=CarProductData.objects.filter( product__subscriptionitem__subscription__customer__person__id=obj.id ) ) return form How can i make it done? -
How to save two forms in same template in models
This is my template. I have got 2 forms , one is for submitting the test and other is for subtest.When I try to submit one form, I get not null_constraint error . <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="test-popup" class="icon-cross"></i> </div> <div class="input-group"> <input type="text" name="name" placeholder="Test name" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> </div> <div id="menu-test-popup"> <form method="POST"> {% csrf_token %} <div class="icon-holder"> <i data-modal-target="menu-test-popup" class="icon-cross"></i> </div> <div class="input-group"> <label for="test-select">Test Name:</label> <select name="test-select" id="test-select"> {% for test in test %} <option value="{{test.name}}" name="choices">{{test.name|title}}</option> {% endfor %} </select> </div> <div class="input-group"> <input type="text" name="subtest" placeholder="SubTest name" /> </div> <div class="input-group"> <input type="text" name="reference" placeholder="Reference rate" /> </div> <div class="input-group"> <input type="text" name="unit" placeholder="Unit" /> </div> <div class="button-group"> <button type="submit">Submit</button> </div> </form> this is my models . In my models I have test and subtest. class Test(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subtest(models.Model): name = models.CharField(max_length=100) test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True) unit = models.CharField(max_length=10) reference_value = models.IntegerField() selected = models.BooleanField(default=False) def __str__(self): return self.name this is my view. And the 2nd one is the template_context_processor for my convience def home(request): name = None if request.method == 'POST': name = request.POST.get('name') choices = request.POST.get('choices') … -
Not displaying post reshare, user link & other post parameters
Im trying to add user link and post reshare user, but its not displaying parent user and link to both users. Below is the code post_list.html function attachPost(postValue, prepend, reshare){ var dateDisplay = postValue.date_display; var postContent = postValue.content; var postUser = postValue.user; var postFormattedHtml; if (reshare && postValue.parent){ var mainPost = postValue.parent postFormattedHtml = "<div class=\"media\"><div class=\"media-body\"><span class='grey-color'>Reshare via " + postUser.username + " on " + dateDisplay + "</span><br/>" + mainPost.content + "<br/> via <a href='" + mainPost.user.url + "'>" + mainPost.user.username + "</a> | " + mainPost.date_display + " | " + "<a href='/post/" + mainPost.id + "'>View</a>" + "</div></div><hr/>" } else { postFormattedHtml = "<div class=\"media\"><div class=\"media-body\">" + postContent + "<br/> via <a href='" + postUser.url + "'>" + postUser.username + "</a> | " + dateDisplay + " | " + "<a href='/post/" + postValue.id + "'>View</a>" + "</div></div><hr/>" } if (prepend==true){ $('#posts-container').prepend(postFormattedHtml) } else { $('#posts-container').append(postFormattedHtml) } } Python 3.8.0 Django '3.0.2' -
How to add an additional field in Django model form
I am trying to include some dummy fields in my model form and using the same in model formset factory. Model form: class DistForm(forms.ModelForm): dist_from_txt = forms.TextInput() ... class Meta: model: Distance fields = ('dist_from', 'dist_to', 'distance') widgets = { ... } However, when rendered the extra field does not show up on the form. Needlessly to mention here that I have searched (including here) and failed to find a possible solution. Question is: How to correctly add and render extra field/s in model form? -
Keeping the value salected in the drop-down list after the search
I have got a filter on my page, that filters my items by the category. You can choose the category from a drop-down list and then press search and the filtered content is displayed. The only problem is that, the drop-down list resets and doesn't show the category, that the current items are filtered by. Anyone knows how to solve this? views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) html: <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option value="" selected>Choose...</option> <option value="" href="/home">All</option> {% for cat in category %} <option value="{{ cat.pk }}"> {{ cat }}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-primary">Search</button> </form> -
Saleor front-end installation
I am trying to install saleor front-end package from github.The documentation is outdated and i get an error when i try >>>nmp start Error: Environment variable API_URI not set I found this variable in different places but did not know what to change, and where to set it -
Django REST framework: how to wrap the response with extra fields .... and supply the current response in data field
So, I have the following: class ObjectViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet ): """ REST API endpoints for Objects. """ serializer_class = ObjectSerializer queryset = Object.objects.all() This returns, say, for a list GET request: [ { "uuid": "787573a2-b4f1-40df-9e3a-8555fd873461", }, { "uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665", } ] However, how could I slightly alter this response for mixins to be similar to the following: { success: true, message: 'Some Extra Useful Message', data: [ { "uuid": "787573a2-b4f1-40df-9e3a-8555fd873461", }, { "uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665", } ] } Is this possible, or should I just write my own custom endpoint Response() and not utilise DRF's mixins capability? So, essentially, switching the custom: Response(data, status=None, template_name=None, headers=None, content_type=None) To: response = { 'success': true, 'message': 'Some Extra Useful Message', 'data': serializer.data } Response(response, status=None, template_name=None, headers=None, content_type=None) -
modifying class based view to add data to logged in user
hey there im trying to modify my todoapp to be user specific in terms of accessing todolists but i've encountered a challenge in changing my class based views in order to accomplish this for example ensuring that when i create a todo its added to the todolist of the logged in user here is my current code models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone import datetime # Create your models here. class TodoList(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Todo(models.Model): todolist = models.ForeignKey( TodoList, on_delete=models.CASCADE) name = models.CharField(max_length=100, default='unamedTodo') description = models.CharField(max_length=200) Todo_date = models.DateTimeField('Todo Date') pub_date = models.DateTimeField('Date Published') def get_absolute_url(self): return reverse('ToDo:detail', kwargs={'id': self.id}) def get_back_home(self): return reverse('ToDo:todos', kwargs={}) def go_to_update(self): return reverse('ToDo:update', kwargs={'id': self.id}) def go_to_delete(self): return reverse('ToDo:delete', kwargs={'id': self.id}) views.py from .forms import TodoForm from .models import Todo from django.template import loader from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib.auth.forms import UserCreationForm from django.views.generic import ( CreateView, ListView, DetailView, UpdateView, DeleteView ) from django.urls import reverse, reverse_lazy from django.shortcuts import render, get_object_or_404 # Create your views here. @method_decorator(login_required, name='dispatch') class TodoListView(ListView): template_name = 'ToDo/todo_list.html' queryset … -
Cannot set PeriodicTask schedule
I use Django Celery Beat in order to manage periodic tasks. Here, I create a periodic task and set it some schedule: new_instance = PeriodicTask.objects.create( name=f'L1 Synchonisation created at {timezone.now()}', task='integrations.tasks.test_task', ) schedule, _ = IntervalSchedule.objects.get_or_create( every=self.every, period=self.period ) new_instance.interval = schedule print(new_instance.interval) # new_instance.interval is not None new_instance.save() print(new_instance.interval) # None new_instance.refresh_from_db() print(new_instance.interval) # None My question is, why does new_instance.interval become None and how do I prevent it from doing so? -
Django Reverse Filter Queryset Foreign Key Example Not Working
I'm loosely following the example laid out here: Django Queryset with filtering on reverse foreign key Model: class Site(models.Model): name = models.CharField(max_length=50) class Profile(models.Model): Days = '1st' Mids = '2nd' Nights = '3rd' Work_Schedule_Choices = [ (Days, 'Day Shift'), (Mids, 'Mid Shift'), (Nights, 'Night Shift'), ] sitename = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='profiles') title = models.CharField(max_length=100) schedule = models.CharField(max_length=3,choices=Work_Schedule_Choices,default=Days) totalusers = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(50)]) views: def sitedetail(request): site = Profile.objects.filter(id_in=Profile.sitename) if request.method == 'GET': return render(request, 'App/site-detail.html', {'profile_set': Profile.objects.all(site)}) When I load the page it gives a FieldError: Cannot resolve keyword 'id_in' into field. Choices are: id, schedule, sitename, sitename_id, title, totalusers Can someone help me understand what I am doing wrong? I see the same stack article referenced numerous times so I'm assuming it's Operator-Head-Space-Timing error :) Thanks in advance. -
Best practice for getting data from Django view into JS to execute on page?
I have been told it is 'bad practice' to return data from a Django view and use those returned items in Javascript that is loaded on the page. For example: if I was writing an app that needed some extra data to load/display a javascript based graph, I was told it's wrong to pass that data directly into the javascript on the page from a template variable passed from the Django view. My first thought: Just get the data the graph needs in the django view and return it in a context variable to be used in the template. Then just reference that context variable directly in the javascript in the template. It should load the data fine - but I was told that is the wrong way. So how is it best achieved? My second thought: Spin up Django Rest Framework and create an endpoint where you pass any required data to and make an AJAX request when the page loads - then load the data and do the JS stuff needed. This works, except for one thing, how do I get the variables required for the AJAX request into the AJAX request itself? I'd have to get them … -
How to add a model field calculated by data from to other model?
I have the following models: # models.py class Test(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Tester(models.Model): test_id = models.ForeignKey(Test, on_delete=models.DO_NOTHING) class TestViewset(viewsets.ModelViewSet): serializer_class = TestSerializers permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): if self.request.user.is_superuser: return Test.objects.all() else: return Test.objects.filter(author=self.request.user) So each test can be made by many testers. My wish is to count how many testers conducted the test , i.e when I do a GET request to the TestViewset I wish to get in addition to current fields [name, author] a count field , for each test which specify how many testers have been tested. Appreciate the help! -
IntegrityError at /doctor/Appointment/
'''my code''' here is my model i am getting null constrain error class Patient(models.Model): patient_name=models.CharField(max_length=20, null=True,blank=True) date_of_birth=models.DateField(null=True) email=models.EmailField(null=True,blank=True) mobile_number=models.IntegerField(null=True) family_members=models.IntegerField(null=True) def __str__(self): return self.patient_name def is_staff(self): return self.mobile_number class Doctor(models.Model): doctor_name=models.CharField(max_length=20,null=True,blank=True) email_id=models.EmailField(null=True,blank=True) doctor_number=models.IntegerField(null=True) address=models.CharField(max_length=100,null=True,blank=True) def __str__(self): return self.doctor_name class Appointment(models.Model): user_name=models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='first') mobile_no=models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='second') def __str__(self): return self.user_name #here is my viewset class AppointmentViewSet(viewsets.ViewSet): def create(self,request): user_name=request.data.get('user_name') mobile_no=request.data.get('mobile_no') new=Appointment() new.user_name=user_name new.mobile_no=mobile_no new.save() return Response({'done':True}) -
Django Rest Framework - OneToOne reverse relation
I have a custom User model and the User Profile model. class User(AbstractUser): """Custom User authentication class to use email as username""" username = None email = models.EmailField(verbose_name='email', max_length=255, unique=True, error_messages={ 'unique': _( "A user is already registered with this email address"), }, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(User, to_field='email', on_delete=models.CASCADE) emp_id = models.CharField(max_length=20, blank=False, default='0', null=False) department = models.CharField(max_length=50, blank=True, default='', null=True) I am trying to write a serializer that combines both these models are produces a nested JSON. for example: { "email":"user@gmail.com", "is_active":true, "profile": { "emp_id":2, "department":2 } } This is what I tried to do class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'user', 'emp_id', 'department') class UserPairSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(read_only=True) class Meta: model = User fields = ('id', 'email', 'is_active', 'profile') But for some reason, there is neither the field profile in my response nor am I getting any errors. I tried following this docs: https://www.django-rest-framework.org/api-guide/relations/ What is the issue and how do I solve this? -
Error during travis ci integration in django and postgres
I integrated travis in to my project where i used postgres but when i tried to test i got stuck in with an unkwown error i.e $ python manage.py test Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/runner.py", line 554, in setup_databases self.parallel, **kwargs File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/utils.py", line 157, in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/test/utils.py", line 258, in get_unique_databases_and_mirrors default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 295, in test_db_signature self._get_test_db_name(), File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 153, in _get_test_db_name return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] TypeError: must be str, not NoneType The command "python manage.py test" exited with 1. I used postgres format as below in .travis.yml file services: - mongodb - postgresql before_script: - sleep 15 - psql -c 'create database myapp_test;' -U postgres What i will do?