Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize {% bootstrap_form form %} in django?
There is Problem Hello I'm creating a project,I created a register form, but I tried to create an email authentication submit button in the form near EmailInput, but I could not find it I'm currently using {% bootstrap_form form%} to render automatically in a register form What I want I would like to have the Submit Email Authentication button appear on the form near EmailInput, When the user clicks the Send Email Authentication button, it sends an authentication email to the user's email Then, when the user clicks the link attached to the mail, the user is informed that the confirmation has been made on the register window and When the user clicks the sign up button, the registration is completed What I've tried I created a register form using UserCreationForm supported by django, I tested using gmail smtp to send email from django. It works well The Code /django-blog/blog/settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'y$a)3faq3*h#r0g5b^cxsw^lgdxbbu&#lsqek!_0ju+d*c!ups' # SECURITY WARNING: don't run with debug turned on in … -
Displaying nested dictionary in view
I have a dataframe where I group by a column and then convert that dataframe to a dictionary. context['data'] = "carrier_data": noDupsdf.groupby("market").apply(dict) The resulting data looks something like this: "ATL": { "currency": ["USD", "EUR", "CAD"], "amount": [1232, 22, 44], }, "JFK": { "currency": ["GBP", "EUR"], "amount": [122, 442], } I'd like to loop through the data and display it accordingly: <ul style="list-style: none"> <li style="display: inline-block">ATL</li> <li style="display: inline-block">JFK</li> </ul> <div class="first-container"> <div class="card"> <p>Currency: USD</p> <p>Amount: 1232</p> </div> <div class="card"> <p>Currency: EUR</p> <p>Amount: 22</p> </div> <div class="card"> <p>Currency: CAD</p> <p>Amount: 44</p> </div> <div class="second-container"> <div class="card"> <p>Currency: GBP</p> <p>Amount: 122</p> </div> <div class="card"> <p>Currency: EUR</p> <p>Amount: 442</p> </div> There will be at maximum three markets. How do I display the data in the way like so? -
Django jquery AJAX form submission in view and display results
There are a lot of different posts about all parts of this, I just can't quite figure out how it all fits together. I have name that is displayed with an update button next to it. When the update button is clicked it shows a form to update the name. In the form is a save changes button. When the changes are saved, it should reload the name at the top, and should the update button be clicked again, the form should show the new name info. urls.py path('profile/<int:pk>/', views.customer_profile, name='profile'), path('update-profile/<int:pk>/', views.update_profile, name='update-profile'), views.py def customer_profile(request, pk): name = get_object_or_404(CEName, id=pk) name_form = NameForm(instance=name) return render( request, 'customer/customer_profile.html', {'name':name, 'NameForm': name_form} ) def update_profile(request, pk): if request.POST: name_form = NameForm(request.POST) if name_form.is_valid(): name_form.save() name = get_object_or_404(CEName, id=pk) context = {'name':name, 'NameForm': name_form} html = render_to_string('customer/customer_profile.html', context) return HttpResponse(html, content_type="application/json") template.html <div id="name" class="container d-flex justify-content-between pt-1"> {{ name }} <button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button> </div> <div id="div_NameForm" class="container" style="display: none;"> <hr size="3px"> <form id="NameForm" method="POST" data-url-name="{% url 'customer:update-profile' name.id %}"> {% csrf_token %} {{ NameForm.as_p }} <br> <button type="submit" id="save_changes" class="btn btn-main button-main btn-block">Save Changes</button> </form> </div> <script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script> jquery.js $('#save_changes').click(function() { var NameForm … -
MultiValueDictKeyError Exception Value: 'stripeToken'
I am trying to insert a stripe credit card form, but I am receiving this error which I believe means that my view is not receiving a token associated with the form that was submited. "MultiValueDictKeyError Exception Value: 'stripeToken'" Error. I included my Views, HTML, and JS. Views.py @login_required def checkout(request): count = OrderItem.objects.all().count() existing_order = get_user_pending_order(request) #stripe publishKey = settings.STRIPE_PUBLISHABLE_KEY customer_id = request.user.user_stripe.stripe_id if request.method == 'POST': token = request.POST['stripeToken' # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: try: charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, ) return redirect(reverse('checkout:update_records', kwargs={ 'token': token }) ) except stripe.error.CardError as e: message.info(request, "Your card has been declined.") context = { 'order': existing_order, 'publishKey': publishKey, 'count': count } return render(request, 'checkout/checkout.html', context) checkout.html <h5 class=""> PAYMENT METHOD </h5> <form class="form" action="." method="POST" id="payment-form"> {% csrf_token %} <div class="form-row "> <div class="col"> <label for="card-element"> Credit or debit card </label> </div> </div> <div class="form-row "> <div id="card-element" class="col ml-2"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert"></div> </div> <button class='btn btn-success text-white shadow mt-4' style="width: 100%; font-size: 1.2em;">Pay ${{ order.get_cart_total }}</button> <span … -
How to set a Django model field's NoData value
I just realized that the dataset I uploaded to Django model has a field (call it 'A') with "-999" which indicates NoData. This is throwing off my calculations, but I don't want to totally exclude these objects from my filters, just for calculations, for example: objects.aggregate(Avg('A')). How do I tell my Django model to treat this value as the NoData for field A? I see null=True tells Django to store empty values as NoData, but what if it should store Null when the values = -999. If there is not a straightforward way, is the best/most efficient way just to use exclude() whenever I make these calculations? Or maybe I should do some sort of replace in my database to convert -999 in field A to Null (how?). I thank you -
What's the best way to check if a queryset is a subset of another?
If there are two querysets q1 and q2, what's the best way to check if q1 is a subset of q2 ? Or do I have to iterate the values of them ? q1_id = q1.values_list('id', flat=True) q2_id = q2.values_list('id', flat=True) all([x in q2 for x in q1]) -
Using Angular Django MySQL and Bootstrap Studio in ONE project?
I'm just wondering if there is any way to use all those things together to make a project. Seems to me like great choice but I don't know if all of them can be combined into one workplace! Here is my thoughts, please don't be critical to me. I'm very new. So if it's possible to use all of them together(Bootstrap Studio[bootstrap 4], Angular, Django, mySQL). 1.Make really nice looking webpage in Bootstrap Studio (customize it or whatever you like) then extract files from there. 2. Insert your project into Angular framework to add maximum functionality to it. QUESTION HERE IS THAT POSSIBLE? 3.Using Django as back-end framework to interact with database? IS THERE POSSIBILITY TO USE IT WITH ANGULAR? 4.Use PHP myAdmin to interact with database and have control over it with GUI. How possible is that is? For me if everything really can work together looks like a nice and efficient way to create great websites. But I wanna say I'm newbie so don't judge me bad. -
Angular 5, Django rest and Xampp
I'm trying to do a deploy of django rest in Xampp, either uni angular and django rest, when trying to run django rest in xampp I get an error. GET http://localhost:8000/api/categorias/ net::ERR_CONNECTION_REFUSED Request URL: http://localhost:8000/api/categorias/ Referrer Policy: no-referrer-when-downgrade Provisional headers are shown Accept: application/json, text/plain, */* Origin: http://localhost:8081 Referer: http://localhost:8081/ User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 This is my configuration in apache to run django <IfModule wsgi_module> # Setup WSGI WSGIScriptAlias / C:\xampp\htdocs\tutorial\tutorial\wsgi.py WSGIPythonPath C:\xampp\htdocs\tutorial <Directory C:\xampp\htdocs\tutorial> Allow from all </Directory> # Static files Alias /static/ C:\xampp\htdocs\tutorial\static\ <Directory C:\xampp\htdocs\tutorial\static> Order deny,allow Allow from all </Directory> my question is because that error comes out, when I run it with runserver.py it works normal but in xampp it does not work, why that happens -
How to django model ManyToMany field empty initially?
I'm have two related models as follows. class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) isbn =models.CharField(max_length=15) class Lending(models.Model): member_id = models.ForeignKey(Member) name = models.CharField(max_length=100) borrowed = models.DateField(auto_now_add=True) returning = models.DateField() book_list = models.ManyToManyField(Book, related_name='borrowed_books') I want to make the book list field empty in Lending creation HTML form when displayed to the user. I want to make sure it is not blank in backend model form and not null in the model. I'm doing this because the book list could be huge and will use ajax to query the book to add them dynamically to the book list in HTML form field when sending data. How can I do this? -
Django how do i filter ManyToMany field
I have the following M2M relationship between OrderPage and Site. How can I filter Site which belong to all OrderPage ? something like Site.objects.filter(all of the orderpage).distinct() class OrderPage(models.Model): description = models.CharField(max_length=255, blank=False) sites = models.ManyToManyField(Site) -
Setting Groups which have different number of instances and, expiration dates in django
I'm creating a property listing website and I'm fairly new to django, have created the property model, and would like to group users into groups with different privileges, ie can post 3 ads for one week and another can post 7 ads for one month. I would really appreciate your help, even a link would be of much help to me thanks in advance -
How to properly serialize an object whose model has a foreign key which also takes an ImageField?
# models.py class Post(models.Model): content = models.TextField(blank=True, default='') created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class PostImage(models.Model): image = models.ImageField(upload_to=unique_upload) post = models.ForeignKey( Post, related_name='images', on_delete=models.CASCADE) This is my model set up for a basic scenario where a user can enter content or upload images as their posts. I want to bundle my logic to handle creating a post with either content or images or both. I first started playing around with GenericViewSet and CreateViewSet but was images was never being passed to my serializer. # views.py class CreatePostViewSet(generics.CreateAPIView /* viewsets.GenericViewSet */): permission_classes = (IsAuthenticated,) queryset = Post.objects.order_by('id') serializer_class = CreatePostSerializer def create(self, request, *args, **kwargs): data = {} print(request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(created_by=request.user) # post = serializer.instance # print(post) # for im in post.images.all(): # im.save(post=post) # print(post.images.all()) return Response(data, status=status.HTTP_201_CREATED, headers=self.get_success_headers(serializer.data)) # serializers.py class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('id', 'url', 'image', 'post',) read_only_fields = ('post',) depth = 1 class CreatePostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, required=False) class Meta: model = Post fields = ('id', 'url', 'content', 'images',) read_only_fields = ('created_by',) depth = 1 def create(self, validated_data): # validated_data['images'] is always [] print(validated_data) raise images is always [] when I pass it to a serializer, but it does … -
Django gives Seg Fault when rendering template, but works with pdb
So I'm working on this webapp, and it was working smoothly until I started adding Translations to it. Now, when I request a specific URL in my template, it gives ERR_EMPTY_RESPONSE in the browser, and the terminal shows Seg Fault. System check identified no issues (0 silenced). October 18, 2018 - 21:25:00 Django version 2.1, using settings 'Inovatoxin.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [18/Oct/2018 21:25:02] "GET / HTTP/1.1" 200 53144 Segmentation fault (core dumped) The function that causes this is absolutely simple (and I know that the program actually reaches that view): def about(request): """ Shows detail page for the project. """ return render(request, 'Proteins/about.html', {}) So I naturally though the problem is somewhere in rendering the template, and decided to debug it with pdb. I then changed the function above to this: def about(request): """ Shows detail page for the project. """ import pdb; pdb.set_trace() return render(request, 'Proteins/about.html', {}) But when I run the server the error disappears, and the page renders correctly in the browser, translated, even: System check identified no issues (0 silenced). October 18, 2018 - 21:20:25 Django version 2.1, using settings 'Inovatoxin.settings' Starting development server at http://127.0.0.1:8000/ Quit the server … -
ModuleNotFoundError on pythonanywhere
Any idea where I should look for a solution? My django project worked fine on pythonanywhere. I then added a new app to the project, which worked fine locally. However, when I git pulled the project with the new app to PythonAnywhere, I got the following error: 2018-10-18 23:38:56,622: Error running WSGI application 2018-10-18 23:38:56,637: ModuleNotFoundError: No module named 'catalog.apps' 2018-10-18 23:38:56,637: File "/var/www/aceh40_pythonanywhere_com_wsgi.py", line 21, in <module> 2018-10-18 23:38:56,637: application = get_wsgi_application() Here is the content of the WSGI file: settings_path = '/home/aceh40/aceh40.pythonanywhere.com/aceh40' sys.path.insert(0, settings_path) dotenv_path = os.path.expanduser('~/aceh40.pythonanywhere.com') # adjust as appropriate load_dotenv(os.path.join(dotenv_path, '.env')) # Set environment variable to tell django where your settings.py is os.environ['DJANGO_SETTINGS_MODULE'] = 'aceh40.settings' # Set the 'application' variable to the Django wsgi app from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django on Heroku connecting to Azure Database
I'm deploying a Django application onto Heroku. I have my app wired up to a legacy database located on Azure. I've been using the django-pyodbc-azure package and have had no issues connecting to the Azure DB via my local development server. But when I try to access via production, I get a message stating: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)") Any thoughts on what could be causing this? I can't find much documentation on this specific issue. Thanks. -
Django - Where is the context variable?
I'm still getting used to class based views, while I get the general purpose, some things still get past me. I'm following a tutorial which basically walks you through the motions but tends to ignore the fuzzy details, such as this piece of code: class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView): """Generic class-based view listing books on loan to current user.""" model = BookInstance template_name ='books/bookinstance_list_borrowed_user.html' paginate_by = 1 def get_queryset(self): return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back') I get the model, template_name and paginate_by parts, they're attributes of the ListView class, but what I don't get is the get_queryset part, where is it executed? As seen in the code below it's called nowhere. Where is it returned to? I guess my first question can be chalked down to "What do functions in class based views do?" {% extends "base_generic.html" %} {% block content %} <h1>Borrowed books</h1> {% if bookinstance_list %} <ul> {% for bookinst in bookinstance_list %} <li class="{% if bookinst.is_overdue %}text-danger{% endif %}"> <a href="{% url 'book-detail' bookinst.book.pk %}">{{bookinst.book.title}}</a> ({{ bookinst.due_back }}) </li> {% endfor %} </ul> {% else %} <p>There are no books borrowed.</p> {% endif %} So, two issues, first, where did the get_queryset return to, and second, what is bookinstance_list? It's not a context variable, … -
django tutorial poll app, trying to understand logic
I'm trying to understand the logic of linking foreign keys to primary keys, so far everything seems pretty straight forward except this one part which is throwing me off, if anyone can clarify that I would really appreciate it So this first portion I would be linking the row with primary key 1 to the variable q >>> q = Question.objects.get(pk=1) >>> q.choice_set.all() <QuerySet []> Basically Creating choices and linking them to q (which consists of the question associated to primary key 1) # Create three choices. >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> This is the part thats throwing me OFF! Why do I have to all of a sudden on the last choice set it the variable c? >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) # Choice objects have API access to their related Question objects. I see that the question is set inside of variable c, but what was the point, is there a specific reason that the last choice had to be set to a new variable c?? Is this conventional? and what i'm trying to ask is.. Everytime I create some type of foreign key relationship does my … -
HINT: No function matches the given name and argument types. You might need to add explicit type casts. TrigramSimilarity Django
I am trying full text search using TrigramSimilarity. I have activated pg_trgm extension in PostgreSQL. and added 'django.contrib.postgres' in my installed apps. But when I am trying query blog.objects.annotate(similarity=TrigramSimilarity('name', 'abc'),).filter(similarity__gt=0.3).order_by('-similarity') But its giving me an error psycopg2.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...others_2", "blog_mod", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Why this error is happening. Please help me. -
Optimize Django Query with two joins
I have a query that implies three tables: hotels = models.Hotel.objects.filter(contracts__rate_tables__start_date__lte=check_in, contracts__rate_tables__due_date__gte=check_in).distinct(), where contracts and rates_tables are nested lookup fields. The query is becoming slower as the database grows, so I tried to use an index (indexes = [models.Index(fields=['id', 'contracts__id', 'contracts__rates_tables']),]), but I found that it is not possible to do so with columns from different tables. What would be the best option to optimize this query? -
DjangoCMS URLs and Reverses
Working through a django project and still a little confused by URL patterns. Currently what I have is this urls.py from django.conf.urls import url, include from .views import AssetListView, AssetDetailView app_name = 'assets' urlpatterns = [ # List View url(r'^$', AssetListView, name="asset_list"), url(r'^$/<int:id>/', AssetDetailView, name='asset_detail') ] models.py from django.db import models from products.models import * from cms.models.fields import PlaceholderField from django.urls import reverse class Asset(models.Model): name = models.CharField(max_length=50, blank=False) description = PlaceholderField('asset_description') asset_category = models.ManyToManyField(Asset_Category, blank=True) tag = models.ManyToManyField(Tag, blank=True) product_category = models.ManyToManyField(Category, blank=True) product_series = models.ManyToManyField(Series, blank=True) product_line = models.ManyToManyField(Line, blank=True) product = models.ManyToManyField(Product, blank=True) url = models.CharField(max_length=250, blank=True, verbose_name='Video URL') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("assets:asset_detail", kwargs={"id": self.id}) def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .models import * import os from cms.models import Title # Create your views here. def AssetListView(request, *args, **kwargs): path = os.path.basename(os.path.normpath(request.path)) print(path) page_obj = Title.objects.filter(slug=path).first() print (page_obj) for obj in Tag.objects.all(): print (obj.name) if obj.name == page_obj.title: queryset = Asset.objects.filter(tag=obj.id) context = { 'object_list': queryset, } return render(request, 'asset_view.html', context) queryset = Asset.objects.all() context = { 'object_list': queryset, } return render(request, 'asset_view.html', context) def AssetDetailView(request, *args, **kwargs): return HttpResponse('<h1>AssetDetailView<h1>') … -
How to compare models using id's Django
URGENT Can anyone please help in tackling the following problem? Suppose I have a model name Answer and a form for user input named CheckAnswer What I want is that when a particular Question page is openend and the user types the answer, it should get checked with the corresponding answer The answer from the model can be accessed using the id. but how can i specify the id of question page that opens up and link it to the answer id. Below are the codes attached forms.py from django import forms from .models import Answer from django.core.exceptions import ObjectDoesNotExist class CheckAnswer(forms.Form): your_answer=forms.CharField(label='Answer') def clean(self): cleaned_data=super(CheckAnswer,self).clean() response=cleaned_data.get("your_answer") try: p = Answer.objects.get(id=1,answer__iexact=response) except Answer.DoesNotExist: raise forms.ValidationError("Wrong Answer.") views.py from django.shortcuts import render,redirect from django.views.generic import * from . import models from django import forms from .forms import CheckAnswer from django.contrib.auth.decorators import login_required # Create your views here. @login_required def Arena1(request): if request.method=='POST': form = CheckAnswer(request.POST) if form.is_valid(): return redirect('thanks') else: form=CheckAnswer() return render(request,'levels/arena1.html',{'form':form}) models.py from django.db import models from django.contrib.auth import get_user_model User=get_user_model() users=User.objects.all() # Create your models here. class Answer(models.Model): name=models.CharField(max_length=10,unique=True) answer=models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering= ["-name"] -
How to display and update model data in Django One-to-one relationships?
I have two models Place and Restaurant with one-to-one relationship. I want to use one model form Restaurantform and display place name in the form edit mode. Upon submitting the form need to update data in both model fields. class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) name = models.CharField(max_length=50) serves_pizza = models.BooleanField(default=False) def __str__(self): return "%s the restaurant" % self.place.name class Restaurantform(forms.ModelForm): class Meta: model = Restaurant fields = ['name', 'serves_pizza', 'Name field from Place Model?'] I am not sure how to display place name and process the form submission! Thank you! -
Django: SendGrid Click Tracking service prevents messages framework from working
I'm trying to implement signup with confirmation email with Django using SendGrid as email provider, my 'SignUpActivationView' code validates the token and then redirects the user to the home page, where a success/error message is displayed using the messages framework: class SignUpActivationView(RedirectView): redirect_url = reverse_lazy('link_list') def dispatch(self, request, *args, **kwargs): ... # if token is valid: messages.error(self.request, 'Your account is now active.') return HttpResponseRedirect(self.redirect_url) # if token is invalid: messages.error(self.request, 'Your account could not be activated.') return HttpResponseRedirect(self.redirect_url) So far my approach works as long as I copy-paste the link in my browser, if I click on it instead, the user is activated but the success message is not shown in my application. I believe this is because SendGrid's Click Tracking service is wrapping my link: A workaround I found is to tell SendGrid to NOT track the link by adding and the 'clicktracking=off' HTML attribute, the disadvantage is that I can only tell SendGrid not to track links in the HTML version of my email. In case the user's email client decides to open the Plain text version of the email, then link will still be wrapped. # solution: do not track clicks # caveat: only works in HTML, … -
Can't connect to RDS Postgres locally after setting up NAT instance
I am working on a Django project that uses Zappa to host a serverless app on Lambda. It uses a Postgres database on the back and I've been able to use it flawlessly for some time. Recently I needed to use urllib, and so I needed a NAT instance (EC2 micro instance) to allow Lambda to access the internet. Now that it's set up, it works fine on production, I can see my site fine and all the pieces interact correctly. However, locally, Django can't seem to connect, it gets this error: django.db.utils.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "XXXXXXXXX.XXXXXXXXX.us-west-2.rds.amazonaws.com" (54.70.245.158) and accepting TCP/IP connections on port 5432? To outline the steps I've gone through, I created a VPC network with private and public subnets through the wizard. I added 2 more private subnets in other zones for availability. I went to my Lambda function and changed the subnets to the new subnets and I also moved my RDS to the same subnets (private ones). For my RDS, I created a new security group for Postgres (port 5432 inbound with source 0.0.0.0/0). My settings.py under Django remains the same: DATABASES = … -
Structuring JSON to loop through in Django View
I'm using Axios to POST a request to a Django route. The JSON is structured as follows: { "blanks": { { "id": 1, "sizes": { "id": 1, "size": "SM" } }, { "id": 1, "sizes": { "id": 1, "size": "SM" } } }, "locations": { { "id": 1, "name": "Philadelphia" }, { "id": 2, "name": "Boston" }, } } I'm trying to loop through each of the objects within locations, and perform an action on them. My Django function is as follows: def order_new_store(request): post_unicode = request.body.decode('utf-8') post = json.loads(request.body.decode('utf-8')) for location in post['locations'].items(): #etc However, my app is throwing the following error: AttributeError: 'list' object has no attribute 'items' Is there a way that I can restructure either my JSON, or my loop, so that I can grab a subset of the JSON object and loop through it?