Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to present user values on built-in EditProfileForm
My form is like at the photo . I want to show user's data like name , lastname , phone number ... https://imgur.com/a/5qgvNC1 in my forms.py i edit the EditProfileForm as CustomEditProfileForm . I am trying to give user's data in value part (value':User.Accounts.name) . I dont know how to pull the data from accounts model. class CustomEditProfileForm(EditProfileForm): name = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','value':User.Accounts.name})) middlename = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) lastname = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) highschool = forms.CharField(widget=forms.TextInput(attrs={'value':'highschool'})) college = forms.CharField(widget=forms.TextInput(attrs={'value':'college'})) citystate = forms.CharField(widget=forms.TextInput(attrs={'value':'citystate'})) -
Mocking form in class based view not using the MagicMock
I've been fighting with mocking a form class to replace an instance of it in a class-based view. But it looks like that because the form is in a class attribute, it happens before I replace the form class with my mock. Case in point: app/views.py from app.forms import SomeForm # For some reason, this _is_ my mock... class SomeViewClass(View): form = SomeForm # ... while this is the _real_ SomeForm def post(self, request): form = self.form(request.POST, request.FILES) # Hacked around with pdb here # (Pdb) self.form = SomeForm <-- Force the mock into the object # (Pdb) form = self.form(request.POST, request.FILES) # (Pdb) form.is_valid() is now True # (Pdb) continue <--- Test finishes, and asserts are OK. if form.is_valid(): # This fails, as I'm running the real code # code, code, code app/tests/test_views.py from mock import MagicMock, patch from django.tests import Client, TestCase @patch('app.views.SomeForm') def test_post_valid_form_should_pass(self, mocked_form_class): """ Replacing SomeForm in SomeViewClass to pas the is_valid test """ form_instance = MagicMock(spec=SomeForm()) form_instance.is_valid.return_value = True mocked_form_class.return_value = form_instance self.client.login(**self.credentials) # code, code, code As you can see in the inserted comments in app/views.py, I forcefully reloaded self.form and redefined the variable form using pdb, which made my test pass. It … -
Django: How to get the list of month within a daterange in django query
Suppose I have query: ExampleModel.objects.filter(some_datetime_field__gte=start, some_datetime_field__lte=end) How do I get the list of all months present within "start" and "end" in the above mentioned query. For example: IF start= 1/10/2018 and end=10/1/2019 Then the output will be: OCTOBER NOVEMBER DECEMBER JANUARY Anyone any idea how to perform this? Thank you in advance -
Django: stream an image file right into template using requests
Using requests I am fetching an image from a server. Instead of writing this file out and then using it to load into the template, I am trying to parse the contents onto the view (image data inline or another method). Below is the partial output from r.contents: b'/x89PNG/r/n/x1v/n/x0e/x20/x20/rIHDR/x00/x00/x22/xdb/x00/x00/x01/xad/x08/x06/x00/x00/x00/xc7/xe3/xb8/xe9/x10/x00/x00/x06bKGD/x00/xff/x00/xcf/x00/ Since its bytes, I tried to encode using base64 and then pass into the image data-url but haven't been able to render. Below is the partial output: <img id="now" style="max-width: 100%; width: auto;" alt="" src="data:image/png;base64,b&#39;iVBSDFSGcANSUhEUgAAAtsAAAGtCAYAAADH47jpAAAABmJLR0QA/wD/AP+gvSDFsfgsbfbvdsdsbdgndfnOy9eZwcV3nv/autt+mWRqPVY2ksCckWljXacAggexQvQK4NiXHEa1+JsbdfghgcEEOwlBwvHNIL8xvpFmwpIABl8I2HEYzJ4bY48AAzbyaEG2Lxfg463dR/Xpqaqufeuq6uf7+fSnu6vq1HOe012nTv3qqecABEEQBEfgdrcgbQBEEQBEEQBEEQBEEQBEEQfgdfgEEQBEEQAMA1 Is there a way to get this to work? Below is the sample view code in use, the code is meant to give an idea of this question: def graph(request): unix_time = int(time()) r = requests.get(f'http://192.168.1.10/graph.php?type=multi-port_bits_duo_separate&idb=393,204,132,31,36,214&to={unix_time}', auth=(USERNAME,PASS), stream=True) r.raise_for_status() # the write to file method, works but trying to stream contents into view #with open(f'{unix_time}.png','wb') as fd: # for chunk in r.iter_content(chunk_size=50000): # fd.write(chunk) context = {'context': r.content} return render(request, 'live_graph.html', context) -
response data in ApiRequestFactory() _ djangoRestFramework
I need to access the content of response in UnitTesing and API testing in Django rest framework. class AuthTest(APITestCase): def setUp(self): self.factory = APIRequestFactory() def test_get_token(self): """ checking if api works fine for getting tokens """ request = self.factory.get('regenerate-token/') response = views.regenerate_token(request) self.assertEqual(response.status_code, status.HTTP_200_OK) this code works fine. but I need the content of response object. -
MultiValueDictKeyError with modified inline template in Django admin
In Django 1.11, I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() class Bar(models.Model): name = models.CharField() foo = models.ForeignKey(Foo) My admin.py looks like this: class BarInline(admin.StackedInline): model = Bar template = 'admin/edit_inline/list.html' class FooAdmin(admin.ModelAdmin): fields = ('name') inlines = [BarInline] I use a customised template to show the Bar inline form, because I don't want the forms, just links to the edit pages for each Bar. list.html looks like this: {% load i18n admin_urls static %} <div class="js-inline-admin-formset inline-group" data-inline-type="stacked"> <fieldset class="module {{ inline_admin_formset.classes }}"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2> {{ inline_admin_formset.formset.management_form }} {% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last %} empty-form last-related{% endif %}"> <h3 style="overflow:auto"><span style="float:left">{{ inline_admin_formset.opts.verbose_name|capfirst }}:&nbsp;{% if inline_admin_form.original %}<a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}">{{ inline_admin_form.original }}</a>{% else %}#{{ forloop.counter }}{% endif %}</span><span style="float:right">{% if inline_admin_form.original %}<a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="inlinechangelink">Change</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="{% url 'admin:app_bar_delete' inline_admin_form.original.pk|admin_urlquote %}" class="deletelink">Delete</a>{% endif %}</span> </h3> </div>{% endfor %} <div class="add-row"> <a href="{% url 'admin:app_bar_add' %}?foo={{original.pk}}">Add a Bar</a> </div> </fieldset> </div> The problem is that when I edit an existing Foo, and click Save, I get the error: MultiValueDictKeyError at /admin/app/foo/1/change/ "'bar_set-0-id'" -
Django custom cache_page decorator
I am trying to override my django app's(restful API to be precise) caching. So it seems SessionMiddleware is setting vary header to Cookie. Because of this, every user has its own cache. But for my use case it does not need to have unique cache for every user. If a first person visited that route i want to cache it and serve cache to everyone(each user) since it's just a read-only endpoint. Because of vary: Cookie, it's not possible for default django cache. Cookie is different for any user. I dug django cache codes and found CacheMiddleWare is using UpdateCacheMiddleware, FetchFromCacheMiddleware Based on this i just had to write my own cache_page decorator just for certain Viewsets instead of writing whole middleware. All Middlewares(UpdateCacheMiddleware, FetchFromCacheMiddleWare) are extended from MiddlewareMixin Checking vary header is in UpdateCacheMiddleWare i tried overriding UpdateCacheMiddleWare but no luck. Please if anyone have solution please tell me. Thanks in advance. -
how to upload image using django with ModelForm , jquery , ajax
I've looked around at related questions, but none of the answers seem to work for me i need to upload image for each time the user submit the form meaning user have a for to fill in the requested data with the ability to upload image. i am using django and jquery with ajax once i click on submit button the system display this error jquery-1.12.4.min.js:4 Uncaught TypeError: Illegal invocation at e (jquery-1.12.4.min.js:4) at dc (jquery-1.12.4.min.js:4) at dc (jquery-1.12.4.min.js:4) at Function.n.param (jquery-1.12.4.min.js:4) at Function.ajax (jquery-1.12.4.min.js:4) at HTMLInputElement. (creativePage.html:214) at HTMLInputElement.dispatch (jquery-1.12.4.min.js:3) at HTMLInputElement.r.handle (jquery-1.12.4.min.js:3) these are the steps that i did it until now : add picture filed to models.py add picture element in the form.py create a form with enctype = "multipart/form-data" in the html page add the filed of image in the form in the html page add the img element in data field in jquery & ajax in order to send the request once the user click the submit button add the variable img in order to receive the data from ajax in views.py at the end saving the form. models.py class te2chira(models.Model): te2chira_id = models.AutoField( primary_key=True) num = models.IntegerField() # year = models.IntegerField() te2chira_date = models.DateField() … -
Displaying ImageField as required in swagger post api
My model: class Image(models.Model): image=models.ImageField(upload_to='photos') name=models.CharField(max_length=40,unique=False) My serializer: class imagesSerializer(serializers.ModelSerializer): image = Base64ImageField(required=True) class Meta: model = Image fields = ('id','name','image') My swagger looks like above: How to make the ImageField as required in my swagger post API using Django? -
Django encoding issue on ubuntu server
I am working on Django Rest Framework and I have a simple login view.py and everything is working perfectly fine on my localhost. But on ubuntu server it throws some strange error. Following is the view class class userDetail(generics.RetrieveUpdateDestroyAPIView): def post(self, request, *args, **kwargs): header = Header(request) checkHeader = header.checkHeader() if checkHeader['status'] == 0: return Response(checkHeader, status=status.HTTP_401_UNAUTHORIZED) # platform = request.META.get('HTTP_PLATFORM', 'Not Found') data = request.data serializer = loginSerializer(data = data) if serializer.is_valid(raise_exception=True): data = serializer.data username = data['username'] password = data['pword'] authenticate = Authentication(username, password) loginData = authenticate.check() if loginData[0]['status'] == 1: auth = skAuth_Token(loginData[0]['userID']) auth_token = auth.encode() if auth.saveToken(auth_token): rowData = UserMaster.objects.get(pk=loginData[0]['userID']) dataSerializer = loginDataSerializer(rowData) response = { 'status': 1, 'message': 'Login Successfull', 'header': checkHeader, 'skAuth_Token': auth_token, 'data': dataSerializer.data } else: response = { 'status': 0, 'message': 'Couldnot save skAuth_Token in dB', 'header': checkHeader, } elif loginData[0]['status'] == 2: response = { 'status': 2, 'message': 'User is not Registered as a seller', 'header': checkHeader } else: response = { 'status': 0, 'message': 'Login Failed', 'header': checkHeader } return JsonResponse(response) return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST) This Runs fine on my localhost(Windows). But gives the following error on ubuntu server. This is the main error - 'utf-8' codec can't decode byte 0x89 … -
How to fix this error - Not Found: /firstapp/ "GET /firstapp/ HTTP/1.1" 404 2065"
I have created a project named firstproject and added a new project firstapp in which urls.py of firstapp is invoked to call view.py which displays a string in webpage. But the webpage is showing error. I have created a project named firstproject and added a new project firstapp in which urls.py of firstapp is invoked to call view.py which displays a string in webpage. But the webpage is showing error. firstapp urls.py from django.conf.urls import url from . import views urlpatterns={ url('r^$',views.index,name='index') } views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<H2> Hey Everyone welcome to Django Tutorial! </H2>") # Create your views here. firstproject urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$/', include('firstapp.urls')), ] I expect the output to be "Hey Everyone welcome to Django Tutorial!" -
What framework should i choose yii or django?
What framework should I choose Yii or Django?. If Yii framework, then please guide me to call python files from controller and view pages of Yii. I want to install and access following library files for a machine learning project, Tesseract OpenCV Lipnet Pandas etc. Please note : I know to execute shell commands but i don't know how to implement in Yii -
Restrict values that appear in Django admin select box
In Django 1.11, I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() extra = models.BooleanField(default=False) class Bar(models.Model): name = models.CharField() extra_foo = models.ForeignKey(Foo) My admin.py looks like this: class BarInline(admin.StackedInline): model = Bar fields = ('name', 'extra_foo') class FooAdmin(admin.ModelAdmin): fields('name') inlines = [BarInline] My problem is that the in the Bar inline form, the dropdown for extra_foo shows all of my existing Foos. I want it to only show Foos for which extra is true. How can I modify the admin to restrict the available options in a select box to a subset of the whole? -
Django follow feature with m2m
I tried to solve the problem and got stuck. The problem is that I have a post that I can follow. My problem is that I don't know how to add a tracking button. Should this be done by url, with a view? Or should it be rather as a method in the model? My problem is also whether it is properly written in terms of models - using the intermediate model Follower? Here is Post model and I would like to add followers here. I mean, everybody who is interested, can follow this post. class Post(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1024) followers = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Follower', blank=True) is_visible = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', kwargs={'pk': self.pk}) def number_of_followers(self): return self.followers.count() Here is my manager for follower model: class FollowerManager(models.Manager): use_for_related_fields = True def follow(self, user, pk): post_object = get_object_or_404(Post, pk=pk) if user.is_authenticated(): if user in post_object.followers.all(): Follower.objects.filter(post=post_object, user=user).delete() else: Follower.objects.create(post=post_object, user=user) Here is Follower model: class Follower(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = FollowerManager() -
Lookup field in DRF make it case insensitive
I currently have something like this class GetUsernameUnique_RetrieveAPIView(RetrieveAPIView): queryset = modelEmployer.objects.all() lookup_field = 'user__username' serializer_class = Serializer_ListEmployer permission_classes = (permissions.AllowAny,) However it seems the username in lookup field is case sensitive. Any idea how I can make it case insensitive. -
Django user edit profile How to update info without creating another user?
If I use u_form.save(), I suppose there will be a new user data recorded into database. What if I just want to update info but keep the same user? Here's part of my codes: @login_required def profile(request): Exist_Emails = User.objects.filter(is_active=True).values_list('email', flat=True) Exist_Usernames = User.objects.filter(is_active=True).values_list('username', flat=True) current_user = User.objects.get(username=request.user.username) if request.method == 'POST': update_username = request.POST.get('username') update_email = request.POST.get('email') if update_username != current_user.username and update_email == current_user.email and update_username not in Exist_Usernames: u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid(): User.objects.filter(email=current_user.eamil).update(username=update_username) messages.success(request, f'Your account has been updated!') return redirect('/users/profile/') #.Other elif cases... else: u_form = UserUpdateForm(instance=current_user) Here I only show one of the case: the user changes the username, but keep the same email, and the new username should have existed in the database yet. But when I go to my profile page and change only the username, press the submit button, there's no change at all! And I also checked admin user page, there's no change either. I am so confused. if any of my code is wrong please help, thank you! -
Djongo always connects to localhost mongodb
I have followed the guide of db connection config: https://nesdis.github.io/djongo/database-configuration/ However, it always connects to localhost one, not my setting's one. Does anyone have any idea on this issue? my packages versions: Django 2.0 django-cors-headers 2.4.0 django-rest-auth 0.9.3 djangorestframework 3.9.0 djongo 1.1 mongoengine 0.16.3 pip 10.0.1 pymongo 3.7.2 urllib3 1.24.1 -
Django: make field from Model B depend on field from Model A
I've got some Keys (Model B) in my Project and those Keys have a Category (Model A) and each key can be active or inactive, but now I am also trying to add a enable/disable to my categories, so that when I disable my category ALL my keys should set their active field to False. Here's my code example: Model A The Key Category class KeyCategory(models.Model): program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE) name = models.CharField(u'Name', max_length=100) events = models.ManyToManyField('Event', through='EventQuota') enabled = models.BooleanField(verbose_name=u"Category enabled", default=True) Model B The Key class Key(models.Model): created = models.DateTimeField('Created', auto_now_add=True) code = models.CharField('Code', max_length=20) description = models.TextField('Description',blank=True, null=True) program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE) is_active = models.BooleanField('Active?', default=True) last_used = models.DateTimeField('Last used', blank=True, null=True) used_by = models.ManyToManyField('Participant', verbose_name='Participant') quota = models.PositiveIntegerField('Quota', default=1) quota_mode = models.CharField('Quota Mode', max_length=20, choices=QUOTA_MODES, default=QUOTA_MODE_PARTICIPANT) category = models.ForeignKey(KeyCategory, verbose_name='Category', on_delete=models.CASCADE, related_name='keys') In my Key Model I have the is_active field, is it possible to make it depend on the enabled field from the Key Category Model? I mean directly in the model? Or would I have to write a function that basically loops through all keys when I set my category enabled to False / True and then set their is_active field to … -
how to test django 400 bad request error for custom error page?
How to test my custom error page for error 400 bad request in django views.py class Custom400View(TemplateView): template_name = "400.html" urls.py handler400 = Custom400View.as_view() -
Open a link in new tab and trigger postback in the current tab
I want to dislay a link button that, when clicked, triggers postback in the current tab and opens a link in new tab. If it matters, the backend is Python Django. -
docker setup postgis error missing repository
setting up django with docker, the docker file looks like this FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code RUN apt-get update RUN apt-get install software-properties-common --yes RUN add-apt-repository ppa:ubuntugis/ubuntugis-unstable RUN apt-get update RUN apt-get install postgis WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt among other things it sets up postgis using the ppa ubuntugis however it throws this error while setting up Step 5/11 : RUN apt-get install software-properties-common --yes ---> Using cache ---> 634a13159403 Step 6/11 : RUN add-apt-repository ppa:ubuntugis/ubuntugis-unstable ---> Using cache ---> 983fbcf8fd46 Step 7/11 : RUN apt-get update ---> Running in aaf66c98507c Ign:1 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco InRelease Hit:2 http://security.debian.org/debian-security stretch/updates InRelease Ign:3 http://deb.debian.org/debian stretch InRelease Ign:4 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco Release Hit:5 http://deb.debian.org/debian stretch-updates InRelease Hit:6 http://deb.debian.org/debian stretch Release Ign:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Ign:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Ign:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Ign:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Ign:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Err:7 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main amd64 Packages 404 Not Found Ign:8 http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco/main all Packages Reading package lists... W: The repository 'http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu disco Release' does not have a … -
LDAP authentication isnt happening over django rest API
I am authenticating users who login against through django REST framework against NIS using pythonPAM . But when I make the changes to settings.py as mentioned below, user credentials isnt being verified against LDAP. AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', ) This along with ldap credentials for binding is used. Note: I can connect to LDAP server and get all teh details. Its only a problem with django restframework. I also trued AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend',] and it did not work. currently in my urls.py, I call url(/login,) endpoint and authenticate against NIS server. How do I change it to LDAP? I am new to django adn need help on this. -
Connecting to an external MongoDB with populated data via Django
I've got access to a giant MongoDB database with data that was collected by some hardware. It's currently on a remote server. I need to develop with it using Django (preferably). I can iterate with it fine using the straight up pymongo, but I'd like to do it more using Django's built in features. I absolutely love's Django way of handling the data as opposed to running mongodb queries. So I installed Djongo - the connector for Django. With Pymongo I just use it like this client = MongoClient('ipaddress', username='ronald', password='password', authSource='scanning', authMechanism='SCRAM-SHA-1') db = client["scanning"] collection = db["some_collection"] This works fine and I can connect to the collection without any issues. So moving along to Djongo, I assume I would be able to connect to it similarly, however, I keep on getting timeouts. This is my database settings in Settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': False, 'NAME': 'some_collection', 'HOST': 'ipaddress', 'PORT': 27017, 'USER': 'ronald', 'PASSWORD': 'password', 'AUTH_SOURCE': 'scanning', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } This keeps on timing out on starting the server. Is it even possible to do this? Would I be better off dumping the DB locally and storing it in a clean MongoDB optimised for … -
Count consecutive rows with same value for a column in a database using django?
My App consists of a notification module. If the notifications are consecutively arrived from a same user, I would like to show "n notifications from john doe". eg: The database rows are as: id | user | notif | ------------------------------------ 1 john doe liked your pic 2 john doe commented on your pic 3 james liked your pic 4 james commented on your pic 5 john doe pinged you 6 john doe showed interest 7 john doe is busy The above notifications are to be shown as: 2 notifications from john doe 2 notification from james 3 notofications from john doe How would I count these consecutive rows with same value in a column using django orm? Notification.objects.all().values('user', 'notif_count').group_consecutive_by('user').as(notif_count=Sum()) Something like that. Please help. -
How to run behave in django project
i have a feature app in my django project. and some feature files in it like feature/some.feature feature/environment.py feature/steps/some.py And my environment file contains environment.py class FeatureContext(object): """ Used to pass along data between test steps """ def __init__(self): self.scenario_context = {} # Data Specific to a scenario self.http_response = None def before_feature(context, feature): context.response = FeatureContext() def after_feature(context, feature): context.response = None when i run behave i am getting some errors django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured.<br> You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.