Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dictionary update error in Django's ContextDict
Any idea where this error comes from? Python 3.4.2 Django 1.10.8 Method: POST Traceback as text (to find it if somebody else may search for it): ValueError: dictionary update sequence element #0 has length 0; 2 is required File "django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 215, in _get_response response = response.render() File "django/template/response.py", line 109, in render self.content = self.rendered_content File "django/template/response.py", line 86, in rendered_content content = template.render(context, self._request) File "django/template/backends/django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "django/template/context.py", line 267, in make_context context.push(original_context) File "django/template/context.py", line 59, in push return ContextDict(self, *dicts, **kwargs) File "django/template/context.py", line 18, in __init__ super(ContextDict, self).__init__(*args, **kwargs) -
django-tables2 'list' object has no attribute 'prefixed_order_by_field'
I'm working with Django-tables2. I can display a table using a model but can't get one to display using data. I know I have to have an order_by when using data. I'm not clear, on where and how. view def dictfetchall(cursor): desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def Users(request): data = dictfetchall(cursor) table = ProjectTable(data) RequestConfig(request, paginate={"per_page": 4}).configure(data) return render(request, 'JiraAdmin/index.html', {'table': table}) table.py class ProjectTable(tables.Table): name = tables.Column(verbose_name='Role') lead = tables.Column(verbose_name='Lead') display_name = tables.Column(verbose_name='User) class meta: attrs = {'class': 'paleblue'} attrs = {'class': 'table table-responsive', 'width': '100%'} template {% render_table ProjectTable %} -
Setting id columns with Django tables
I have a table: class Table(tables.Table): actions = tables.TemplateColumn(...) class Meta: model = SomeModel fields = ['field1', 'field2', 'field3', 'field4', 'field5', 'field6'] attrs = {"id": 'id', 'class': 'class'} I know that I an always change the row names: col_attrs = { 'data-id': "adsas" } which would make: <table> <tr id="adsas"> <td>.. <td>.. </tr> <tr id="adsas"> <td>.. <td>.. </tr> </table> But unfortunately, I didn't find a similar thing for rows, I want to have this: <table> <tr> <td id="0">.. <td id="1">.. </tr> <tr> <td id="0">.. <td id="1">.. </tr> </table> Can someone show me how can I make a similar structure, or at least what attr to use for it ? -
Django Form Error: Select a valid choice. ... is not one of the available choices
I am trying to create a dynamic choice field. I have a view that creates a list of tuples. The first value of the tuple is the primary key of the object ServiceWriter while the second value is the name of the ServiceWriter. The list then gets passed into the form class. When I make the selection and submit the page the form is decided to be not valid and the following form error is printed in the shell: "Select a valid choice. (First value of tuple. ie 1,2,3..) is not one of the available choices." forms.py class CreateAdvancedRO(forms.Form): service_writer = forms.ChoiceField() def __init__(self, writer_choices, *args, **kwargs): super(CreateAdvancedRO, self).__init__(*args, **kwargs) self.fields['service_writer'].choices = writer_choices self.helper = FormHelper() self.helper.form_id = 'id-create-advanced-ro' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Open Repair Order')) Note: I am not using a ModelForm. views.py class CreateAdvancedRO(View): form_class = CreateAdvancedRO writer_form = CreateServiceWriter add_line_form = AddJobLine def post(self, request): writer_choices = [] form = self.form_class(writer_choices, request.POST) print(form.errors) if form.is_valid(): '''Do something''' else: writer_choices = [] try: writers = ServiceWriter.objects.filter(user=request.user) for writer in writers: writer_choices.append((str(writer.id), writer.name)) except ObjectDoesNotExist: pass form = self.form_class(writer_choices, request.POST) writer_form = self.writer_form() add_line_form = self.add_line_form() return render(request, 'free/advanced_create.html', {'form': form, 'writer_form': wri 'add_line_form': add_line_form}) I have tried both … -
how to run python file on button click (html) in django
i want to execute .py file on button click (html) in django. function clickfun() { exec('home/hello.py'); } <button type="submit" onclick="clickfun()">Process</button> error: (index):10 Uncaught ReferenceError: exec is not defined at clickfun ((index):10) at HTMLButtonElement.onclick ((index):57) --------------uing AJAX-------------- function clickfun() { $.ajax({ url : 'http://127.0.0.1:8000/hello.py', type : 'POST', success : function (result) { console.log (result); // Here, you need to use response by PHP file. alert('a'); }, error : function () { console.log ('error'); alert('a1'); } }); } and while using ajax receiving following error: POST http://127.0.0.1:8000/hello.py 404 (Not Found) -
GET is going to incorrect URL
I'm learning the ropes of Django and perhaps i'm not understanding the URL routes correctly, but everything i've tried I can't get one form to send the GET to another URL. I would think it was more straight forward. I tried this suggestion, but apparently it wouldn't change the URL route or provide the correct request.POST.getlist: Ajax Call not being passed, POST.request shows as None. I am attempting to pass all of my check box selections to a new view. I have the view part working if I manually type the URL in and get the results in account/requestacess with request.GET.getlist, but when I hit my submit button the current URL is populated instead of where I want to go, which is account/requestaccess. my button is defined as: <button href="{% url 'requestaccess' %}" class="btn btn-primary" input type = "submit"> Request Access</button> my form is defined as: <form action "{% url 'requestaccess' %}" form method = "GET"> When I push the button depending on what is selected my profile URL is populated as such: http://127.0.0.1:8000/account/profile/?report_id=75&report_id=79&report_id=41&report_id=31 I want my /account/request URL to have the ?report_id= in it not the account/profile URL. My URL.py is defined as: url(r'^profile/$', views.profile, name='profile'), url(r'^requestaccess/$', views.requestaccess, name='requestaccess') -
Django model TextField not rendering
I've been trying to render the contents of a TextField onto my HTML page, but it's the only thing that just refuses to render. Here is my model: class Section(models.Model): order_id = models.IntegerField() SECTION_TYPE_CHOICES = (('reg', 'regular'), ('not', 'note'), ) section_type = models.CharField( max_length=5, choices=SECTION_TYPE_CHOICES, default='reg', ) class TextSection(Section): contents = models.TextField(blank=True, max_length=5000) class Post(models.Model): post_id = models.IntegerField(unique=True) author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) slug = models.CharField(unique=True, max_length=20) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) belongs_to = models.ForeignKey('Story') order_id = models.IntegerField() contents = models.ManyToManyField(Section, blank=True) and the template {% extends 'stories/base.html' %} {% block title %} {{ post.belongs_to.title }} | {{ post.title }} {% endblock %} {% block content %} <!-- Story Information --> <div> <h1>{{ post.title }}</h1> <p>by {{ post.author }} on {{ post.published_date }}</p> </div> <!-- Post Contents --> <div> {% for section in post.contents.all %} <div> <p>{{ section.contents|safe }}</p> {{ section.order_id }} </div> {% endfor %} </div> {% endblock %} It always renders the section.order_id but never renders the section.contents Thanks in advance for any advice. -
Install Django + Postgresql with Gunicorn in Ubuntu Server
I need to mount a Django Server in a computer with Ubuntu Server. This computer gonna be in local network with other computers with Windows. I know that the best way is using Gunicorn and Nginx but I'm not sure about how to do this. Sorry if i am not very specific. Thanks! -
Passing data through views context to javascript in Django
I'm trying to pass some data from the views.py to a template and using it in a javascript and I can't make it work. Does anyone know how can I solve this? In the views.py listaUsuarios = User.objects.values_list('username', flat=True) context = {'listaUsuarios':listaUsuarios} return render(request, redirect, context) This actually works and if I do a print(listaUsuarios[2]) it shows just the username number 2 in the database. The javascript in the template function checkForm(form) { for (i = 0; i < listaUsuarioss.length; i++) { if(form.username.value==listaUsuarioss[i]){ alert("Error: El nombre de usuario ya está en uso"); form.username.focus(); return false; } } } The invocation to the script <form method="post" action="{% url 'register' %}" onsubmit="return checkForm(this,{{listaUsuarios}});"> I know I should have used Django forms for the registration but I didn't and I'm trying to make this work for checking before the registration of a new user if that username is already in use. Thank you to everyone! -
Changing '?' to '&' in adress bar
For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name. More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name. If i don't click SAVE, just refresh page, i'm getting error 404. How can it be possible? P.S My view function @check_document_access_permission() def notebook(request, is_embeddable=False): if not SHOW_NOTEBOOKS.get(): return serve_403_error(request) notebook_id = request.GET.get('notebook', request.GET.get('editor')) is_yarn_mode = False try: from spark.conf import LIVY_SERVER_SESSION_KIND is_yarn_mode = LIVY_SERVER_SESSION_KIND.get() except: LOG.exception('Spark is not enabled') return render('notebook.mako', request, { 'editor_id': notebook_id or None, 'notebooks_json': '{}', 'is_embeddable': request.GET.get('is_embeddable', False), 'options_json': json.dumps({ 'languages': get_ordered_interpreters(request.user), 'session_properties': SparkApi.get_properties(), 'is_optimizer_enabled': has_optimizer(), 'is_navigator_enabled': has_navigator(request.user), 'editor_type': 'notebook' }), 'is_yarn_mode': is_yarn_mode, }) -
Django RangeField - lookups doesn't work as expected
Can't figure out how to do lookups on DateRangeField properly. I will show my cases on numbers: Let's say my object (trip) has range <5,10> I need to be able to filter other trips which: Overlaps this object on the beginning - (-inf,4> to <5,10> (eg. <3,5>,<4,8> etc.) Overlaps this object from the end - <5,10> to <11,inf> Daterange is contained by given objects daterange - <5,10> to <5,10> Daterange contains given objects daterange - (-inf,4> to <11,inf) For now, I'm using two dates in my model. date_from and date_to so lookups are like this: Trip.objects.filter(user=trip.user, date_from__lt=trip.date_from, date_to__gte=trip.date_from,date_to__lte=trip.date_to) Trip.objects.filter(user=trip.user, date_from__gte=trip.date_from, date_from__lte=trip.date_to, date_to__gt=trip.date_to) Trip.objects.filter(user=trip.user, date_from__gte=trip.date_from, date_to__lte=trip.date_to) Trip.objects.filter(user=trip.user, date_from__lt=trip.date_from, date_to__gt=trip.date_to) To simplify lookups and forms I'm trying to change date_from and date_to to daterange. But lookups doesn't work as I expected: class OverlappingTripsTestCase(TestCase): def setUp(self): self.city = City.objects.create(place_id='xxx',name_en='xxx') self.user = User.objects.create(username='testuser') self.base_trip = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 2), date(2010, 10, 1))) self.trip_contains = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 1), date(2010, 12, 1))) self.trip_contained_by = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 2, 1), date(2010, 9, 1))) self.trip_overlap_start = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2009, 1, 1), date(2010, 2, 1))) self.trip_overlap_end = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 1), date(2010, 10, 1))) def test_overlaps(self): self.assertEqual(Trip.objects.filter(daterange__contains=self.base_trip.daterange).first().pk,self.base_trip.pk) self.assertEqual(Trip.objects.filter( daterange__contained_by=self.base_trip.daterange).first().pk,self.trip_contained_by.pk) Even the first assertion doesn't work because it returns 0 results. … -
Which IDEs are most suited for Django to build a web application?
I am a beginner. I choose Python as my first programming language because I love computer science. I learn to code by myself. I am using Eclipse to build my first Django website. I really want to know the best IDEs to work with Django. P/s: Excuse me about my writing English. Here is the first time I ask a question on Stack Overflow. I really appreciate any help you can provide. -
Django - Reducing duplicate context code in the view
Say I have a view function like so: def check_view(request): if user.is_authenticated: ... return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variablec':c} else: ... return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variabled':d} Is there any way to only write the context variables just one time (given that there some similar variables for both conditions), but the variables that are different can be written under their own parent conditions? So variable C will belong to the if statement and D to the else, whereas both variables A and B can be written once but apply to both the if and else statement.... Note how the last variable for each condition is different (c and d) Thanks -
How can I get the OneToOne relationship easily?
I have two model, names User and Account, the Account to User is one to one relationship: class User(AbstractUser): real_name = models.CharField(max_length=12, null=True,blank=True) phone = models.CharField( max_length=11) email_is_validated = models.BooleanField(default=False) qq = models.CharField(max_length=10, null=True, blank=True) class Account(models.Model): user = models.OneToOneField(to=User) balance = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) total_charge = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) total_consume = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) So, in this case, in my serializer: class OrderCreateSerializer(ModelSerializer): def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "user"): user = request.user I get the user, can I use user.account to get the account? and or whether I need to do something in User model, such as user @property. (those are my whimsical idea) Or is there a convenient way to get the user's account instance? -
Django Users not showing the date_of_birth in the admin site
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following: forms.py: class UserRegisterForm(UserCreationForm): date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1))) email = forms.EmailField(required=True) def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username already exists') return username def clean_date_of_birth(self): ''' Only accept users aged 13 and above ''' userAge = 13 dob = self.cleaned_data.get('date_of_birth') today = date.today() if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day): raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge)) return dob def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_password2(self): ''' we must ensure that both passwords are identical ''' password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords must match') return password2 class Meta: model = User fields = ['username', 'email', 'date_of_birth', 'password1', 'password2'] views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') date_of_birth = form.cleaned_data.get('date_of_birth') new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) message = render_to_string('email_activation_link.html', { 'new_user':new_user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk)), 'token': … -
django can't visit "models class object" object
My English is poor,maybe my descriptions were have many grammar wrong. My Pycharm told me a error.Pycharm can not let me visit models class object object. But,The code can run.I very confuse.Thanks everybody This is view.py This is models.py The code can run,and I use Python3.6 and Django 1.11.7.Pycharm version is 2017.4 pro -
How to show two onetoone related tables in django admin?
My two models are: class User(AbstractUser): ##all user related infos class Payment(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='payment') Now my admin.py is like class PaymentAdmin(admin.ModelAdmin): list_display = ('id', 'chargebee_customerid') search_fields = ('id',) ordering = ('id',) def get_search_results(self, request, queryset, search_term): if search_term: queryset = self.model.objects.filter( Q(id__contains=search_term) ) return queryset, False return queryset, False I want to show both tables side by side like first the payment table then after that user table. How can I do that. -
Sending email with render template but doesn't work
I use this function to send email, but it works only when i use the message with text. With template html, the function cause a problem ( the emails aren't sent but without display of any error). I try to resolve this problem but i couldn't find the error The template: <!DOCTYPE html> <html> <head> <title>Backtest ready</title> </head> <body> <p> Dear {{ user.username }}, <br> <br> Your backtest {{ backtest.title }} is now ready! <br> <br> In order to see the details of your strategy, visit the following link : <br> <br> http://104.131.14.247{{ result_url }} <br> <br> If you would like to check all the backtests you performed so far, go to <a href="{% url 'backtest_result_list' %}"> my backtests</a>. def send_email_with_backtest_result(request, backtest): user= request.user subject = 'Your backtest results' result_url = reverse('backtest_result_detail', kwargs={'backtest_id': backtest.id}) if backtest.user.is_active: template = get_template('interface/emailbacktest.html') context = Context{'user': user, 'backtest': backtest, 'result_url': result_url} msg = template.render(context) # msg = 'http://104.131.14.247{}'.format(result_url) else: # this will act as a result page and user activation token = backtest.user.create_activation_token() msg = 'http://104.131.14.247{}?token={}'.format(result_url, token) send_mail(subject, msg, settings.DEFAULT_FROM_EMAIL, [backtest.user.email]) def store_backtest_result(path, backtest_id): backtest = BackTest.objects.get(uid=backtest_id) file_path = extract_result(path, backtest_id, settings.BACKTEST_RESULTS_FOLDER) backtest_result = BackTestResult(backtest=backtest, path=file_path) backtest_result.save() backtest.results_status = 'cl' backtest.save() send_email_with_backtest_result(request, backtest) backtest.user.notify_backtest_result(backtest) … -
Django rest framework - Model serialization raise not JSON serializable
Hello I'm facing a problem with serializing a list of models. So I have a FileInfo model and I also have a UserFileInfo model which contains a ForeignKey to FileInfo. When I try to serialize a QuerySet of UserFileInfo I can do it and it also serialize the nested FileInfo. But when I try to serialize a FileInfo QuerySet it failes with the following error: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: FileListSerializer(, ]>): file_name = CharField(max_length=100) file_path = CharField(allow_blank=True, allow_null=True, max_length=150, required=False) file_token = CharField(allow_blank=True, max_length=100, required=False, validators=[]) created = DateTimeField(read_only=True) is_available = BooleanField(required=False) is not JSON serializable I tried to remove fields to eliminate a problem with one of the fields but with only fields = ('id') it also fails. Tried to serialize a single FileInfo, fails. Tried creating a ListSerializer, fails. Would appreciate any help, below are code samples: The model: class FileInfo(models.Model): file_name = models.CharField(max_length=100, blank=False) file_token = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) file_path = models.CharField(max_length=150, blank=True, null=True, default="") created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) is_available = models.BooleanField(default=True) groups = models.ManyToManyField(Group, related_name='groups', null=True, blank=True) def __unicode__(self): return self.file_name The file serializer: class FileSerializer(serializers.ModelSerializer): created_by = UserSimpleSerializer() class … -
form not saving form.is_valid() returning false
below is all my models basically this is an auction website class Item(models.Model): name = models.CharField(max_length = 30) description = models.TextField() image = models.ImageField(upload_to='media/') category = models.CharField(max_length=100) ask = models.DecimalField(default=0, max_digits=6, decimal_places=2) created_at = models.DateTimeField(default=datetime.now, blank=True) closes = models.DateTimeField() class Bid(models.Model): item = models.ForeignKey(Item) user = models.ForeignKey(User) price = models.DecimalField(default=0, max_digits=6, decimal_places=2) created_at = models.DateTimeField(default=datetime.now, blank=True) this is the form class itemform(ModelForm): class Meta: model = Item fields =['name','description','image','category','ask','closes'] view for saving the form def createitem(request): if request.method == "POST": form= itemform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/items') else: form = itemform() return render(request, 'app/create.html', {'form':form}) create.html {% extends 'app/layout.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <button type ="submit">Save</button> </form> {% endblock %} it would also be helpful if someone could help me making a view of details of the of the items as i have to show this by end of the weekend -
using django on heroku, connect to AWS S3
Hi I'm trying to use S3 on heroku(making Django App) as a storage to save PDF files to view on the page. I saw instructions on heroku to connect S3 to heroku and finished setting with $ heroku config:set AWS_ACCESS_KEY_ID =xxx AWS_SECRET_ACCESS_KEY =yyy Adding config vars and restarting app... done, v21 AWS_ACCESS_KEY_ID => xxx AWS_SECRET_ACCESS_KEY => yyy $ heroku config:set S3_BUCKET = zzz Adding config vars and restarting app... done, v21 S3_BUCKET => zzz Do i need to write AWS ACCESS ID and SECRET KEY to settings.py? -
django - Is it possible to access multiple databases without declaring in settings.py file?
Every time a Company is created I want to create an individual database to store corresponding values. models.py(company App) class Company(models.Model): name = models.CharField(max_length=30) user = models.ForeignKey(User) views.py (company App) class AddCompany(LoginRequiredMixin, CreateView): mode = Company form_class = AddCompanyForm template_name = "add_company.html" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } models.py(Inventory App) class Inventory(models.Model): item = models.CharField(max_length=30) quantity = models.IntegerField(null=False) company = models.ForeignKey('company.Company') views.py(Inventory App) class AddToInventory(LoginRequiredMixin, CreateView): model =Inventory form_class = AddToInventoryForm template_name = "add_inventory.html" Is it possible to access a database without declaring the database in settings.py file and without using any routes. I want the items belonging to each company to be stored in a separate database if the database of company does not exist then a new database has to be created and I have to be able to read and write data from the databases without using any routes. Is it possible to do something like with django by using some SQLAlchemy? Is this even possible with django? -
Django query table to find Item that only exist in Parent field
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field. This is the models. class Item(models.Model): text = models.CharField() class ItemRelations(models.Model): child = models.ForeignKey('Item', related_name='itemchild') parent = models.ForeignKey('Item', related_name='itemparent') So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent. I tried so many different ways. I want to accomplish something like this. firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self) Is it possible. Or does one have to make several queries and loops to manage this? -
Optimizng pattern of loading Django template filters in a for loop
In a Django template of mine, I use a for loop to display content. The content itself is of 3 types, each requiring its own set of conditions, HTML and CSS. I felt including all that processing in 1 template would make it tough to maintain the file, so instead I'm using template tags: {% load get_display_type_1 %} {% load get_display_type_2 %} {% load get_display_type_3 %} {% for item in content %} {% if item == '1' %} {% display_type_1 payload='foo' %} {% elif item == '2' %} {% display_type_2 payload='bar' %} {% elif item == '3' %} {% display_type_3 payload='foo bar' %} {% endif %} {% endfor %} And where, for example, the template tag called display_type_1 has the following code: from django import template register = template.Library() @register.inclusion_tag(file_name='display_type_1.html') def display_type_1(payload): return {'payload':payload} Standard stuff so far. But now take a look at the HTML template connected to the template tag: {% load myfilter %} <div class="type1">{{ payload|myfilter }}</div> I.e. notice I'm loading a custom filter called myfilter here. So here's the problem: in essence, I've called {% load myfilter %} within a for loop. How? Because the template tag itself resides in the parent template's for loop. This … -
ERROR: ' No module named 'django.core.urlresolvers'
I am trying to create web services using the Django Rest framework.While running the server, when I try to access the admin page, I get the following error: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers' Note: I have added the rest_framework on the settings.