Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: add ForeignKey limit_choices_to associate another or same Model instance
This is my code. std_name = models.ForeignKey( StudentInfo, on_delete=models.CASCADE) def get_std_class_name(self): return int(self.std_name.std_subject_class.std_class_name_N) def limit_subject_std_choices(): return {'std_subject_class__std_class_name_N':'get_std_class_name' } subject_name = models.ForeignKey(StdSubject,on_delete=models.CASCADE, limit_choices_to=limit_subject_std_choices) But shows error. ValueError at /admin/results/studentinfo/1/change/ invalid literal for int() with base 10: 'get_std_class_name' I dont know what is issue with my code. I wanna when any student put her marks any subject while subject will be showed base her class name. Just I wanna get student class info from this model instance and pass a value within this function. def limit_subject_std_choices(): return {'std_subject_class__std_class_name_N':'get_std_class_name'} -
Django Paypal IPN doesn't trigger any signal in live mode, yet works in sandbox
I have successfully integrated django-paypal in sandbox mode, along with Django debug settings. My payments are done, and the signals attached to valid_ipn_received are triggered. When I move to the PayPal live mode, payments are also received, but I don't receive any signal anymore. Here is the code that normally triggers PayPal IPN: class StoreItemView(SomeUserCheckMixin, SomeAjaxMixin, View): # …some business logic… paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'item_name': 'my item', 'amount': '20', 'discount_amount': '10', 'currency_code': 'USD', 'invoice': generate_uuid_as_string(), 'payment_date': timezone.now().strftime('%H:%M:%S %b %d, %Y') + ' CET', 'lc': 'FR', 'bn': 'SomeCompany_BuyNow_WPS_FR', 'email': request.user.email, 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'address1': request.user.profile.adress.street, 'address2': request.user.profile.adress.extension, 'zip': request.user.profile.adress.zip, 'city': request.user.profile.adress.city, 'country': 'FR', 'night_phone_a': '33', 'night_phone_b': request.user.profile.phone_number, 'notify_url': notify_url, 'return': return_url, 'cancel_return': cancel_return_url, 'custom': request.user.username + _separateur + str(cible), } return render(request, self.template_name, { 'form': PayPalPaymentsForm(initial = paypal_dict) }) # After my functions to hook to the Following signals valid_ipn_received.connect(store_check_transaction) invalid_ipn_received.connect(store_alert_bad_transaction) My config settings are set so that ADMINS contains mails to alert if any error occurs, some logging messages shall appear in my custom logger (and I know it works for other operations on my website) and my PayPal settings are set like that: # In debug mode: ALLOWED_HOSTS = ['localhost', '.paypal.com', 'paypal.com.'] PAYPAL_TEST = True PAYPAL_RECEIVER_EMAIL … -
Object is not iterable Django
I've model called Order. The problem appears when I attempt to initial with a queryset. I get 'Order' object is not iterable, i think cause of get_queryset called twice views.py class ChechoutViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = serializers.OrderSerializer queryset = None # this line is probably not required, but some code checking tools like it to be defined. def get_queryset(self): cart_obj, cart_created = Cart.objects.get_or_create(user_profile=self.request.user) billing_obj, billing_created = BillingProfile.objects.get_or_create(user_profile=self.request.user) if billing_obj is not None: self.queryset = models.Order.objects.new_or_get(billing_obj=billing_obj, cart_obj=cart_obj) return self.queryset models.py class OrderManager(models.Manager): def new_or_get(self, billing_obj, cart_obj): qs = Order.objects.filter(billing_profile=billing_obj, cart=cart_obj, active=True) if qs.exists(): obj = qs else: obj = Order.objects.create(billing_profile=billing_obj, cart=cart_obj) return obj -
how to display my M2M model in Django Rest Framework
I'm trying to display a 'nested' model in my API response and having trouble shaping the data. I have the model the API is called from: something like class Rules: conditions = models.ManyToManyField(RulesPoliciesConditions) ... ... class RulesPoliciesConditions: rules = models.ForeignKey(Rules, ...) policies = models.ForeignKey(PolicyStatus, ...) Rules and Policies are their own models with a few TextFields (name, nickname, timestamp, etc) My problem is that when I use the Rules model to call a field called conditions, only the rules and policies PK display. I want to reach the other attributes like name, timestamp, nickname, etc. I tried making my fields (in my Serializer) try to call specifically like "conditions__rules__name" but it's invalid, I also tried "conditions.rules.name" which is also invalid. Maybe I'm using the wrong field in my serializer, I'm trying out conditions = serializers.SlugRelatedField(many=True, queryset=q, slug_field="id") My intention is to display something like: conditions: [ { rules: {id: rulesId, name: rulesName, ...}, policies: {id: policiesId, name: policiesName, ...} }, ... ] or just even: conditions: [ { rules: rulesName, policies: policiesName }, ... ] since right now it just returns the rulesId and policiesId and it doesn't "know" about the other fields -
Combine wav files using pydub in Django and save output to model FileField
I have .wav audio files stored in my Django database using a custom AudioInfo model that has the following parameters: 1) "text" (a string which represents the corresponding audio file content), e.g. "howdy" 2) "audio" (the corresponding .wav audio file), e.g. "howdy.wav" 3) "duration (the duration of the audio file), e.g. "0.7333" models.py class AudioInfoManager(models.Manager): def get_by_text(self, text): qs = self.get_queryset().filter(text=text) if len(qs) == 0: return None return qs[0] def create_problem_audio(self, text, audio, duration): problem_audio = self.create(text=text, audio=audio, duration=duration) return problem_audio class AudioInfo(models.Model): text = models.TextField(unique=True) audio = models.FileField(upload_to=upload_audio_info_path) duration = models.FloatField() objects = AudioInfoManager() In my views.py I want to retrieve two audio files (e.g. "howdy.wav" and "partner.wav") from my AudioInfo model, combine the files into one "howdy_partner.wav" file, and pass it as a parameter to the "create_problem_audio" AudioInfoManager method to create and save a new AudioInfo instance to the database. Note that I don't want to export the new "howdy_partner.wav" file anywhere but to the database. Right now this is my attempt using the pydub package: views.py from .models import AudioInfo from pydub import AudioSegment from django.core.files.base import ContentFile howdy_audio_info = AudioInfo.objects.get_by_text('howdy') howdy_audio = howdy_audio_info.audio # .wav audio file that says "howdy" partner_audio_info = AudioInfo.objects.get_by_text('partner') partner_audio = partner_audio_info.audio … -
How to properly match an API to Views in Django
My question boils down to one of best practice for REST and Views in Django. I am reworking the REST api for my current project, and that includes reworking our Views (Controller in traditional MVC) somewhat. Currently, everything is tunneled through POST requests, even things that should be a simple GET. From a rest perspective, a list of all jobs should be returned with a URL like: api/jobs/ and a single job (with ID 1) should be retrieved with: api/jobs/1 and finally this should return all tasks that are part of job 1 api/jobs/1/tasks/ This is the philosophy I'm using for the new system, but I'm torn on the implementation. Should both of these get their own View in Django, or should one view handle both. Currently I am using one View, where all relevant urls route to it, with logic like this; def get(self, request, id=None, task_id=None): if id is None: return Job.objects.all() # This will be the LIST' if task_id is not None: return Job.objects.get(id=id).task_set.all() return Job.objects.get(id=id) This seems like it could lead to very complex and verbose views if more complexity is added. If I wanted to add similar logic to the task logic for some other … -
Javascript to reset a section of a Django form field?
I'm trying to use a tiny piece of javascript: $("#btn_clear").click(function(){ $("#two")[0].reset(); }); to reset a section of a form which i have inside a div. the form has multiple sections (divs), but i only want it to clear the form fields inside a specific div html pseudocode: <form ... <div id="one" ... <div id="two" ... <label for=... {{ form.startdate }} {{ form.startdate.errors }} ... I'm trying to use this button (also in the html) combined with the javascript to clear div id="two": <button class="btn btn-primary" id="btn_clear" style="margin-left: 142px" value="Reset" type="button">Clear Section</button> When i click the button nothing happens and I don't get any errors in the console. Is there something special I need to do to clear a django form field in this manner? -
Django template: Can't pass an int and a string from path to view
Having issues passing values from template to view, the int value is fine but the 2 string values are not. The string values i.3 and i.4 print fine in template, but when passed as url parameters the full url cannot be found. Reverse for 'world' with keyword arguments '{'some_id': 0, 'some_val': '', 'some_val_2': ''}' not found. template: {% for item in my_config %} <tr> {% for i in item %} {{ i.3 }} {{ i.4 }} {{some_id}} <a href="{% url 'hello:world' some_id=some_id some_val=i.3 some_val_2=i.4 %}">hello</a> {% endfor %} </tr>{% endfor %} Getting NoReverseMatch error. Rest of my code: urls.py path(r'^world/<int:some_id>/<some_val>/<some_val_2>/', views.world, name='world'), Any help is much appreciated. -
ModuleNotFoundError: No module named 'pip.download' when trying to install Python package for Django
When trying to install Numpy and other packages using pip. I get a message saying ModuleNotFoundError: No module named 'pip.download'. Anyone know any possible solutions for this? I'm currently running on Python3. I've had a look at similar problems but no solutions seem to work. E.g. "pip install unroll": "python setup.py egg_info" failed with error code 1 pip3 install 'django-numpy==1.0' Collecting django-numpy==1.0 Downloading https://files.pythonhosted.org/packages/a2/15/22ea119379010455ee91c3ee2f76da207fbd342f5277305da3ad660a0a13/django-numpy-1.0.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/pz/d28llk412ss8ptwv5znkhv1m0000gn/T/pip-install-kwd6b6us/django-numpy/setup.py", line 6, in <module> from pip.download import PipSession ModuleNotFoundError: No module named 'pip.download' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/pz/d28llk412ss8ptwv5znkhv1m0000gn/T/pip-install-kwd6b6us/django-numpy/ -
Hello, I get the following error when I tried to run "python manage.py runserver"
The error that I get: from LoginAPI.LoginApp.views import register_view, login_view, logout_view ModuleNotFoundError: No module named 'LoginAPI.LoginApp' My urls.py: from django.conf.urls import url from django.contrib import admin from LoginAPI.LoginApp.views import register_view, login_view, logout_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', register_view, name='register'), url(r'^login/', login_view, name='login'), url(r'^logout/', logout_view, name='logout'), ] Django version: 2.1.1 I am not very experienced in python yet and would love to here your feedback, I have searched for solutions but couldn't seem to find any. Maybe that I missed something small but can't seem to find the problem. -
PAGE NOT FOUND with url in Django Project
I am just learning Django and have hit my first question. In the HTML page itself, I can view the page and see the header I created. However, when I type in the url (http://127.0.0.1:8000/) it will not show. Instead, it says PAGE NOT FOUND. Here is my code. This is the relevant portion of code from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is the code from urls.py: from django.conf.urls import url from django.contrib import admin from .views import home_page urlpatterns = [ url(r'^$/', home_page), url(r'^admin/', admin.site.urls), ] This is the code from views.py: from django.http import HttpResponse from django.shortcuts import render def home_page(request): return render(request, "home_page.html", {}) This is the code from home_page.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>home</title> </head> <body> <h1>Hello World!</h1> </body> </html> The first three files are in a directory within the src folder and the last file is in another directory but still within the src folder. I did notice that I did not have a pycache folder when I started the project for some reason (even though the instructor from the video did have … -
Cannot return from function that uses zmq in python 3 django
I use python 3.6.6 anaconda 64 bit windows, zmq 4.2.5 I have very strange behavior: function can't return. Server: import zmq import json def send_response(**kwargs): try: #... Some kwargs standard preprocessing socket.send_string(json.dumps(kwargs)) except zmq.ZMQBaseError: return False return True def main(): context = zmq.Context() socket = context.socket(zmq.REP) #socket.setsockopt(zmq.RCVTIMEO, 1000) socket.setsockopt(zmq.SNDTIMEO, 1000) socket.bind(my_address) while True: try: msg = socket.recv().decode("utf-8") except zmq.ZMQBaseError: continue #... Processing if not send_response(error='Everything is wrong'): continue #... Processing Client: import zmq import json def do_request(**kwargs): context = zmq.Context() socket = context.socket(zmq.REQ) socket.setsockopt(zmq.RCVTIMEO, 5000) socket.setsockopt(zmq.SNDTIMEO, 1000) socket.connect(my_address) #... kwargs pre-rocessing try: socket.send_string(json.dumps(kwargs)) response = json.loads(socket.recv().decode("utf-8")) #... Processing return response except zmq.ZMQBaseError as e: print(e) print("PING1!!!") return dict(error='Service temporarily unavailable', r_status=503) def called_from_view(): response = do_request(command='ping') print("PING2!!!") It was working. I don't know what has changed. But now it is broken. When server is shut down, client's do_request doesn't return the Service temporarily unavailable. The response = json.loads(socket.recv().decode("utf-8")) throws an exception. In except section python prints the PING1, but it doesn't print PING2 in called_from_view after that. Even with the empty return. I can't figure out why. I create new socket in do_request because the client's called_from_view is called from django's view. I had other problems before with the global … -
Find Django API Bottleneck
I have a Django app deployed on Heroku with a PostgreSQL database on Amazon RDS. The React front end is deployed on Heroku. In production, the API is very slow and I don't understand why. It's a small, simple database. How can I figure out where the bottleneck is? For example, I'm loading a page of 40 items and it takes 30 seconds. Even when I remove the actual query, hitting the endpoint and receiving a response can take 6+ seconds, which seems extreme. This load time is unacceptable in my app, and I don't know where to look to optimize. Could it be RDS, or Heroku? I upgraded to the $25/month Dyno to see if that made a difference but it did not. No one is using my app yet so usage volume should not be a factor. I'm not sure if this makes sense, but I threw some print() functions in my view to watch what section was taking the longest, and it seems like all my queries finish quickly, THEN it takes the 20+ seconds at the end to actually return that information to my React app. Any advice on where to start much appreciated. Note: I … -
Filtering in Django Dynamic REST
How can I filter in django dynamic REST (https://github.com/AltSchool/dynamic-rest) with OR clause? I need to implement queryset like User.objects.filter(Q(username="admin") | Q(first_name="test")) Is it possible to do it via request GET query parameters - something like api/users?filter{username}=admin <OR> filter{first_name}=test? -
Django: adding simple button to admin generic view
Django newbie here working on a pre-existing app I've inherited. I need to add a cancel/back button to the show (DetailView in Django terms, I think?) page. I know how to do this with anchor tags in HTML. However, I can't figure out where the HTML template is for this view! I believe it's being procedurally generated as a "generic view" or "admin" from this code in urls.py: from django.conf.urls import url from . import views app_name = 'reports' urlpatterns = [ # ex: /reports/ url(r'^$', views.IndexView.as_view(), name='index'), # ex: /reports/5/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # ex: /reports/5/results/ url(r'^(?P<pk>[0-9]+)/results$', views.ResultsView.as_view(), name='results'), # ex: /reports/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name='vote'), ] The bottom bar of the reports 'view' page contains the following values when accessed via browser: I'd like to add a "Cancel" button to this bar, but I can't find where I could add such a button -- I can't even find these existing buttons in the codebase. An admin/reports_admin.py exists with some configuration that may be relevant, but I don't see an obvious place in that file where I could add this "Cancel" button. Please help! -
Django adding users to existing Group
I want to make a signup form having groups to save automatically. My forms.py class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) group = forms.ModelChoiceField( queryset=Group.objects.all(), required=True ) class Meta: model = User fields = ('username', 'email', 'group', 'password1', 'password2') and views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('home') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) Is there any way to save group(i.e Group1/Group2) when creating user instance? -
Trouble serving uploaded images on Django
After a user has uploaded an image, she's always returns a 404 error. I think this is a Nginx missconfig but I'm not sure of it and after hours of search and tries I still don't understand the issue. Here's my settings.py : DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Next, my urls.py : urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my Nginx config file : location ^/static/ { autoindex on; alias /home/user/mywebsite/site/static; } location ^/media/ { alias /home/user/mywebsite/site/media; } Here's a image's generated URL : https://www.mywebsite.com/media/CACHE/images/img/venus/758c9f7d70d0c64b5631cc865986de48.jpg (404) I use Django Imagekit for handling uploaded images. I always founded these URLs weird...maybe ImageKit need some more extra configuration ? My static and media directories are in /mainappdjango/static, not on root directory. If I don't do that, my static aren't loaded. The image is well uploaded on the server (I can access it with FTP or SSH). Do you have any idea of the trouble causing these 404 errors ? :/ Thanks a lot! -
SyntaxError: invalid syntax in django project
I'm having issue while configuring views and I am following django 1.11 official tutorial. Here is my Code: from django.conf.urls import url, include from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^$', views.home), url(r'login/$', login, {'template_name': 'accounts/login.html'}), url(r'logout/$', logout, {'template_name': 'accounts/logout.html'}), url(r'register/$' views.register, name='register') ] -
Django: continuing code execution after transaction.atomic's Exception
Probably it's a very stupid question, but the part I am working on is so important, so I'd like to check things twice) Quote from Django documentation about with transaction.atomic(): Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back. My Guess: And the following code will not be executed, because a regular python Exception raised, right? For example: def my_view(request): with transaction.atomic(): # bunch of queries api_call() return JsonResponse('Done') Is there a guarantee that api_call() will not be executed if a database Exception will occur inside transaction.atomic() block? Big thx -
How to format highcharts to skip missing datapoints
I'm working with irregular time-series data in Highcharts. Currently the graph looks like this: Line graph including missing data I want it to look like this: Line graph skipping missing data Is that possible with Highcharts? Here is my Highchart function: Highcharts.chart('container', { chart: { type: 'line' }, title: { text: '2018 Particle Data Channel 1 w/ Date Testing' }, xAxis: { type: 'datetime', labels: { format: '{value:%b-%e}' }, }, series: [{ name: "Channel 1 Count", data: {{ chan1 }}, color: 'red', }] }); And a snippet of the dataset showing the missing data (jumps from 4/18 to 6/23): [["2018-04-18 17:49:00+00:00", 4678], ["2018-04-18 18:04:00+00:00", 6380], ["2018-04-18 18:19:00+00:00", 4676], ["2018-06-23 06:05:00+00:00", 4878], ["2018-06-23 06:20:00+00:00", 16088], ["2018-06-23 06:35:00+00:00", 3466], ["2018-06-23 06:50:00+00:00", 6060], ["2018-06-23 07:05:00+00:00", 4570]] And my Django view which serves the data: def charts_testing(request): particle_data = ParticleData2.objects.values('dtime','chan1count') solo_1 = [] dtime = [] for entry in particle_data: solo_1.append(entry['chan1count']) dtime.append(entry['dtime'].timestamp()*1000) return render(request, 'charting_testing.html', { 'chan1': json.dumps(list(zip(dtime, solo_1))), 'dtime': json.dumps(dtime), }) Thank you in advance! -
'utf-8' codec can't decode byte 0x8a in position 170: invalid start byte
I am trying to do this: fh = request.FILES['csv'] fh = io.StringIO(fh.read().decode()) reader = csv.DictReader(fh, delimiter=";") This is failing always with the error in title and I spent almost 8 hours on this. here is my understanding: I am using python3, so file fh is in bytes. I am encoding it into string and putting it in memory via StringIO. with csv.DictReader() trying to read it as dict into memory. also tried with io.StringIO(fh.read().decode('utf-8')), but same error. what am I missing? :/ -
Logout Django Rest Framework JWT
I want to ask if it's a good idea to logout when I'm using JWT. To log in, I send a post request with username and password to get the desired token (saved into localStorage) which will allow me to send further requests to views that requires the token, of course. But I'm not sure how should I log out the user. I can clear the localStorage, but the token remains available. So, I want to ask if I should use refresh the token since I can not disable it. Thanks in advance -
How to get a current date for upload_to in Django models
Since some image files have name conflicts, I decided to make the system to change a uploaded file's name automatically. However, after changing the system, I got in trouble with getting a current date for the file path. This is how my previous Image model looks like, and it stores an image with a name like boutique/2018/9/20/FILE_NAME.jpg. class Image(TimeStampedModel): ... image = ImageField(..., upload_to='boutique/index/%Y/%m/%d') ... After that, I changed it to like this. This successfully changes a uploaded image's name automatically. However, it stores a name like boutique/%Y/%m/%d/FILE_NAME.jpg. def image_path(instance, filename): basefilename, file_extension = os.path.splitext(filename) chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' randomstr = ''.join((random.choice(chars)) for x in range(10)) return 'boutique/index/%Y/%m/%d/{imageid}/{basename}{randomstring}{ext}'.format(imageid=instance.store.domainKey, basename=basefilename, randomstring=randomstr, ext=file_extension) class Image(TimeStampedModel): ... image = ImageField(..., upload_to=image_path) ... Like you see the above, the problem is that %Y, %m, and %d don't provide date data I need anymore. What is wrong here? image_path function returns the same thing in the same place. I don't know why they are just like recognized as a normal string -
Sharing form logic between Django Rest Framework and UI
My django app has an entity Campaign. For my UI, I've implemented CampaignForm which has logic that is not trivial. I have also integrated Django Rest Framework to allow CRUD functionalities of the Campaign class via an API. After searching on Google and DRF's docs, I found out that there is no official way to integrate Django Forms into DRF. I must be mistaken right? The only thing I see is that DRF has custom validators but I don't think it can port all the logic of my form to DRF's validators. How can I include the logic of my CampaignForm into my API? Reference: class CampaignForm(forms.ModelForm): class Meta: model = Campaign fields = '__all__' help_texts = { 'dayparting_schedule': schedule_help_text } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): """ - All Active MUST have dayparting schedule defined - If schedule is set then timezone must also be set """ cleaned_data = super().clean() status = cleaned_data.get('status') dayparting_schedule = cleaned_data.get('dayparting_schedule') if status == Campaign.ACTIVE: # if there is no existing dayparting_schedule OR # if this form does not have dayparting_schedule if dayparting_schedule is None \ and self.instance.dayparting_schedule is None: raise forms.ValidationError(_('dayparting_schedule cannot be empty for … -
How to retrieve POST request body in django REST API
I am trying to get the content of POST request body in django which is not working. from django.shortcuts import render from django.http import HttpResponse import json from car.models import Car from django.views.decorators.csrf import csrf_exempt @csrf_exempt def get_car(request): if request.method == 'POST': try: payload = json.loads(request.body) carname = payload['car_name'] response = json.dumps([{'car': carname}]) except: response = json.dumps([{'Error': 'no car with that name'}]) return HttpResponse(response, content_type = 'text/json') This code always returns 'Error' .