Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
files with arabic name causes rest_framework.fields.to_representation
I'm using django-rest-framework to store some models. in my model I have avatar with ImageWithThumbsField filed after storing the file in admin dashboard if the file with arabic name will cause rest_framework.fields.to_representation. should I rename the file before saving or there is a method to solve this problem? -
Django open view PDF file in another page
In a HTML page I am showing a list of data containing pdf files. All the pdf file name are hyperlinks. When user clicks on that hyper link the pdf should open in a new tab. My problem that I can not manage this situation to view a PDF file. Tell me the correct answer in code. contract_list.html {% for final in finals %} Contract name: <a href="{% url 'contract_detail' id=final.id %}" target="_blank"> {{ final.file_name }} </a><br> {% endfor %} contract_detail.html ( ????????) I do not know what have to be writen here. views.py from django.shortcuts import render, get_object_or_404 from django.http import FileResponse, Http404 from .models import Valoare, Tip, Contract def contract_list(request, valoare, tip): valoare = get_object_or_404(Valoare, tip_valoare=valoare) tip = get_object_or_404(Tip, tip_contract=tip) finals = Contract.objects.filter(valoare__tip_valoare=valoare, tip__tip_contract=tip) return render(request, 'contracte/contract_list.html', {'valoare': valoare, 'tip': tip, 'finals':finals}) def contract_detail(request, final): id = get_object_or_404(Contract, id=final.id) return render(request, 'contracte/contract_detail.html', { 'id': id }) def pdf_view(request, final): name = get_object_or_404(Contract, name=final.file_name) document_data = open(name, “rb”).read() return HttpResponse(document_data, mimetype=”application/pdf”) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.valoare_list, name='valoare_list'), url(r'^valoare/(?P<valoare>[A-Z]{4})/$', views.valoare_detail, name='valoare_detail'), url(r'^valoare/(?P<valoare>[A-Z]{4})/(?P<tip>[A-Z]+)/$', views.contract_list, name='contract_list'), url(r'^contract/(?P<id>\d+)/$', views.contract_detail, name='contract_detail'), url(r'^pdf/$', views.pdf_view, name='pdf_view'), (!!! I am not sure if it is correct) ] models.py … -
Cant figure out how to create multiple Modelforms with different prefix django
I am working on a specific view in a project and I cant seem to figure out how to accomplish it. I want to dynamically duplicate a single form in a django view and for each of the forms, add a prefix to each of the forms based on a data field from a query set. I want to then pass in the duplicate forms into the html where the user can input information in the fields and the submit it. The issue is that I cant figure out how to create duplicate forms with different prefixes based on the results of a query set. and assign each prefix to the username of the user record that is being called. So lets say I have a query set that calls a query set to pull all of the users whose names start with t. and for every user in the users query, I want to create a form based on the inividualsplitform and for each of the forms, add the prefix with the username that is attach to the specific user. And i want to pass each of the forms to the html template and display the forms in the … -
KeyError during template rendering
I am facing KeyError while populating table using django tables2. i have not use django model and directly using django row query. Error during template rendering In template C:\Users\Shariq\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_tables2\templates\django_tables2\table.html, error at line 11 state_name 1 {% load django_tables2 %} 2 {% load i18n %} 3 4 <div class="table-container"> 5 {% block table %} 6 <table{% if table.attrs %} {{ table.attrs.as_html }}{% endif %}> 7 {% block table.thead %} 8 {% if table.show_header %} 9 <thead> 10 <tr> 11 {% for column in table.columns %} 12 {% if column.orderable %} 13 <th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a></th> 14 {% else %} 15 <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> 16 {% endif %} 17 {% endfor %} 18 </tr> 19 </thead> 20 {% endif %} -
How to turn a Django webpage into a PDF
I would like to add a feature to my Django website where the user can click on a link saying "Save as PDF". I would like this link to 1) produce a slightly different version of the page the user is currently on and 2) generate a PDF file in a separate window that the user can then save to wherever he or she wants. All of the PDF functions I came across related to Django assumed that you already had a PDF that you wanted to render. In this case though, I want to create a PDF based on the content of the current page. Any idea how to do this? Thank you. -
Django Querysets: Get only one from set and order them
I have this models: #models.py class Expression(models.Model): text = models.CharField(max_length=254) class Country(models.Model): name = models.CharField(max_length=100) class Definition(models.Model): expression = models.ForeignKey(Expression) country = models.ForeignKey(Country) text = models.CharField(max_length=254) class Vote(models.Model): definition = models.ForeignKey(Definition) And this view #views.py def index(request): # Here is where I want to get the queryset return render(request, 'index.html', { 'definitions':definitions) Then in the template the idea is something like this: #index.html Expression is {{ expression }} {% for definition in expressions.definitions_set.all %} Country's "1" top definition for expression is {{ definition }} Country's "2" top definition for expression is {{ definition }} [etc] {% endfor %} How can I get a queryset of definitions that gets only the top definition (by votes) of each country -
Django Rest List() Error with multiple serializers
Im trying to create a Question Model Serializer. The Question model have several other models that inherit from it like RangeQuestion, YesNoQuestion, etc.. This is my view: class QuestionViewSet(generics.ListCreateAPIView): """ A viewset that provides `create` actions. """ queryset = Question.objects.all() def get_serializer_class(self): if 'type' in self.request.data: if self.request.data['type'] == 'range': return serializers.RangeQuestionSerializer elif self.request.data['type'] == 'open': return serializers.QuestionSerializer elif self.request.data['type'] == 'multiple_choice': return serializers.MultipleChoiceQuestionSerializer elif self.request.data['type'] == 'yes_no': return serializers.YesNoAnswerSerializer elif self.request.data['type'] == 'object': return serializers.ObjectQuestionSerializer else: return serializers.QuestionSerializer def create(self, request): if 'type' in self.request.data: serializer = self.get_serializer(data=self.request.data) print serializer serializer.is_valid(raise_exception=True) serializer.save() headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: return Response(status=HTTP_400_BAD_REQUEST, data="Must specify a question type") And this are my serializers: class QuestionSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() def get_type(self): return settings.QUESTION_TYPES['open'] class Meta: model = Question exclude = [] class YesNoQuestionSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() def get_type(self): return settings.QUESTION_TYPES['yes_no'] class Meta: model = YesNoQuestion exclude = [] class RangeQuestionSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() def get_type(self): return settings.QUESTION_TYPES['range'] class Meta: model = RangeQuestion exclude = [] class QuestionChoiceSerializer(serializers.ModelSerializer): class Meta: model = QuestionChoice exclude = [] class MultipleChoiceQuestionSerializer(serializers.ModelSerializer): choices = QuestionChoiceSerializer() type = serializers.SerializerMethodField() def get_type(self): return settings.QUESTION_TYPES['multiple_choice'] class Meta: model = MultipleChoiceQuestion exclude = [] When I acces the url … -
How to used for loop to create table in django form
I wish to have the following table : Brand Total Price A 2 2 T 4 9 I 2 20 B 9 9 Total 17 40 while Brand=['A','T','I','B'];Total=[2,4,2,9] and Price=[2,9,20,9] views.py context['LUnique'] = range(1,LUnique+1) Header.html <div class="col-sm-3"> <table class="table table-bordered " border="1"> <tr><td colspan="4">JUSON Supermart</td></tr> {% for i in LUnique %}<tr><td>{{i.Brand|safe}}</td><td>{{i.Total|safe}}</td><td>{{i.Price|safe}}</td></tr>{% endfor %}</table> </div> Anyone can help me on this because above code not return the table as i wish. -
heroku push rejected due to gdal library
I wanted to deploy my application in heroku. The platform I am using aredjango 1.11, django-rest-framework, postgresql, gis. When I do git push heroku master, I get the following error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. It says to install GDAL and provide GDAL_LIBRARY_PATH. How do i provide the path for it? I have also configured for postgresql heroku addons:create heroku-postgresql:hobby-dev -
Iteration of a formset not working django
I have a question about iterating through a formset that is submitted by a user in order to process the information that is being submitted. I am create the formset in the view and passing it into to html template. Within the same view i am trying to grab the formset and iterate through the forms in order to grab and assign the correct information to the database. I commented where I assigned the formset as well as where i am trying to process it. I just want to iterate though the set. Here is the views.py method: def addTransaction(request, groupId, recordId): user = User.objects.get(username='omar') group = Group.objects.get(id=groupId) record = Record.objects.get(id=recordId) transactions = Transaction.objects.all() if request.method == 'POST': if recocrd.split == 1: form = EvenSplitTransactionForm(request.POST) if form.is_valid(): cd = form.cleaned_data amount = cd['amount'] description = cd['description'] split_amount = SplitEven(record, amount) for trans in transactions: if trans.record.id == record.id: trans.description = description trans.amount = split_amount trans.save() return redirect('group_home', groupId=group.id) if record.split == 2: # this is where i want to iterate though the formset and get the info # that i need from the forms that the user submitted. form = IndividualSplitTransactionForm(request.POST) return redirect('accounts') else: if record.split == 1: form = … -
Django: setting multiple lists in a view for a template to iterate over
I'm trying to create multiple context objects in a view so that I can iterate over them separately in the template and print them vertically as HTML lists. How can I achieve this? My code is something like this: views.py: class MultiListView(ListView): template_name = os.path.join(APPNAME, "list.html") context_object_name = 'list1' context_object_name2 = 'list2' context_object_name3 = 'list3' def get_queryset(self): query_set = List.objects.all() return list(query_set) # Only sets the context_object_name var, not the rest list.html: {% if list1 %} <ul> {% for item in list1 %} <li class="item-list">item.name</li> {% endfor %} </ul> {% endif %} {% if list2 %} <ul> {% for item in list2 %} <li class="item-list">item.name</li> {% endfor %} </ul> {% endif %} {% if list3 %} <ul> {% for item in list3 %} <li class="item-list">item.name</li> {% endfor %} </ul> {% endif %} The important thing for me is that the lists are printed vertically, so each list is it's own column. I am aware that the multiple context_object_name's thing won't work, but I put it in there to demonstrate what I want. -
how to run the django kronos automatically
I want to use django Kronos to compare 'end_date' of Member model and today every 1.a.m. So, I installed 'django-Kronos' and wrote 'Kronos' in installed app. I made the file in my root of the project. from staff.models import Member from datetime import timedelta import datetime import kronos import random @kronos.register('1 * * * *') def the_task(): today = datetime.date.today() Member.objects.filter(end_date__lte=today).update(Membership_status=0) To test, I wrote python manage.py runtask the_task But, CommandError: Task 'the_task' not found happens. How I run the cron.py automatically?? -
One field (ManyToMany) in a Django ModelForm is not saving to database
My app is project management tool where users can add, edit, and view Projects. Projects have titles, summaries, and authors (users). Users have ManyToMany relationships with Projects. Adding new Projects was working fine until I added an edit project view. I can still create a new Project or edit an existing one, and the new title and summary get saved to the database, but the selected authors do not get saved. Note that I can still go into the shell and add authors to a project manually. Here are the Project and User models: class MyUser(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bank_id = models.CharField("researcher's four-letter bank id", null=True, max_length=4, unique=True) #division = models.CharField(max_length=30, blank = True) department = models.CharField(max_length=3, choices=DEPARTMENTS) job_title = models.CharField("job title", max_length=30, choices=JOB_TITLES) citations = models.IntegerField(null=True, blank=True) institution = models.CharField(max_length=30, choices=DEPARTMENTS, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) #history = HistoricalRecords() REQUIRED_FIELDS = ['email'] USERNAME_FIELD = 'username' class Project(models.Model): title = models.TextField('Title') summary = models.TextField('Summary', default=DEFAULT_TEXT) authors = models.ManyToManyField(MyUser) internal_status = models.CharField('Internal Status', max_length = 20, choices = INTERNAL_STATUS, default='wip') external_status = models.CharField('External Status', max_length = 20, choices = EXTERNAL_STATUS, blank=True) mtp_goal = models.CharField(max_length = 50, choices = MTP_GOALS, blank=True) topics = ArrayField(models.CharField('Topics', max_length=30), size=4, null=True) created_on … -
How do I handle the submitted image in dropzonejs?
I have a website that I'm designing the profile pic feature for, I started using dropzonejs and I've read other questions on here like how to add a button to dropzone, which is what I'm trying to do. But even when I don't have a button the profile picture isn't updating when I select the picture. It just sits there in the dragNdrop box This is the code that checks if the user has a picture currently then will display it if they do: <div class="col-md-4"> {% if user.userprofile.img.url is not None %} <img src="{{ user.userprofile.img.url }}" style='height:150px;width:150px' class="hvr-grow"> {% else %} <div class='div-text box-container box' align='bottom'> <div class='box-contents'> <label id='myBtn' class='custom-file-upload'>Upload</label> </div> </div> </div> Here's my HTML/javascript that limits the amount of uploaded pic to one: <!-- for limiting file upload to 1 file --> <script type='text/javascript'> autoProcessQueue: false Dropzone.options.myAwesomeDropzone = { accept: function(file, done) { console.log("uploaded"); done(); }, init: function() { this.on("addedfile", function() { if (this.files[1]!=null){ this.removeFile(this.files[0]); //document.getElementById('submitBtn').style.visibility = "visible"; } }); } }; </script> <!-- Modal --> <div id="picModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close"></span> <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="myAwesomeDropzone">{% csrf_token %} <input id='file-upload' type='file' name='uploaded_image'/> {{form}} </form> </div> </div> … -
Using the PATCH method with Django Rest Framework
I have a Django Rest Framework set up and I'd like to be able to send PATCH requests to it that update a specific field. I looked at some previous posts and incorporated the partial update code in my view: class RequestViewSet(viewsets.ModelViewSet): queryset = Request.objects.filter(done = False).order_by('-time') serializer_class = RequestSerializer paginate_by = None def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) When I try to run curl requests using PATCH, though, the object doesn't get updated. Here's an example of curl I was using: curl --data '{"request": "foo"}' -X PATCH http://127.0.0.1:8000/api/request/1/ In the terminal, it returns the original, unmodified object. Is there a different way to set up the Model ViewSet to accept partial updates via PATCH? -
Missing staticfiles manifest entry in Django deployment using Heroku
I am trying to deploy my webapp to heroku. I am using Django and the following is most of my settings.py file: """ Django settings for blog project on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url import raven # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) try: from .local_settings import * except ImportError: pass # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'blogapp', 'homeapp', 'nimfksapp', 'omniclipapp', #Heroku Sentry 'raven.contrib.django.raven_compat', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog.urls' WSGI_APPLICATION = 'blog.wsgi.application' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "live-static", "media-root") # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When running collectstatic locally … -
Requesting help creating a custom Wagtail plugin
I'm creating a simple plugin to collapse and sort any stream object and have selective grouping. (this is different than Condensed Inline Blocks) I added Jquery Sortable functionality which works great, but the problem Is that I need to change the Id prefixes along with all the inner ones when they swap positions in order to properly save and not mess up the database. I looked through all the js files to find the function that is used when clicking the sort buttons. In the file 'sequence.js' there is a bunch of functions (moveUp/moveDown...etc) though I don't know how to call the methods on a specific stream object since my javascript knowledge is a bit lacking. This is probably a stupid, but I hope I could sort this out, it's been bugging me. I appreciate any sort of help and I plan on releasing this once I get the code cleaned up. (function($) { window.SequenceMember = function(sequence, prefix) { var self = {}; self.prefix = prefix; self.container = $('#' + self.prefix + '-container'); var indexField = $('#' + self.prefix + '-order'); self.delete = function() { sequence.deleteMember(self); }; self.prependMember = function(template) { sequence.insertMemberBefore(self, template); }; self.appendMember = function(template) { sequence.insertMemberAfter(self, template); … -
D3 / Django - How to write code in JS file with named URLs [duplicate]
This question already has an answer here: How do I return the response from an asynchronous call? 22 answers I'm trying to build d3 graphs with backend data provided by Django Rest Framework. I want to write my d3 / js code in separate javacript file instead of cramming everything in HTML. I can pass Django named URLs in HTML file but JS file doesn't accept this named URL. I'm planning to pass the whole data into a variable which contains the data in HTML and then reference it to JS file. My code in HTML: <script> var dataToPlay d3.json("{% url 'list-create-financial-data' %}", function (data) { dataToPlay = data }); console.log(dataToPlay) </script> But this var dataToPlay is not available outside the function. How can I make it available in separate JS file? -
pytest can't access django classes
I have a Django application, working fine. When I run the tests with pytest, it only works with utility classes (so not Django related). For example, a test from package A calling an utility class from this package, or another, works fine. However, I'm facing an error as soon as I import a django class. example 1 : I import my model (in the test), starting the test class with : from app.common.models import Country --> ImportError: No module named django.db [django.db is called in models.py] example 2 : I import an url resolver (in the test), starting the test class with : from django.core.urlresolvers import reverse --> ImportError: No module named django.core.urlresolvers first try of fix Following another topic, I set the content of PYTHONPATH : /home/user/pyenv/lib/python3.5/site-packages This folder contains installed packages in the virtualenv : django, pytest, psycopg2, and more. 1) If I set DJANGO_SETTINGS_MODULE to the same file as the application, "py.test" gives this error ending with : File "/home/user/pyenv/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 24, in raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) 2) If I set DJANGO_SETTINGS_MODULE to a smaller test setting file, containing only the database infos, I face a different error (self.client failing in a test) … -
A trouble with Django models and index_together feature
Create a Django project with an app (add it to INSTALLED_APPS!) with the following models.py: from django.db import models class BaseTransaction(models.Model): pass class SubscriptionTransaction(BaseTransaction): class Meta: index_together = ["id", "canceled"] canceled = models.BooleanField() Then the things work this way: $ python3 manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: testprj.SubscriptionTransaction: (models.E016) 'index_together' refers to field 'id' which is not local to model 'SubscriptionTransaction'. HINT: This issue may be caused by multi-table inheritance. Please explain the reason of this error (there is no multi-table inheritance here) and how to make my code to work. The problem happens with Django 1.10.3 with both Python 3.5.3 and Python 2.7.13. Is it a Django bug? What's about a workaround? -
What would be the format of urls.py for class based views?
I am new to django so i want to know how to write urls.py for a project. I want to make backend api for inventory management system.I am having following error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: The current path, inventory_backend/dep/, didn't match any of these. My code for mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^inventory_backend/', include('inventory_backend.urls') ), url(r'^admin/', admin.site.urls) , ] inventory_backend/urls.py: from inventory_backend.views import DepartmentsView,InventoriesView from rest_framework import routers router = routers.SimpleRouter() router.register(r'dep/',DepartmentsView ) router.register(r'inv/',InventoriesView ) urlpatterns = router.urls -
Group list items by field value in the Django admin
I'm trying to group the items in the Django admin app by a specific field (e.g. date). So I've added to the queryset in admin.ModelAdmin.getQueryset() the following: queryset = queryset.values('date').annotate(Sum('amount')) But this doesn't work because in this case, a dict is returned instead of a queryset. I started exploring what's inside the django/contrib/admin folder, and I think something need to be done before sending the object to the template change_list.html. I'm not sure but I think the class in views/main.py (admin folder) might need some change. Can anybody confirm that what I'm trying to do is achievable at all? -
How to print pretty JSON on a html page from a django template?
Why is it that in python, I can pretty print JSON with the python example below, but in a django template, it doesn't work? How can I pretty print JSON in a django template? python: import requests, json url = 'https://api.example.com/details' r = requests.get(url) json_data = r.json() json_pretty = json.dumps(json_data, sort_keys=True, indent=4) print (json_pretty) django views.py: def json_list(request): url = 'https://api.example.com/details' r = requests.get(url) json_data = r.json() json_pretty = json.dumps(json_data, sort_keys=True, indent=4) context = { "json_pretty": json_pretty, } return render(request, "json_output.html", context) template: <div>{{ json_pretty }}</div> -
D3 / Django - How to write code in JS file with named URLs [duplicate]
This question already has an answer here: How do I return the response from an asynchronous call? 22 answers I'm trying to build d3 graphs with backend data provided by Django Rest Framework. I want to write my d3 / js code in separate javacript file instead of cramming everything in HTML. I can pass Django named URLs in HTML file but JS file doesn't accept this named URL. I'm planning to pass the whole data into a variable which contains the data in HTML and then reference it to JS file. My code in HTML: <script> var dataToPlay d3.json("{% url 'list-create-financial-data' %}", function (data) { dataToPlay = data }); console.log(dataToPlay) </script> But this var dataToPlay is not available outside the function. How can I make it available in separate JS file? -
Django: TypeError at /categories/ sequence item 0: expected str instance, Category found
I'm trying to code an e-phrasebook with Django to help people learn languages. Or actually a new version of an older one with new features. Anyway I'm badly stuck on the first meters here. I have added some objects to the database and want to show them at the "categories" url. The first url http://127.0.0.1:8000/ works nicely and gives me a wonderful hello world. However, I need to connect the new app to the project, and when I try to open the url of the app http://127.0.0.1:8000/categories/, the browsers gives me this: TypeError at /categories/ sequence item 0: expected str instance, Category found My console complains about app's view.py, and within that about line 9 output = ', '.join(categories). I can't find anything wrong with it. Here is the whole views.py: from django.http import HttpResponse from django.shortcuts import render from .models import Category def category_list(request): categories = Category.objects.all() output = ', '.join(categories) return HttpResponse(output) This is the app's url.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.category_list), ] Here is the main url.py: from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^categories/', include('phrasebooktwo.urls')), url(r'^admin/', admin.site.urls), url(r'^$', views.hello_world), …