Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error after posting new data to the web server
It all looks good by when i try to add some post to my topic I have an error created_by=user : Here is my forms.py from django import forms from .models import Topic class NewTopicForm(forms.ModelForm): message = forms.CharField( widget=forms.Textarea( attrs={'rows': 5, 'placeholder': 'What is on your mind?'} ), max_length=40000, help_text='The max length of the text is 4000.') class Meta: model = Topic fields = ['subject', 'message'] and my view function for this form: def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) user = User.objects.first() if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.board = board topic.starter = user topic.save() post = Post.objects.create( message=form.cleaned_data.get('message'), topic=topic, created_by=user ) return redirect('board_topics', pk=board.pk) else: form = NewTopicForm() return render(request, 'new_topic.html', {'board': board, 'form': form}) -
Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(5, 5, 1, 32), dtype=float32) is not an element of this graph
I made a predictive audio using python tensorflow, when the first upload file was successful but if I repeat it again an error message like this appears Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(5, 5, 1, 32), dtype=float32) is not an element of this graph. whether it contains cookies? def creatematrix(request): if request.method == 'POST': myfile = request.FILES['sound'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) # load json and create model json_file = open('TrainedModels/model_CNN.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("TrainedModels/model_CNN.h5") print("Model restored from disk") sound_file_paths = myfile.name # "22347-3-3-0.wav" parent_dir = 'learning/static/media/' sound_names = ["air conditioner","car horn","children playing","dog bark","drilling","engine idling","gun shot","jackhammer","siren","street music"] predict_file = parent_dir + sound_file_paths predict_x = extract_feature_array(predict_file) test_x_cnn = predict_x.reshape(predict_x.shape[0], 20, 41, 1).astype('float32') loaded_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # generate prediction, passing in just a single row of features predictions = loaded_model.predict(test_x_cnn) # get the indices of the top 2 predictions, invert into descending order ind = np.argpartition(predictions[0], -2)[-9:] ind[np.argsort(predictions[0][ind])] ind = ind[::-1] a = sound_names[ind[0]], 100 * round(predictions[0,ind[0]],3) b = sound_names[ind[1]], 100 * round(predictions[0,ind[1]],3) c = sound_names[ind[2]], 100 * round(predictions[0,ind[2]],3) d = sound_names[ind[3]], 100 * round(predictions[0,ind[3]],3) e = sound_names[ind[4]], 100 * round(predictions[0,ind[4]],3) f = … -
Static and Media Files in Django 1.10
I have a ImageField in my user_accounts/models.py file which i use to store the profile picture of users.It has a upload_to field which calls a function and uploads the file to a media folder in myproj/media/.. . The Image Field also has a default field which is used to set the default profile image from the static folder. This is an entry of User Table in development server. In The image the avatar field shows static url but when clicked it /media/ gets attached to the url before /static/ as follows: In The image the url bar shows /media/ attached before the static url.When i manually remove the /media/ from the url the defaultProfileImage is shown. This is my project structure |-myproj |-myproj |-__init__.py |-settings.py |-urls.py |-wsgi.py |-static |-user_accounts |-images |-defaultrofileImage.png |-user_accounts |-__init__.py |-models.py |-admin.py |-tests.py |-views.py |-urls.py Models.py File from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser def get_upload_url(instance , filename): return 'userProfileImages/%s/%s'%(instance.username , filename) class User(AbstractUser): mobileNumber = models.IntegerField(blank = True , null = True) avatar = models.ImageField(upload_to = get_upload_url , default = '/static/user_accounts/images/defaultProfileImage.png') def __str__(self): return self.username I have the following lines added in my settings.py file AUTH_USER_MODEL = 'user_accounts.User' STATIC_URL = '/static/' … -
Django - Not able to set view using a front end folder which is outside app folder structure
I am new to Django , i have learnt most the basics in framework in past one month .I have deployed my application from local to an online server .The REST APIs are working fine but now I am not able to access my front end code on that server because Django is on the server's root . There is sepration of concerns between server and front end code so I had developed my UI by not worrying about directory structure as per Django ( for example static file confiuration etc. ) Now I want to use Django on local server's root and access my /front-end/html/index.html as home page . Please see all code and directory strcture as follows with error : I am always getting following error : TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.0 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Users\didi\Envs\wantedly_virtual_env\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\didi\Envs\wantedly_virtual_env\Scripts\python.exe Python Version: 3.6.3 My urls.py file is as follows : urlpatterns = [ path('admin/', admin.site.urls), url(r"^$", TemplateView.as_view(template_name='index.html')), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), url(r'^rest-auth/login/', include('rest_auth.registration.urls')), url(r'^refresh-token/', refresh_jwt_token), url(r'^user/$', DetailsView.as_view(), name='rest_user_details'), url(r'^', include('api.urls')), url(r'^api/v1/skills/$', wantedly_app_views.skill_collection), url(r'^api/v1/skills/(?P<pk>[0-9]+)$', wantedly_app_views.skill_element), url(r'^api/v1/user/skills/(?P<pk>[0-9]+)$', wantedly_app_views.user_skill_collection), url(r'^api/v1/user/skill/upvotes/(?P<pk>[0-9]+)$', wantedly_app_views.user_skill_upvotes), ] My settings.py contains … -
django - how to retrieve data from database?
I really don't understand the documentation on retrieving data from database, this is what I've tried account_from_validation = AwaitingValidation.objects.filter(av_hash = acchash) test = account_from_validation['email'] But I get "No exception message supplied" This is acchash: path('confirm-email/<str:acchash>/', views.ConfirmEmail), I store a random hash in database which if accessed from the confirm-email link will confirm the email and register the account. But I don't know how to retrieve that information from database. -
Django using one time call function output as global value
While initializing the project, i want to call login function from projects settings for once and use the output token anywhere in project. I want to use same token whether I call again to check if token changed. def login(creds): r = requests.post(base_url + '/api/admin/login', json=creds, headers=headers, verify=False) if r.status_code == 200: token = r.json()['token'] return token If i call function in project settings, function starts each time. I don't want to dump token to a file and read each time. Any other way? Thanks. -
Django2,Page not found,but it exits
enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here I really do not know where the problem, the first page can be displayed, click on the link to die, watch the video tutorial, but the teacher can, which can help out to see where the problem lies? -
Need help for creating new record if its a new year in django
I am new to python. I really like Django. I wanted to create an application for an NGO to keep track of kids. We will have kid details given by NGO. We will create a form that takes the health details of the kid. If they try to fill the form with in this year, the same data should get update. If it another year then it needs to create a new data of that year. I have tried my level best. The form only updates but doesn't create a new one. Any help would be great. I am trying to show the details of the kid and prefill the form if data exists. Posting my code. Here is the model. class StudentsProfileInfo(models.Model): SCHOOL_UID = models.ForeignKey(SchoolUID) CHILD_NAME= models.CharField(max_length=245) CHILD_UID = models.CharField(max_length=245) SEX = models.CharField(max_length=245) DOB = models.DateField(max_length=245) AGE = models.IntegerField() FATHERS_NAME = models.CharField(max_length=245) FATHERS_EMAIL = models.EmailField(max_length=245) FATHERS_NUMBER = models.IntegerField() MOTHERS_NAME = models.CharField(max_length=245) MOTHERS_EMAIL = models.EmailField(max_length=245) MOTHER_NUMBER = models.IntegerField() ADDRESS = models.CharField(max_length=245) CITY = models.CharField(max_length=245) SECTION_AND_CLASS = models.CharField(max_length=245) TEACHERS_NAME = models.CharField(max_length=245) TEACHERS_EMAIL =models.EmailField(max_length=245) def __str__(self): return self.CHILD_NAME class Anthropometry(models.Model): KID_DETAILS = models.CharField(max_length=245) HEIGHT = models.IntegerField() WEIGHT = models.IntegerField() BMI= models.CharField(max_length=245) HEAD_CIRCUMFERENCE = models.IntegerField() MID_UPPER_ARM_CIRCUMFERENCE = models.IntegerField() TRICEP_SKIN_FOLDNESS= models.IntegerField() BSA = models.CharField(max_length=245) … -
How can I get the `content_type` in the Model `save` method?
I have the field: image = models.ImageField(upload_to=file_upload_to) How can I get the content_type and just 'filename' in the Model save method ? I know I can get it in the form, but the situation is more complex(custom formset for user, need to change also in admin, plus some celery task) and is better if I can get it on the model. -
How do i implement sorting and filtering in django?
I'm pretty new to django and i am working on a project where i need to let users sort or filter listed results by brand or manufacturer and sort using prices(highest to lowest or vice versa).How should i approach this problem? -
Recover GET parameter from PasswordResetConfirmView
I'm trying to recover a GET parameter from the django template view django.contrib.auth.PasswordResetConfirmView. Basically when a user click on his password reset link (like http://127.0.0.1:8000/commons/reset/MQ/4t8-210d1909d621e8b4c68e/?origin_page=/mypage/) I want to be able to retrieve the origin_page=/mypage/ argument. So far my url.py looks like this: from django.urls import path from . import views app_name = 'commons' urlpatterns = [ path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] And my views.py like this: from django.contrib.auth import views as auth_views class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): template_name = 'commons/password_reset_confirm.html' success_url = '/commons/reset/done/' def get(self, request, *args, **kwargs): self.extra_context = { 'origin_page': self.request.GET['origin_page'] } return super().get(request, *args, **kwargs) As you can see I'm trying to get my origin_page with 'origin_page': self.request.GET['origin_page'] but it doesn't work. It throws me a MultiValueDictKeyError. I even used the debugger to inspect every objects from the class/method but none of them seems to contains my origin_page variable. Any idea? Thanks -
How to introduce non-model, write-only field to a modelserializer
I have the following ModelSerializer: class MaintProtoSerializer(serializers.ModelSerializer): class Meta: model = MaintenanceProtocol fields= ('warranty_card_number', 'warranty_id', 'machine_id', 'inner_body_id', 'outter_body_id', 'warranty', 'date', 'seller', 'inner_cleanup', 'outter_cleanup', 'turbine_cleanup', 'filter_condition', 'pressure', 'outer_air_temp', 'inlet_air_temp', 'other_problems', 'propuski', 'client_notes', 'electricity') and its model: class MaintenanceProtocol(models.Model): warranty_card_number = models.CharField(max_length=100) warranty_id = models.CharField(max_length=100) machine_id = models.CharField(max_length=100) inner_body_id = models.CharField(max_length=100) outter_body_id = models.CharField(max_length=100) warranty = models.BooleanField() date = models.DateField() seller = models.CharField(max_length=100) inner_cleanup = models.BooleanField() outter_cleanup = models.BooleanField() turbine_cleanup = models.BooleanField() filter_condition = models.TextField() pressure = models.IntegerField() outer_air_temp = models.IntegerField() inlet_air_temp = models.IntegerField() other_problems = models.TextField() electricity = models.IntegerField() propuski = models.TextField() client_notes = models.TextField() It's deserializing an object based on the following json passed to it: { "warranty_card_number": "profi-1234", "warranty_id": "fji-0938", "machine_id": "fuji", "inner_body_id": "outter-2349", "outter_body_id": "inner-2349", "warranty": "yes", "date": "2017-12-20", "seller": "maga`zin", "inner_cleanup": "no", "outter_cleanup": "yes", "turbine_cleanup": "yes", "filter_condition": "so-so", "pressure": "4", "outer_air_temp": "5", "inlet_air_temp": "23", "electricity": "45", "propuski": "some", "other_problems": "none", "client_notes": "n/a", "sigb64": "alkjhsdfpas8df,a;lsejf,p0394" } So the sigb64 field is not really part of the model (and it mustn't be persisted to the database), however I'd like to access it from the created model by the serializer. What's the correct way to achieve that? -
Access data from other model in a ListView
Good morning, how can I access data from another model in my ListView ? Right now I have a model called Project and I I am using ListView in order to render a a list of all current projects. My Project is linked to another models call Team that has multiple Members and each members has an attribute called Response_set. I would like that in my HTML template if Response_set is not empty for each member put a Green Mark else put a red mark. The thing is I do not know and do not find the answer on how to loop through my list within the view; class HRIndex(generic.ListView): #import pdb; pdb.set_trace() template_name = "HR_index.html" model = Project ordering = ['-created_at'] def get_context_data(self, **kwargs): import pdb; pdb.set_trace() context = super(HRIndex,self).get_context_data(**kwargs) status_dict = {} for project in object_list: proj_team_id = project.team_id proj_memb = proj_team_id.members.all() open_close = 1 for memb in proj_memb: if not list(memb.response_set.all()): status = False else: status = True open_close = open_close*status status_dict.update({project.id:open_close}) context['status_dict'] = status_dict return context I tried using object_list like in the template but it not working How can I loop through my list in my view ? Thx you -
Why Django DecimalField let me store Float or string?
I don't understand the behaviour of Django DecimalField. It's defined as: A fixed-precision decimal number, represented in Python by a Decimal instance. However, with the following model: class Article(models.Model) unit_price = DecimalField(max_digits=9, decimal_places=2) I can create an article in at least 3 ways: article = Article.objects.create(unit_price="2.3") type(article.unit_price) >>> str article = Article.objects.create(unit_price=2.3) type(article.unit_price) >>> float article = Article.objects.create(unit_price=Decimal('2.3')) type(article.unit_price) >>> decimal.Decimal Why Django DecimalField is able to return something else than Decimal type? What would be the best way to ensure my app never deals with floats for prices? Thanks. -
Django not running after restarting AWS AMI Elastic Beanstalk
I was recently fixing an Apache issue on an AWS AMI Elastic Beanstalk instance, I created an image and hence it restarted. After restarting, the application is not working. Do I have to run any command after restarting? -
fatal: destination path '.' already exists and is not an empty directory
I'm getting this error when I try to git clone my Bitbucket repo from my remote Digital Ocean server. The server directory I'm trying to clone the repo into is not empty, as I'm setting up my Django project in it (env, static, manage.py etc are all in there). So how do I clone the repo into this directory that is not empty? I've already tried a reccommended answer which said use git fetch and git checkout -t origin/master -f - and that didn't work - I got this error: fatal: A branch named 'master' already exists Any suggestions what I can do? -
"mkvirtualenv command not found" within vagrantbox
I am trying to set up a django project using vagrant, but I am getting this error: Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-112-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage Get cloud support with Ubuntu Advantage Cloud Guest: http://www.ubuntu.com/business/services/cloud 0 packages can be updated. 0 updates are security updates. Last login: Sun Jan 28 08:21:28 2018 from 10.0.2.2 vagrant@ubuntu-xenial:~$ mkvirtualenv profiles_api --python=python3 mkvirtualenv: command not found In my vagrant file I have the following : sudo pip install virtualenvwrapper if ! grep -q VIRTUALENV_ALREADY_ADDED /home/ubuntu/.bashrc; then echo "# VIRTUALENV_ALREADY_ADDED" >> /home/ubuntu/.bashrc echo "WORKON_HOME=~/.virtualenvs" >> /home/ubuntu/.bashrc echo "PROJECT_HOME=/vagrant" >> /home/ubuntu/.bashrc echo "source /usr/local/bin/virtualenvwrapper.sh" >> /home/ubuntu/.bashrc fi I have python 3.6,3.5 and anaconda installed, if that matters. Thank you for the help -
Django site move to another sever
I have copied one django site source code and move it to another server, then did the following steps on new server: Install python 2.7.9 Install Django 1.8.6 Set the environment variable make a website in IIS and create fast CGI handler and mappings. But when running the site it showed the following error any help: Error occurred while reading WSGI handler: Traceback (most recent call last): File "E:\websitecode\wfastcgi.py", line 711, in main env, handler = read_wsgi_handler(response.physical_path) File "E:\websitecode\wfastcgi.py", line 568, in read_wsgi_handler return env, get_wsgi_handler(handler_name) File "E:\websitecode\wfastcgi.py", line 551, in get_wsgi_handler raise ValueError('"%s" could not be imported' % handler_name) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported StdOut: StdErr: -
django socket with react-native
We have a django backend with Django Rest Framework for our api, and our frontend is built with React Native (android). What is the best way to go about creating a socket between two users? We would like to implement chat/video and allow users to send data like current geolocation to each other. Also, is it possible to create a socket between the server and frontend to listen for DB updates (instead of sending requests from the front end to the api at set intervals) ? -
submit new record to db give me invalid literal for int
guys im working on django-rest-framwork . now im creating some new record to db at( store_product ) table when im submitting new data when i press POST button i get this error why i get this error ? !! ValueError at /store/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://localhost:8000/store/ Django Version: 2.0.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 947 Python Executable: /home/mohammadreza/www/html/academy/uenv/bin/python3 Python Version: 3.6.4 Python Path: ['/home/mohammadreza/www/html/academy/api/academy', '/home/mohammadreza/www/html/academy/uenv/lib/python36.zip', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages'] Server time: Sun, 28 Jan 2018 11:54:13 +0330 INFO here is my serializer.py file from rest_framework import serializers from .models import Product class StoreSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'filepath', 'created_date', 'updated_date', ] read_only_fields = ['product_id', 'created_date', 'updated_date','author'] def validate_title(self,value): qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value and here is my view.py file from rest_framework import generics from .serializers import StoreSerializer from .models import Product class StoreCreateApiView(generics.CreateAPIView): lookup_field = 'pk' serializer_class = StoreSerializer def get_queryset(self): return Product.objects.all() def perform_create(self, serializer): serializer.save(author = self.request.user) and it is my model for this … -
Python 3 - Django 1.9 One Create Request Causing Multiple Creation Attempts?
I was adding a successful or unsuccessful message to when a post is created on a learn to make a blog project when I started getting that post creations were both successful and unsuccessful at the same time: The contents of the message are defined using if/else statements and the only thing I can think might be happening is when I click submit on my post creation form it is being submitted multiple times causing an initial successful attempt and then two unsuccessful attempts but I don't see a reason for this to be happening in views.py, post_form.html, or post_detail.html files. Does anyone have a clue on how to fix this? views.py: from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from .forms import PostForm from .models import Post def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "Not Successfully Created") context = { "form": form, } return render(request, "post_form.html", context) post_form.html: <!--DOCTYPE html --> <html> <head> <title></title> </head> <body> <h1>Form</h1> <form method="POST", action="">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Create Post"/> </body> </html> post_detail.html: <!--DOCTYPE html --> <html> <head> <title></title> </head> {% … -
No login and redirection with Python Social Auth, mobile Chrome (PWA or normal)
I have a problem with login and redirection using python-social-auth. The documentation says I can do using next in link: <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login with Facebook</a> It works okay for Firefox and Chrome on desktops. However on mobile phones I have different behavior. Mobile Firefox is working without problems. On mobile Chrome (PWA mode or normal mode) I cannot login and I am redirected to /accounts/login page without any errors. social-auth-core 1.6.0 social-auth-app-django 2.1.0 Any ideas are welcome. -
Why is my try catch solution not working as I expect it
I am trying to validate a form in a django project and part of the validation is to check if a project exists. The Environment: python 3.6.3 django 1.10.8 python-keystoneclient 3.14.0 I have this check currently def clean_projectname(self): submitted_data = self.cleaned_data['projectname'] newproj = "PROJ-FOO" + submitted_data.upper() keystone = osauth.connect() try: project = keystone.projects.find(name=newproj) raise forms.ValidationError('The project name is already taken') except NotFound: return submitted_data The try section will return either a project object or it will have a 404 not found Exception. I have tried to except on the NotFound but Django gives me an error name 'NotFound' is not defined I would appreciate help with this. -
NoReverseMatch at / django python:Reverse for '*' not found. tried
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['details/(?P[.\-\w]+)$'] I am getting this error when I open the home page. All other pages seem to work. urls.py app_name = 'main' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'ask-question/$', views.question, name='ask-question'), url(r'^details/(?P<slug>[.\-\w]+)$', views.details, name='details'), ] views.py for the home page def home(request): questions = Question.objects.all().order_by("-date") numbers = Question.objects.all().count() numbers2 = Answer.objects.all().count() total_users = User.objects.all().count() # counting answers on specific questions results = Question.objects.annotate(num_answers=Count('answer')).order_by("-date") # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(results,10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) # end of counting empty = [] for a in Answer.objects.all(): idd = a.id question_id = (a.question_id) empty.append(str(question_id)) repeatition = Counter(empty) # i = 0 # trend_list = [] # for x in range(len(repeatition)): # new = repeatition.most_common()[i][0] # trend_list.append(new) # i += 1 # if len(trend_list) != 0: # trend = Question.objects.get(id=trend_list[0]) # else: # trend = 'No Trending Category' # getting the answers to all questions in the front page # search the questions ============ query= request.GET.get("q") if query: short_list = Question.objects.all() questions = short_list.filter(title__icontains=query) resulted = questions.annotate(num_answers=Count('answer')) counted = questions.count() context1 = { 'questions': questions, 'query': query, 'counted': counted, … -
Mock gives "raise except" error
I am trying to unit test my program. I have a side effect in my mock object from models import MyObject mock_obj.objects.get.side_effect = mock.Mock(side_effect=MyObject.DoesNotExist) The test works and passes when I have this in the function that I am testing: import models try: obj = models.MyObject.objects.get(id=1) except Exception: return True However when I change this to: import models try: obj = models.MyObject.objects.get(id=1) except models.MyObject.DoesNotExist: return True It gives me this instead of returning True: > Traceback (most recent call last): > File "/home/test/test_my_function.py", line 40, in test_get_job_not_exist > response = my_function.my_function(request_mock, 1) > File "/home/handlers/my_function.py", line 35, in get_job_with_id > obj = MyObject.objects.get(id=id) > File "/local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__ > return _mock_self._mock_call(*args, **kwargs) > File "/local/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call > raise effect > DoesNotExist Why is this happening? MyObject is a Django model object