Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Maths Editor
I am django newbie and working on a math based project. I need to save texts involving mathematical symbols like integral, sigma, product etc. At the same time, I also need to emphasize or bold some texts (and do all kinds of rich text editing) and include figures that explains a mathematical concept. At present, I am just saving all the fields in a CharField (with dummy texts and without including any mathematical symbol) and have no idea how to include such a field. If you have any idea/hint or you have worked on similar projects, please help. -
Filter one-to-many relationship
I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view class Aliens(models.Model): class Meta: db_table = 'aliens' verbose_name = ('Introduction Event') verbose_name_plural = ('Introuction Events') ordering = ['alien'] alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species", on_delete=models.CASCADE, null=True, blank=True) #SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True) group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE, blank=True, null=True, default='') firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True) med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE, null=True, blank=True) origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='', verbose_name=u"Origin") status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='', verbose_name=u"Establishement") created_by = CurrentUserField() created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now()) photo = models.ImageField(upload_to='photos', blank=True, null=True) vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways") updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now()) updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated', default=CurrentUserField(), null=True) notes = models.TextField(verbose_name='Notes', blank=True, null=True) db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True) def __str__(self): # __unicode__ on Python 2 return self.alien.SpeciesName class Distributions(models.Model): class Meta: db_table = 'distributions' verbose_name = ('verified occurence') verbose_name_plural = ('verified occurences') alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions', on_delete=models.CASCADE, null=True, blank=True) country = models.OneToOneField(Country, on_delete=models.CASCADE, … -
Count number of objects by date in daterange
In a Django project, I have these simplified models defined: class People(models.Model): name = models.CharField(max_length=96) class Event(models.Model): name = models.CharField(verbose_name='Nom', max_length=96) date_start = models.DateField() date_end = models.DateField() participants = models.ManyToManyField(to='People', through='Participation') class Participation(models.Model): """Represent the participation of 1 people to 1 event, with information about arrival date and departure date""" people = models.ForeignKey(to=People, on_delete=models.CASCADE) event = models.ForeignKey(to=Event, on_delete=models.CASCADE) arrival_d = models.DateField(blank=True, null=True) departure_d = models.DateField(blank=True, null=True) Now, I need generate a participation graph: for each single event day, I want the corresponding total number of participations. Currently, I use this awful code: def daterange(start, end, include_last_day=False): """Return a generator for each date between start and end""" days = int((end - start).days) if include_last_day: days += 1 for n in range(days): yield start + timedelta(n) class ParticipationGraph(DetailView): template_name = 'events/participation_graph.html' model = Event def get_context_data(self, **kwargs): labels = [] data = [] for d in daterange(self.object.date_start, self.object.date_end): labels.append(formats.date_format(d, 'd/m/Y')) total_participation = self.object.participation_set .filter(arrival_d__lte=d, departure_d__gte=d).count() data.append(total_participation) kwargs.update({ 'labels': labels, 'data': data, }) return super(ParticipationGraph, self).get_context_data(**kwargs) Obviously, I run a new SQL query for each day between Event.date_start and Event.date_end. Is there a way to get the same result with a reduced number of SQL query (ideally, only one)? I tried many aggregation … -
Django: how to use a DB parameter in a default attribute of model field?
I have created a (kind of) singleton to put all the app parameters in my database: class SingletonModel(models.Model): def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) @classmethod def load(cls): return cls.objects.all().get() class Meta: abstract = True class AppParameters(SingletonModel, models.Model): DEFAULT_BALANCE_ALERT_THRESHOLD = models.PositiveIntegerField(default=5) # other parameters... It worked pretty well, until I tried to use one of these parameters in a default attribute of a model field: class Convive(models.Model): balance_alert_threshold = models.IntegerField( default=AppParameters.load().DEFAULT_BALANCE_ALERT_THRESHOLD, blank=True, null=True) This seemed to work too, but when I use a script to reinitialise local data, the first manage.py migrate produce a DoesNotExist since my Singleton does not exist yet. It happens because of a file importing Convive model. How would you solve this? Is there a way to "delay" the evaluation of the default field? Thanks. -
Why does the attribute not exist in the POST request?
I am trying to fill a field in a forms.ModelForm using a query based on a forms.Form. Unfortunately I am getting an AttributeError that suggests the field doesn't exist, and I'm not sure why this is. The error is AttributeError: 'ElectionSuggestionForm' object has no attribute 'PostElection' Here is the views.py: def new_post(request): if request.method == 'POST': form = NewPostForm(request.POST) election_form = ElectionSuggestionForm(request.user, request.POST) if form.is_valid(): post = form.save(commit=False) post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection) post.save() return redirect('/feed/') else: form = NewPostForm() election_form = ElectionSuggestionForm(request.user) return render(request, 'campaign/new_post.html', { "form": form, "election_form": election_form, }) Here is the forms.py: class ElectionSuggestionForm(forms.Form): PostElection = forms.ModelChoiceField(queryset=None) def __init__(self, user, *args, **kwargs): super(ElectionSuggestionForm, self).__init__(*args, **kwargs) print(Election.objects.all().filter(candidate__UserID=user)) self.fields['PostElection'].queryset = Election.objects.all().filter(candidate__UserID=user) Thanks -
Django 2: path('^$', home, name='home') not working
I am new to Django and trying to make a project, but I am facing a simple problem. I am writing a path in Django 2 for root and it's not working, but for other things it works. Can anyone point out why it's not working. What is working: path(r'home/', home, name='home'), This is not working: path(r'^$', home, name='home'), And just to be clear: I am not loading both the line together. I comment one line at a time, so no order issues. -
Epic HttpResponse Error
I'm yet to understand why I'm getting 'HttpResponse' error. Traceback (most recent call last): File "C:\Python27\Scripts\covaenv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Python27\Scripts\covaenv\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view exampleapp.views.get_recieve_update didn't return an HttpResponse object. It returned None instead. This view is responsible for getting a POST request from an API and load the data and do things with it. VIEWS: @csrf_exempt def get_recieve_update(request): if request.method=="POST": man= json.loads(request.body) txId = man['hash'] uri = bgo_main_base_url + '/wallet/{}/tx/{}'.format(WALLETID, txId) rexa = requests.get(uri, headers=headers) vd = rexa.json() isMine = vd['outputs'][0]['isMine'] confirmations = vd['confirmations'] if isMine == True and confirmations > 1: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] try: get_adr = CPro.objects.get(address = address) except CPro.DoesNotExist: get_adr = None if not get_adr.is_used==True and get_adr.is_active==False: update_cw = CW.objects.filter(user = get_adr.user).update(current_btc_balance=F('current_btc_balance') + value , modified_date=datetime.datetime.now()) return HttpResponse('done') elif get_adr.is_used==True and get_adr.is_active==False: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] send_mail('Recieved on Used Address','failed to credit for {} with {} and id {}'.format(address, value, txId), DEFAULT_FROM_EMAIL,[DE_MAIL,]) else: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] send_mail('Recieved Callback Error','failed to credit for {} with {}'.format(address, value), DEFAULT_FROM_EMAIL,[DE_MAIL,]) What am I missing? -
Convert SQL to django ORM query
Can someone convert the following query into Django ORM query without using raw in ORM. If you can please explain usage of '__' in the answer. SELECT date from submissions where application_id in (select application_id from products where name = (select name from bank where bank_id = 'B01')); -
Django ImportError: Couldn't import Django
I have a project about django web, this project has no problem on other computers, but pycharm on my own laptop prompts for the following information ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I use PyCharm Professional and PyCharm3 My system is Windows 10. Can someone help? -
Ordering Topic model in Django for forum app
I'm working on a forum like app. The problem I'm having is that the order of the topics of the forum is determined by query. However I want to implement custom ordering by the admins. So I thought I could have a integer field named order in my Topic model with unique=True. However I'm not able to think how I can create a form for this. Here's my approach: I want to have a up and down button in my forum for every topic. When the admin orders using JS, a invisible form is filled and submitted on pressing the submit button. My idea of the invisible form is this: I will have data in the form like this: The left is the pk of the topic and right is the ordering 1 0 2 3 3 2 4 1 I think this is too hacky and not a good implementation. Is there a better way to do it? Is this a bad design? -
Error in Django: OSError: dlopen() failed to load a library: cairo / cairo-2
After installing WeasyPrint, I am getting this error: "Error in Django: OSError: dlopen() failed to load a library: cairo / cairo-2" Here is all the details: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0446DE40> Traceback (most recent call last): File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Kanon\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File … -
Pandas apply ValueError: bad input shape() when sending POST request
I am trying to implement an API in a django framework with the following code below: def worker_label_encoder(df,selected_col): le = LabelEncoder() enc = le.fit(np.unique(df[selected_col])) df[selected_col] = df[selected_col].apply(enc.fit_transform) It works fine when I tried it in a script on Atom. But when I use postman to send POST request with this API, it returns ValueError: bad input shape () on this line: df[selected_col] = df[selected_col].apply(enc.fit_transform) What is wrong? Why does it work in a script but not in post request? -
local variable 'post' referenced before assignment
Im trying to assign the current logged in username to the existing model through a form. But facing a problem while saving the form #views.py def create(request): if request.method == "POST": form=NotForm(request.POST) if form.is_valid(): post.user = request.user.get_username() post = form.save(commit=False) post.save() return redirect('base') else: form=NotForm() return render(request, 'create.html',{'form':form}) forms.py class NotForm(forms.ModelForm): class Meta: model=Note fields = ('title', 'desc',) models.py class Note(models.Model): title=models.CharField(max_length=50) desc=models.TextField(max_length=200) user=models.ForeignKey('auth.User') -
show the result of two dictionaries
i have two dictionaries a and b a = {"xx": [{"sat": [{"sat1": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75}, {"sat2": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75},...]}} b = {"xx": [{"sat": [{"sat1": [{"det": {"amount": 2222}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75}, {"sat2": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75},...]}} here in dict a {"amount": 1111} and in b {"amount": 2222} ..this is the diff in a and b....i want to show this difference.. like --- diff: a = {"sat": [{"sat1": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75} b = {"sat": [{"sat1": [{"det": {"amount": 2222}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75} similarities : a = {"sat2": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75} b = {"sat2": [{"det": {"amount": 1111}, "help": {"cs": 0, "c": 0, "some_key": "no"}}], "value": 75} how can i display such result.. i have used diff(a, b) -
How to add myself's logic when I access the `ListAPIView`?
I use the BannerListAPIView when access the banner list: class BannerListAPIView(ListAPIView): serializer_class = WebsiteBannerSerializer permission_classes = [] queryset = WebsiteBanner.objects.all() But I want to add my logic when access this ListAPIView, such as I want to record the remote_ip. How to add myself's logic when I access this ListAPIView? -
Django nested serializers update
I have two models in my models.py: class City(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=28) class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) Since I only want to get the name of the city if i fetch a Person from the API, i implemented it like this in the serializer: class PersonSerialzer(serializers.ModelSerializer): city = serializers.SerializerMethodField('_city') class Meta: model = Person fields = ('username', 'city') def _city(self, obj): return obj.city.name I have an endpoint to update the instance which is an generics.UpdateAPIView class, but when I send the following response it cannot update the city: { "city": "Hamburg" } I think I need to create a CitySerializer and nest it into the PersonSerializer instead of the SerializerMethodField and implement a custom update method in the CitySerializer. But is it possible to nest the serializer but only print out the name string instead of an object containing that string in the API? -
Django stops recieving/sending MQTT messages after 500 error
I am trying to implement Paho MQTT on Django but Django stops receiving/sending MQTT messages after a 500 error. I am using Paho MQTT client 1.3.0 along with Django 1.10.8, Python 3.6.2 Here are my MQTT settings: mqtt.py from django.conf import settings import paho.mqtt.client as mqtt SUB_TOPICS = ("device/vlt", "device/auth", "device/cfg", "device/hlt", "device/etracker", "device/pi") RECONNECT_DELAY_SECS = 2 # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. for topic in SUB_TOPICS: client.subscribe(topic, qos=0) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) def on_publish(mosq, obj, mid): print("mid: " + str(mid)) def on_subscribe(mosq, obj, mid, granted_qos): print("Subscribed: " + str(mid) + " " + str(granted_qos)) def on_log(mosq, obj, level, string): print(string) def on_disconnect(client, userdata, rc): client.loop_stop(force=False) if rc != 0: print("Unexpected disconnection: rc:" + str(rc)) else: print("Disconnected: rc:" + str(rc)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_subscribe = on_subscribe client.on_disconnect = … -
Fix a user to its specific blog when logged in
Here is my view for blog_create. I want to fix this for a specific user when he/she is logged in. @login_required def blog_create(request,blogger_id): blog=Blog.objects.all() user=get_object_or_404(User,pk=blogger_id) form=BlogForm(request.POST) if request.method=="GET": return render(request,'winterblog/blog_create.html',{'form':form}) if request.method=="POST": if form.is_valid(): blog=form.save(commit=False) blog.save() return redirect('winterblog:blog_list') else: form=BlogForm() return redirect('winterblog:blog_create') And for the form is: class BlogForm(ModelForm): class Meta: model=Blog fields=['headline','blog_text','user'] Thanks! -
create multiple same html page in django
I am new to Django and I am going to create a website with multiple same html pages. I got a text file which contains the number of how many same html pages is going to create. And the following one is the view.py. And the t=a.split()[7] get the number of pages needed to be created def bb(request): form=BBForm(request.POSt or None) if(form.is_valid()): my_file=open("./input_data.txt",'r') a=my_file.read(); my_file.close(); t=a.split()[7] form.save() context={"form":form} return render(request,'bb/bb.html',context) And the bb.html is like the following: <form method='POST' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit /> </form> If I only use those code, I can generate the website with the form.However, it only appears once. What can I do if I want to create multiple same forms within one html page or multiple html page with the same html code -
MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform
i downloaded MySQL_python-1.2.5-cp27-none-win_amd64.whl to help with connection between mysql and django. But there is an error : MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform. what should i do now ? -
Reorder app and models in Django admin
I want to reorder my apps in my Django admin panel, I saw some responses from another similar question here in SO, so I go for install this method: django-modeladmin-reorder I follow all the steps and it's not working. Here's my actual Django panel #settings.py MIDDLEWARE_CLASSES = ( 'admin_reorder.middleware.ModelAdminReorder', ) ADMIN_REORDER = ( # Keep original label and models 'organization_owners', 'panel', 'clients', ) and also is in my requirements.txt Django==2.0.1 django-extensions==1.9.8 django-modeladmin-reorder==0.2 djangorestframework==3.7.7 flake8==3.5.0 -
Django ORM calculations between records
Is it possible to perform calculations between records in a Django query? I know how to perform calculations across records (e.g. data_a + data_b). Is there way to perform say the percent change between data_a row 0 and row 4 (i.e. 09-30-17 and 09-30-16)? +-----------+--------+--------+ | date | data_a | data_b | +-----------+--------+--------+ | 09-30-17 | 100 | 200 | | 06-30-17 | 95 | 220 | | 03-31-17 | 85 | 205 | | 12-31-16 | 80 | 215 | | 09-30-16 | 75 | 195 | +-----------+--------+--------+ I am currently using Pandas to perform these type of calculations, but would like eliminate this additional step if possible. -
Django ModelForm not displaying all fields
I'm trying to build forms linked to a PostgreSQL database using Django ModelForms. The template is rendering two of the fields(the ones with ManyToMany relationships), but it only gives me an empty box for "title". This is my forms.py: Forms.py: class ProgramForm(forms.ModelForm): class Meta: model = Program fields = ['function','task', 'title'] widgets = { 'function' : forms.Select, 'task' : forms.Select, 'title' : forms.Select, } This is my Models.py: class Program(models.Model): title = models.CharField(max_length=255) function = models.ManyToManyField(function, related_name='programs') task = models.ManyToManyField(Task, related_name='programs') def __unicode__(self): return self.title class Task(models.Model): tasknum = models.CharField(max_length=20) taskname = models.CharField(max_length=100) task_num_name = models.CharField(max_length=100) function = models.ForeignKey(Function, related_name="tasks") def __unicode__(self): return self.task_num_name class Function(models.Model): function = models.CharField(max_length=50) function_abrev = models.CharField(max_length = 25) def __unicode__(self): return self.function Views.py: def main(request): return render (request, 'assignments/main.html') def add_program(request): form = ProgramForm() return render (request, 'assignments/ad_form.html', {"form":form}) def link(request): if request.method == 'POST': form = ProgramForm(request.POST) if form.is_valid(): return HttpResponse("we maybe getting somewhere") else: return HttpResponse("keep working") I need a couple of things to happen: I need for the "title" to render in the html page as a scroll down(the same way "function" and "task" appear. I need to be able to save the relationships. The models are populated with all the … -
How to test redirection in Django using pytest?
I already know that one can implement a class that inherits from SimpleTestCase, and one can test redirection by: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True) However, I am wondering what is the way I can check for redirection using pytest: @pytest.mark.django_db def test_redirection_to_home_when_group_does_not_exist(create_social_user): """Some docstring defining what the test is checking.""" c = Client() c.login(username='TEST_USERNAME', password='TEST_PASSWORD') response = c.get(reverse('pledges:home_group', kwargs={'group_id': 100}), follow=True) SimpleTestCase.assertRedirects(response, reverse('pledges:home')) However, I am getting the following error: SimpleTestCase.assertRedirects(response, reverse('pledges:home')) E TypeError: assertRedirects() missing 1 required positional argument: 'expected_url' Is there any way I can use pytest to verify redirection with Django? Or I should go the way using a class that inherits from SimpleTestCase? -
Django http request to api error
As this is the first time i'm trying this out, i do not know what is wrong with the problem. So it would be great if someone can help me solve this problem The code im using is at the bottom page from this website: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html Where it give example on how you can make http request function and retrieve data base on your query. The code in the website is this. query.py import requests import json BASE_URL = 'http://pokeapi.co' def query_pokeapi(resource_url): url = '{0}{1}'.format(BASE_URL, resource_url) response = requests.get(url) if response.status_code == 200: return json.loads(response.text) return None charizard = query_pokeapi('/api/v1/pokemon/charizard/') sprite_uri = charizard['sprites'][0]['resource_uri'] description_uri = charizard['descriptions'][0]['resource_uri'] sprite = query_pokeapi(sprite_uri) description = query_pokeapi(description_uri) print charizard['name'] print description['description'] print BASE_URL + sprite['image'] In my edit, i only change these print line at the bottom to this query.py print(charizard['name']) print(description['description']) print(BASE_URL + sprite['image']) But i got this error instead Traceback (most recent call last): File "query2.py", line 46, in sprite_uri = charizard['sprites'][0]['resource_uri'] TypeError: 'NoneType' object is not subscriptable