Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django use processes or threads to handle user requests in view?
Does Django use processes or threads to handle user requests in view? If Django uses threads I can't to use all CPU cores(python global interpreter lock), if Django uses processes I can't with no worry share memory. I tried to find the info in google, but maximum that I have managed to find is Did django use thread to handle requests? This seems isn't a answer. -
Djano endless(el) pagination not working
i am using django-el-pagination Twitter style However i am not able to obtain the desired pagination on scroll feature this is my page_template {% load el_pagination_tags %} {% lazy_paginate parent_list %} <ul> {% for items in parent_list %} <li>{{ items }}</li> {% endfor %} </ul> {% show_more "even more" %} ` This is my main template <div class="endless_page_template"> {% include page_template %} </div> {% block js %} {{ block.super }} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{{ STATIC_URL }}el-pagination/js/el-pagination.js"></script> <script> $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 200 }); </script> {% endblock %} -
Modal opens only after clicking twice when submitted for the first time from a button
I have a modal popup to be opened from a button click. Unfortunately, I'm able to see the popup only after clicking twice when it is submitted for the first time in the browser. But once the popup is opened and closed, I'm able to open the modal with a single click on the next attempts. The same happens if I refresh my browser. This looks strange. Any body can explain, why? I have the following code, Button html: <div><button class="btn btn-danger btn-sm" ng-disabled="{{update_problem_description_disabled}}" ng-click="siverifyAddReviewModal()"><i class="glyphicon glyphicon-edit"></i> Edit Review </button> </div> Modal html: <div class="modal-header container-fluid"> {% include "siverify_modal_header.html" %} </div> <form class="well form-horizontal" name="addReviewForm"> {% csrf_token %} <div id="form-modal-body" class="modal-body"> {% verbatim %} <table class="table" style="width:90%"> <tr> <th><label>Review Title/Purpose*</label></th></br> {% endverbatim %} <td><input type="text" class="col-md-10" maxlength="256" ng-model="arform.revtitle" value="arform.revtitle" required/></td> <!--<td><input type="text" class="col-md-10" maxlength="256" ng-init="'{{reviewtit}}'" ng-model="arform.revtitle" > {{reviewtit}} </td>--> </tr> <div class="modal-footer"> <button type="submit" class="btn btn-primary" ng-disabled="addReviewForm.$invalid || rev_submit_disabled" ng-click="addReview(arform)">Save</button> <button type="button" ng-click="cancel()" class="btn btn-small btn-warning">Cancel</button> </div> </form> -
PyCharm giving Static path imports errors when using Docker
PyCharm does not recognise any paths to Static files when running in Docker interpreter environment. If I run the same project in local virtualenv path is recognised. Also PyCharm recognise module imports in Docker environment without any issues. For example > <!-- This file stores project-specific CSS --> <link href="{% static 'css/project.css' %}" rel="stylesheet"> {% endblock %} Gives error --> Unsolved template reference "css/project.css" This path actually exists in the project and CSS gets applied on the application without any issues. I get the same error (wich I have no suppressed to warning) with all static paths including, js files, and images. It's annoying problem as PyCharm is generally really good in auto-populating paths.If someone had this before please advice, else I open a ticket with IntelliJ and update the answer for all to use. Below my PyCharm project settings for running Django with Docker in the IDE. Here are also my static file settings in Django --> # See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs CRISPY_TEMPLATE_PACK = 'bootstrap4' # STATIC FILE CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR('staticfiles')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( str(APPS_DIR.path('static')), ) # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # … -
Celery, Group task AttributeError: 'NoneType' object has no attribute 'app'
I am trying to run a group of celery tasks as follows: @shared_task def run_sms_task(smstask_id): smstask = SmsTask.objects.get(id = smstask_id) if smstask: phones = [] for user in smstask.userlist.users.all(): phones.append(user.profile.phone) g = group(send_sms_async(phone, smstask.text) for phone in phones) g.apply_async() smstask.status = 3 smstask.save() The task is executed partly and in the end throws following error: python3.5/site-packages/celery/canvas.py", line 560, in app return self._app or (self.tasks[0].app if self.tasks else current_app) AttributeError: 'NoneType' object has no attribute 'app' You are welcome to help! Thank you! -
Models and Apps in Django
I am creating a Django Project . It has n number of Apps in it . Also it has different models . A model will have to be defined in an App . But the apps are interrelated . So a model defined in one app can also be used in another app . So how to decide where to put a particular app ? -
desktop app interacting with django app: authentication
I have a django web application which allows users to run various workflows on uploaded datasets. Additionally, I have a desktop utility, written in python, which should allow the user to upload the datasets. The reason I have this separation is that there is a lot of pre-processing that has to be performed on the datasets and for security and confidentiality reasons, it is vital that the datasets are not uploaded without these pre processing steps. My idea was to write a simple GUI app which lets a user selects the data directory, perform the pre-processing magic and upload the transformed data (somehow) to the server for further post processing. My problem is that I have no idea how I can geta stand-alone python app to interact with the django application. The first issue is that only authenticated users should be able to upload the datasets. So, assuming I get a user to input the username and password, how can I authenticate it with the django app? -
Defining custom delimiter for Django GROUP_CONCAT simulator
class Concat(Aggregate): # supports COUNT(distinct field) function = 'GROUP_CONCAT' template = '%(function)s(%(distinct)s%(expressions)s)' def __init__(self, expression, distinct=False, **extra): super(Concat, self).__init__( expression, distinct='DISTINCT ' if distinct else '', output_field=CharField(), **extra) I have come across a splendid answer in Stackoverflow which provided a Django solution to simulate MySQL's GROUP_CONCAT. And now I am wondering how to set a delimiter for it in Django. I tried many possible options, among them '%(function)s(%(distinct)s% ", "(expressions)s)', but none of my attemps were successful. Any ideas ? -
Python 2: why does one file not read the other?
I have two .py files; Dashboard.py and Clock.py. When I run Dashboard.py i want it to run the code in Clock.py. I keep getting the error: NameError: name 'Frame' is not defined. However when I put the Class in the same file as the dashboard it works fine. What I am trying to do essentially is create a modular system where I have different frames in separate files and I can add the those frames to the main dashboard window if and when needed. Is there a way to do this? Dashboard.py: from Tkinter import * from Clock import * class FullscreenWindow: def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background = 'black') self.middleFrame = Frame(self.tk, background = 'blue') self.bottomFrame = Frame(self.tk, background = 'green') self.topFrame.pack(side = TOP, fill=BOTH, expand = YES) self.middleFrame.pack(side = TOP, fill=BOTH, expand = YES) self.bottomFrame.pack(side = TOP, fill=BOTH, expand = YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) #clock self.clock = Clock(self.topFrame) self.clock.pack(side=RIGHT, anchor=NE, padx=25, pady=25) def toggle_fullscreen(self, event=None): self.state = not self.state self.tk.attributes("-fullscreen", self.state) return "break" if __name__ == '__main__': w = FullscreenWindow() w.tk.resizable(width=False, height=False) w.tk.geometry('1280x720') w.tk.mainloop() Clock.py: import time class Clock(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, bg = 'black') # initialize date … -
Deferred foreign key 'OrderPayment.order' has not been mapped
I'm trying to integrate django-shop with a simple django installation but it gives my following error : django.core.exceptions.ImproperlyConfigured: Deferred foreign key 'OrderPayment.order' has not been mapped I even tried creating the OrderPayment model as referred in docs as below but still I got no luck. class OrderPayment(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') order = models.ForeignKey(on_delete=models.deletion.CASCADE, to=Order, verbose_name='Order') class Meta(): verbose_name = "Order Payment" -
What are swappable models in django?
Hello I am new to django. I have came across the term Swappable model, while reading about django models. I am not able to find the significance of Swappable model. I have also inspected Model._meta object. It contains a member attribute swappable, which is None by default. I have tried to search documentation. I have also googled out, but couldn't find any reference to swappable model. Thanks in advance. -
Page not rendering because of url
I want to make contact page is made of simple template html. in view.py i made this from .models import tutorials from django.views import generic class Contactviews(generic.View): template_name = 'home/contact.html' and this is my url: url(r'^contact$',views.Contactviews.as_view(), name='contact') the contact.html is just a simple text that extends from base.html .and it doesnt involve any functionality from models.py so the page is not rendering. i think maybe problem is on my url address. -
haystack and django-autocomplete-light
I implemented haystack with solr as a search engine and everything worked fine. I wanted to add some autocomplete so I tried to implement django-autocomplete-light. Autocomplete works fine, it suggest results but when I choose one search and press search button I got error: Traceback: File "C:\Python35\lib\site-packages\django\core\paginator.py" in _get_count 72. self._count = self.object_list.count() File "C:\Python35\lib\site-packages\haystack\query.py" in count 513. return len(self) File "C:\Python35\lib\site-packages\haystack\query.py" in __len__ 86. self._result_count = self.query.get_count() File "C:\Python35\lib\site-packages\haystack\backends\__init__.py" in get_count 626. self.run() File "C:\Python35\lib\site-packages\haystack\backends\solr_backend.py" in run 705. final_query = self.build_query() File "C:\Python35\lib\site-packages\haystack\backends\__init__.py" in build_query 700. final_query = self.query_filter.as_query_string(self.build_query_fragment) File "C:\Python35\lib\site-packages\haystack\backends\__init__.py" in as_query_string 387. result.append(query_fragment_callback(field, filter_type, value)) File "C:\Python35\lib\site-packages\haystack\backends\solr_backend.py" in build_query_fragment 554. prepared_value = value.prepare(self) File "C:\Python35\lib\site-packages\haystack\inputs.py" in prepare 104. exacts = self.exact_match_re.findall(query_string) During handling of the above exception (expected string or bytes-like object), another exception occurred: File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python35\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python35\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Python35\lib\site-packages\haystack\generic_views.py" in get 123. return self.form_valid(form) File "C:\Python35\lib\site-packages\haystack\generic_views.py" in form_valid 80. 'object_list': self.queryset File "C:\Python35\lib\site-packages\django\views\generic\list.py" in get_context_data 134. paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size) File "C:\Python35\lib\site-packages\django\views\generic\list.py" in paginate_queryset 78. page = paginator.page(page_number) File … -
unable to access dictionary in a queryset after serializing - django
I am creating a comments app based on django-contrib-comments. I am trying to return a comments record in ajax response. The comments model has a property (userinfo) which gathers user information in a dictionary. I can't get the below method to work context = Comment.objects.filter(pk=id) data = serializers.serialize('json', list(context)) i don't see userinfo after parsing the above json in jquery. I tried sending userinfo separately as below and it works context = Comment.objects.filter(pk=id) user = context[0].userinfo data = serializers.serialize('json', list(context)) response={} response['userinfo'] = user response['data'] = data return HttpResponse(json.dumps(response), content_type='application/json') i came across this question here Serialize the @property methods in a Python class. but are there any issues with my second method? Thank you! -
django rest PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl
I have some nested serializers, and I'm going to get the users objects in a JSON format through http requests, using following snippet: import requests r = requests.get('http://127.0.0.1:8000/accounts/users', auth=("admin", "mat")) But here is what it returns: PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl I tried a lot of approached include using to_representation method and inheriting from serializers.RelatedField. But always I get the same result. It seems that I'm doing something wrong. I'd be appreciate if you have any suggestion regarding this? Here are serializers: class TagSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name', 'popularity') class CategorySerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = Category fields = ('en_name', 'fa_name', 'tags') class CpSerializer(serializers.ModelSerializer): class Meta: model = CP fields = ('en_name', 'fa_name', 'id_number') class AppSerializer(serializers.ModelSerializer): category = CategorySerializer() cp = CpSerializer() class Meta: model = App fields = ('en_name', 'fa_name', 'package_name', 'build_number', 'downloads', 'cp', 'category') class UserAppSerializer(serializers.ModelSerializer): class Meta: model = UserApps app = AppSerializer() # or even serializers.StringRelatedField() fields = ('status', 'user_rate', 'comment', 'app') def to_representation(self, instance): return None class UserSerializer(serializers.HyperlinkedModelSerializer): id_number = serializers.CharField(read_only=True, source='userprofile.id_number') apps = serializers.SerializerMethodField() class Meta: model = User fields = ('username', 'password', 'first_name', 'last_name', 'email', 'id_number', 'apps') def get_apps(self, obj): if obj.username != "admin": return … -
Desrializing Django object from REST repsonses
I am using Django REST framework and quite a newbie at that... What is the simplest way to create a local model object from the response to a GET request? In details: I use a GET request to get one object. The response data has a full JSON of the object (including all automatically created fields, nested objects etc.), since this is how I defined the model serializer. Now, how can I use this JSON in the simplest to de-serialize it into a usable object? Moreover, whqat is the best practice to let users who use my REST interface to deserialize objects? Should I supply them with python classes of my Django moodels? Is there a -
djangocms-installer not asking setup questions
When creating a new django-cms project, the installer does not ask any setup questions. runserver starts fine, and a page is produced at 127.0.0.1:8000 but the page is blank instead of a demo page. Beyond this, adding a new template to the template directory does not appear as an option when adding a new page to the site. The tutorial at docs.django-cms seem entirely different to what I'm experiencing. -
How can I return nested entity from other database in json response in Django Rest Framework?
I use Python, Django and DRF. I have 2 databases. One of them contains table named "documents" (fields: id, name, document_type_id), second database contains table named 'document_type' (fields: id, name, description). Field 'document_type_id' from table "document" already filled values from table 'document_type'. As tell Django documentation: "Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases." Question: How can I show nested entity 'document_type' when serializing entity 'document' in GET requests? Example entity 'document': { "id": 1, "name": "document_name", "document_type": { "id": 25, "name": "passport", "description": "identity document" } -
django rest PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl
I have some nested serializers, and I'm going to get the users objects in a JSON format through http requests, using following snippet: import requests r = requests.get('http://127.0.0.1:8000/accounts/users', auth=("admin", "mat")) But here is what it returns: PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl I tried a lot of approached include using to_representation method and inheriting from serializers.RelatedField. But always I get the same result. It seems that I'm doing something wrong. I'd be appreciate if you have any suggestion regarding this? Here are serializers: class TagSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name', 'popularity') class CategorySerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = Category fields = ('en_name', 'fa_name', 'tags') class CpSerializer(serializers.ModelSerializer): class Meta: model = CP fields = ('en_name', 'fa_name', 'id_number') class AppSerializer(serializers.ModelSerializer): category = CategorySerializer() cp = CpSerializer() class Meta: model = App fields = ('en_name', 'fa_name', 'package_name', 'build_number', 'downloads', 'cp', 'category') class UserAppSerializer(serializers.ModelSerializer): class Meta: model = UserApps app = serializers.StringRelatedField() fields = ('status', 'user_rate', 'comment', 'app') def to_representation(self, instance): return None class UserSerializer(serializers.HyperlinkedModelSerializer): id_number = serializers.CharField(read_only=True, source='userprofile.id_number') apps = serializers.SerializerMethodField() class Meta: model = User fields = ('username', 'password', 'first_name', 'last_name', 'email', 'id_number', 'apps') def get_apps(self, obj): if obj.username != "admin": return else: apps = UserAppSerializer(read_only=True, … -
Django page no found
views.py def search_author(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] authors =User.objects.filter(username=q) return render_to_response('search_results.html', {'authors': author, 'query': q}) else: return HttpResponse('Please submit a search term.') def search_form(request): return render_to_response('search_form.html') urls.py url(r'^search_author$',app.views.search_author), url(r'^search_form$', app.views.search_form) search_form.html {% extends "app/layout.html" %} {% block content %} <form action="/search_author/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> search_results.html {% extends "app/layout.html" %} {% block content %} <p>You searched for: <strong>{{ query }}</strong></p> {% if authors%} <p>Found {{ authors|length }} author{{ authors|pluralize }}.</p> <ul> {% for author in authors %} <li>{{ author.username }}</li> {% endfor %} </ul> {% else %} <p>No authors matched your search criteria.</p> {% endif %} loginparitial.html {% if user.is_authenticated %} <form id="logoutForm" action="/logout" method="post" class="navbar-right"> {% csrf_token %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">您好 {{ user.username }}!</span></li> <li><a href="search_form">查询作者</a></li> <li><a href="upload_book"> 发布旧书</a></li> <li><a href="user_book_detail" >查看我的书籍</a></li> <li><a href="javascript:document.getElementById('logoutForm').submit()"> 登出</a></li> </ul> when l click the '查询作者' in the home page,the error says Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search_form/ Can anyone help me with my problem ? Thanks in advance -
python django 1.10 - admin not registered namespace
I'm having a hard time trying to figure out what's the matter when I access my \admin url. I tried reading up on the following docs but still no luck... (I'll be using LeafletGeoAdmin but if I don't fix this no wonder I won't be able to fix LeagletGeoAdmin as well) https://docs.djangoproject.com/en/1.10/topics/http/urls https://docs.djangoproject.com/en/1.10/ref/contrib/admin An error occurs as follows: NoReverseMatch at /gridlock/admin/ u'admin' is not a registered namespacelockquote Here's the stacktrace that I am getting: Internal Server Error: /gridlock/admin/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py", line 229, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py", line 201, in inner if request.path == reverse('admin:logout', current_app=self.name): File "/usr/local/lib/python2.7/dist-packages/django/urls/base.py", line 87, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) NoReverseMatch: u'admin' is not a registered namespace My admin.py from leaflet.admin import LeafletGeoAdmin from django.contrib import admin from .models import Stop admin.site.register(Stop, LeafletGeoAdmin) My urls.py from . import views … -
django models choices behavior
i'm using django 1.10 and try to make some models which including some simple choices, this is my models.py @python_2_unicode_compatible 7 class Person(models.Model): 8 Senior='A' 9 Middle='B' 10 Junior='C' 11 class_person=[(Senior,'Senior'),(Middle,'Middle'),\ 12 (Junior,'Junior')] 13 14 name=models.CharField(max_length=100) 15 grade=models.CharField(max_length=2,choices=class_person,default=Junior) 16 17 def __str__(self): 18 return '%s in %s' % (self.name,self.grade) 19 20 def is_senior(self): 21 return self.grade in (self.Senior,self.Middle) now i try make some Person objects instance via shell, for example Person.objects.create(name='John',grade='Another') now i call Person.objects.all() and it returns <QuerySet [<Person: John in Another>]> My question why the Person grade atribute can create the 'Another' as i know that grade models has maximum length of 2. thank you for the explanation -
Using Compressor (combine/minify css/html) with Cactus (static website generator)
I'm trying to use Django Compressor (http://django-compressor.readthedocs.io/en/latest/quickstart/) with Cactus (https://github.com/eudicots/Cactus). I've done the following... 1) Run "pip install django-compressor" from a command line 2) Modified the "INSTALLED_APPS" variable in site-packages/Cactus/site.py to have the value ['django_markwhat', 'compressor'] 3) Added this to my base.html... {% load compress %} {% compress css %} <link rel="stylesheet" href="/static/css/one.css" type="text/css" charset="utf-8"> <style type="text/css">p { border:5px solid green;}</style> <link rel="stylesheet" href="/static/css/two.css" type="text/css" charset="utf-8"> {% endcompress %} Running 'cactus serve' then results in this error... django.template.base.TemplateSyntaxError: 'compress' is not a valid tag library: ImportError raised loading compressor.templatetags.compress: cannot import name caches Unfortunately, I'm really not that familiar with Django to troubleshoot this well. Any ideas how to fix this or otherwise get a CSS/JS minifier/combiner working with Cactus? -
Always filter related fields for logged user
All my models on the database should be filtered by user, always. I created for all my models a field owner which I get the user from the request and fill it in when I'm creating the models. When I go to all urls they are filtered correctly, as well as when I create them onto the database. But the problem is when I use the html interface to insert a model on the database, all the related items (it doesn't matter the user) are listed on the foreign key field. My view class TransactionList(generics.ListCreateAPIView): serializer_class = TransactionSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self): return Transaction.objects.filter(owner=self.request.user) My serializer class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ('id', 'date', 'description', 'value', 'account', 'envelope', 'bill',) My model class Transaction(models.Model): date = models.DateField(auto_now=True) description = models.CharField(max_length=100) value = models.DecimalField(max_digits=10, decimal_places=2) account = models.ForeignKey(Account, on_delete=models.DO_NOTHING) envelope = models.ForeignKey(Envelope, on_delete=models.DO_NOTHING, null=True) bill = models.ForeignKey(Bill, on_delete=models.DO_NOTHING, null=True) owner = models.ForeignKey('auth.User', related_name='transactions') For example, with those items when I open the page for inserting the data, all the other accounts (which are restricted for user, too) appear on the combo. How do I filter related fields for the HTML forms? And how do … -
Django "reverse for ____ with arguments"... error
Error: Reverse for placeinterest with arguments ('',) and keyword arguments {} not found. 1 pattern(s) tried: [u'polls/(?P<section_id>[0-9]+)/placeinterest/$'] I worked through the Django example for a polling app, and now I'm trying to create a class registration app adapting what I already have. Error points to line 5 here: <h1>{{ section.class_name }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:placeinterest' section.id %}" method="post"> {% csrf_token %} <input type="radio" name="incr" id="incr" value="incr" /> <label for="incr"></label><br /> <input type="submit" value="Placeinterest" /> </form> But I think the problem is in my placeinterest function: def placeinterest(request, section_id): section = get_object_or_404(Section, pk=section_id) try: selected_choice = section.num_interested except (KeyError, Section.num_interested.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'section': section, 'error_message': "You didn't select a choice.", }) else: section.num_interested += 1 section.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(section.id,))) I'm not sure what my POST call should be if my Section class looks like this: class Section(models.Model): class_name = models.CharField(max_length=200) num_interested = models.IntegerField(default=0) pub_date = models.DateTimeField('date published') def __str__(self): return self.class_name def was_published_recently(self): return self.pub_date >= timezone.now() - …