Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, IDLE slow loading page - 16s
As you can see from image, page loaded 16s, and most of time loaded IDLE. WTF??? I spent 2 month to dev., deployment by Heroku, learned git, AWS S3 - and when finished i notice this. I'm so sad T_T. Can you help me? i just don't understand how to fix it Image - timeline of my page -
django error on simple app while run the program
raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
django websocket send update from database without pooling
I am using django channels with redis for backend with mysql database, I push new data to mysql database and in consumers.py i send data through websocket to client. The problem is once the new data was pushed to the database the client has to send message in order to receive the new data. therefore i am using long pulling. the client send message every 2 second and gets the new data but it is very inefficient. Is there any other way to solve this problem so the client doesn't have to send message all the time? in consumers.py: def ws_message(message): livedata = serializers.serialize("json",testLiveData.objects.all()) Group(message.content['text']).send({ "text": livedata, }) in javascript: setInterval(function() { if (socket.readyState == WebSocket.OPEN) socket.onopen(); }, 2000); i followed tutorial on channels readthedocs -
SearchQuerySet().filter(content='content') returns results, but they don't show up in search.html
I can go into my shell and type sqs = SearchQuerySet().filter(content='content') len(sqs) and I get results. I have inspected them and when I type sqs[0] sqs[0].id sqs[0].text I get coherent results. However when I use the search form on my website, I get no results. I don't even define my own SearchView. It is the default one. On the template, I have tried {% for result in page.object_list %} {% for result in object_list %} {% for result in page_obj.object_list %} and still don't get any results. And the query did run because I can put stuff inside {% if query %} so that clearly works. What do I do? Thank you. -
How should i proceed to make a project that allow user to put their travel detail and keep track of hotel,airline,budget and schedule
As a database project, I want to make a system that allows users to put together their own little travel itinerary and keep track of the airline/hotel arrangements, points of interest, budget and schedule. -
parse and order csv file in django template
How to parse csv file into django template and sort them by: myfile.csv status, date, user, rating Registered, 12-10-2016, user1, 8.75 Registered, 22-05-2016, user2, 9.23 Registered, 19-11-2016, user3, 7.00 Currently i'm trying to do things like this: Views.py args = {} file_url = urllib2.Request("http://server.local:8000/static/myfile.csv", None, {'User-Agent': 'Mozilla/5.0'}) file_url_response = urllib2.urlopen(file_url) pre_reader = csv.reader(file_url_response) args['list'] = pre_reader return render_to_response('template.html', args) template.html {% for row in list %} <p> {% for item in row %} {{ item }} {% endfor %} </p> {% endfor %} Rendered HTML response is: status, date, user, rating Registered, 12-10-2016, user1, 8.75 Registered, 22-05-2016, user2, 9.23 Registered, 19-11-2016, user3, 7.00 But I want to do something like this: <table> {% for row in list %} <tr> <td> {{ row.status }} </td> <td> {{ row.date }} </td> <td> {{ row.user }} </td> <td> {{ row.rating }} </td> </tr> {% endfor %} </table> Also it would be great If I could order by values, so users can order results by date or by rating -
Error while running simple django app
knysys@kshahidLT ~/Desktop/firsrproject $ python manage.py runserver Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/knysys/Desktop/firsrproject/firsrproject/urls.py", line 22, in url(r'^', include('marcador.urls')), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/knysys/Desktop/firsrproject/marcador/urls.py", line 6, in name='marcador_bookmark_user'), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
Image is not uploaded from form django
My Views def apost(request): if request.method =='POST': form = APostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.slug = slugify(form.title) form.save() return redirect('apost') else: form = APostForm() template_name = 'dadmin/form.html' items = Post.objects.all() context = {'title':'Add Post','form':form,'items':items} return render (request, template_name, context) My Form class APostForm(forms.ModelForm): class Meta: model = Post fields = {'title','photo','content'} Models photo = models.ImageField(upload_to='images') No Image uploaded is Accepted Photo is selected but when Click save. It shows this field is required error. I had searched through the questions here but request.FILES solves others problems but not mines. Whats wrong? -
Django-bootstrap tree click event
How to write a click event for a particular node of a bootstrap tree in django? if following is my treeview how to display a list while clickin the node 'processareafilter'? context = dict() organization = Organization.objects.all() orglocations = Orglocations.objects.all() locationprocessarea = Locationprocessarea.objects.all() processareaasset = Processareaasset.objects.all() processtaglink = Processareaassettaglink.objects.all() context["TreeStructure"] = [ { 'text': organizations.name, 'nodes': [ { 'text': orglocationss.name, 'nodes': [ { 'text': processarea.name, 'nodes': [ { 'text': processasset.name, 'nodes': [{ 'text': processareafilter.name, 'nodes': [{ 'text': taglink.name }for taglink in processtaglink.filter(areaassetid=processareafilter.id)] }for processareafilter in processareaasset.filter(parentassetid=processasset.id)] } for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)] } for processarea in locationprocessarea.filter(locationid=orglocationss.id)] } for orglocationss in orglocations.filter(organizationid_id=organizations.id)] } for organizations in organization.filter(id=1)] return { "tree_view": context } -
Matching one-or-more keywords with Django's Postgres full-text searching
If I search on a website with multiple keywords (and no quotes) -- such as for red car -- my expectation is that items containing "red car" exactly should be first, followed by items containing both keywords (but non-sequentially), followed by items containing one of the keywords. (I believe this is the default behavior in Lucene-like systems, but it's been a while since I've used them, so can't say for sure.) My hope was that the Postgres full-text searching would automatically do this, but my early tests show this is not the case: ## ASSUME: items in database: <blue car>, <green car>, <red truck> keywords = "red car" items = ForSaleItem.objects.filter(name__search=keywords) ## RESULT: items is empty/None, whereas it should have each of ## the items since one keyword matches. The hack I'm seeing is to using Django's disjunction operator, but I'm hoping there is something less-hacky. I'm also pretty sure this hack wouldn't put exact matches at the top of the list. Here's the hack: from django.db.models import Q keyword_query = Q() for keyword in keywords.split(' '): keyword_query.add(Q(name__search=keyword), Q.OR) items = ForSaleItem.objects.filter(keyword_query) Is there some settings/API that I'm missing (or something implementable on the postgres side) that gets the functionality … -
Deploying Django Channels with Daphne + NGINX using SSL
I had a working configuration of nginx proxying to an upstream daphne server for django channels. However, when I moved my site to ssl, I started running into issues 403 errors with the websocket requests. This is from my error log: None - - [24/Apr/2017:02:43:36] "WSCONNECTING /pulse_events" - - None - - [24/Apr/2017:02:43:36] "WSREJECT /pulse_events" - - 2017/04/24 02:43:37 [info] 465#465: *10 client 69.203.115.135 closed keepalive connection And from the access log: - - [24/Apr/2017:02:48:54 +0000] "GET /pulse_events HTTP/1.1" 403 5 "-" "-" - - [24/Apr/2017:02:49:03 +0000] "GET /pulse_state/ HTTP/2.0" 200 1376 "-" "Pulse/1 CFNetwork/811.4.18 Darwin/16.1.0" My nginx config is as follows: upstream pulse_web_server { server unix:/home/pulseweb/run/gunicorn.sock fail_timeout=0; } upstream pulse_web_sockets { server unix:/home/pulseweb/run/daphne.sock; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name backend.com; return 301 https://$host$request_uri; } server { listen 443 http2 ssl; server_name backend.com; root /var/www/vhosts/backend.com; location ~ /.well-known { allow all; } include snippets/ssl-params.conf; ssl_certificate /etc/letsencrypt/live/backend.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/backend.com/privkey.pem; client_max_body_size 4G; access_log /var/log/nginx/pulse-access.log; error_log /var/log/nginx/pulse-error.log info; location /static/ { alias /var/www/vhosts/backend.com/static/; } location /pulse_events { proxy_pass http://pulse_web_sockets; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host … -
HTTP Request Testing in Pytest
So I am very new to coding in general and I have written the following code to pass HTTP requests to Python/Django methods to test them with Pytest: import django django.setup() from login.views import delete_song, delete_playlist, create_song, logout_user, add_preferences, create_playlist, detail, login_user from django.shortcuts import render, get_object_or_404 from login.models import Playlist from django.test import TestCase from django.test import Client class test_songs(TestCase): def setUpClass(self): self.client = Client() self.post = ('POST /docs/index.html HTTP/1.1 Host: www.nowhere123.com Accept: image/gif, image/jpeg, / Accept-Language: en-us Accept-Encoding: gzip, deflate Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) (blank line) {"foo": "bar"}') def test_login_pass(self): assert login_user(self) == render(self, 'index.html', {'playlists': Playlist.objects.filter(user=self.user)}) def test_login_fail(self): assert login_user(self) == render(self, 'login.html', {'error_message': 'Invalid login'}) def test_create_playlist(self): assert create_playlist(self) == render(self.post, 'create_playlist.html', context) def test_create_song(self): assert create_song(self,111) == render(self, 'detail.html', {'playlist': get_object_or_404(Playlist, pk=111)}) def test_add_preference(self): assert add_preferences(x, 111) == render(x, 'add_preferences.html', context) def test_delete_song(self): assert delete_song(x,111,222) == render(x,'detail.html', {'playlist': get_object_or_404(Playlist, pk=111)}) def test_detail(self): assert detail(self, 111) == render(self, 'detail.html',{'playlist': get_object_or_404(Playlist, pk=111), 'user': self.user}) def test_detail_not_auth(self): assert detail('nonuser', 111)== render('nonuser', 'login.html') def test_delete_playlist(self): assert delete_playlist(x, 111) == render(x, 'detail.html', {'playlist': Playlist.objects.get(pk=111)}) def test_logout_user(self): assert logout_user(x) == render(x, 'login.html', context) but I keep getting the error when running them: TypeError: setUpClass() missing … -
Django form in a base class
forms.py class search_form(forms.Form): options = categories.objects.all() category = forms.ModelChoiceField(options, initial={'All':'All'}, label='') search = forms.CharField(max_length=100, label='', required=False) This form is used for searching for items. And right now I have it implemented on the index page and it works as expected. The index (home) page has its own view that makes use of this form, but I have a base template (base.html) that every page on the site extends. The base template holds the menu bar and the footer of the site. I need to add the form to the base class and have it function in every template that extends it. Is there a way to do this? -
Creating random URLs in Django?
I'm creating a project where: A user submits an input into a form That data is input into the database A random URL is generated (think imgur / youtube style links) The user is redirected to that random URL The input data is display on that random URL forms.py class InputForm(forms.Form): user_input = forms.CharField(max_length=50, label="") random_url = forms.CharField(initial=uuid.uuid4().hex[:6].upper()) models.py class AddToDatabase(models.Model): user_input = models.CharField(max_length=50, unique=True) random_url = models.CharField(max_length=10, unique=True) views.py def Home(request): if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): user_input = request.POST.get('user_input', '') random_url = request.POST.get('random_url', '') data = AddToDatabase(user_input=user_input, random_url=random_url) data.save() return render(request, 'index.html', {'form':form}) else: form = InputForm() return render(request, 'index.html', {'form':form}) index.html <form action="" method="POST"> {{form}} {% csrf_token %} <input type="submit"> </form> I'm new to Python / Django, which is probably obvious. The above code allows users to submit an input which is succesfully added to the database. It also generates a 6 character UUID and adds that to the database. The problem is I don't know how to turn that UUID into a URL and redirect the user there after submitting the form. I've tried a couple of methods so far, such as adding action="{{ random_url }}" to the index.html form, as well as … -
AppConfig.ready() is Running Twice on Django Setup (Using Heroku)
I have a function that needs to run in the background on one of my web applications. I implemented a custom AppConfig as shown below: class MyAppConfig(AppConfig): run_already = False def ready(self): from .tasks import update_products if "manage.py" not in sys.argv and not self.run_already: self.run_already = True update_products() However, this command is being executed twice (the update_products() call) As stated in the documentation: In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time. I feel like I am following what the documentation says to do. What gives? -
Deploy django as war - Jython
I'm trying to deploy a django app as war (to use with JBOSS server).I have seen the documentation and I made this: jython manage.py builder --include-java-libs=/usr/share/java/jython/jython.jar And I have this error: Traceback (most recent call last): File "manage.py", line 16, in <module> raise ImportError( 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? What should I do? Thanks. -
Looping over JSONResponse() result from django in jquery
I am interested in getting the results of an insert operation from views.py in form a JSON. I am getting the results alright, I think. my view looks like this: added={} if request.method=='POST': #Post method initiated. try: for id in allergies: allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user) allergy.save() added[allergy.id]=id except BaseException as e: pass return JsonResponse(added,safe=False) The records, passed from JQUERY, added successfully to the database. What I want to get now is a JSON result in the form of {12:1, 13:2}. My firebag shows the response as: 12:1 13:2 I am not sure if this a valid JSON or not. If I do list(added), it gives instead: 0: 12 1: 13 which I don't want. The problem I am having now I want to go thru the returned items but I am getting incorrect results. I basically want to get 12:1, 13:2. $.ajax({ type: "POST", url: "/patient/addallergy/", data: postForm, dataType : "json", cache: "false", success: function (result) { alert(result.length); //gives undefined, rendering the below line meaningless if (result.length>0){ $.each(result,function(key,value){ alert(key); alert(value); }); } }, fail: function (result){ } }); -
Django models.Manager custom SQL query "more than one row returned" error
So I'm trying to get the result of the age() function on PostgreSQL from a column in the DB. The goal is to append a new virtual column with the age or time elapsed since the datetime stored the database. I tried this by creating a models.Manager in Django to add this new column: class PriorityManager(models.Manager): def get_queryset(self): time_elapsed = RawSQL('SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post', params=(), output_field=models.IntegerField()) return super(PriorityManager, self).get_queryset().annotate(score=time_elapsed) I need a score column to help sort the objects later, and the score is based on the time elapsed. The query SELECT EXTRACT(EPOCH FROM age(datetime)) AS age FROM backend_post; works in the dbshell but when running it on Django, the following message comes up: ProgrammingError at /api/post/list/ more than one row returned by a subquery used as an expression I suspect the problem is that the query returns a whole column of elements while the models.Manager expected only one result. I believe there should be something sent as a parameter in the RawSQL query but I couldn't figure out what it is... Anyone knows what to do? Thank you very much! -
ListSerializer object is not iterable
Hi django newbie here, I have permissions model which is about door and door_groups. There is between ManyToMany realationship between Door and Door_Group models. And they have OneToMany realation with Permission. I want to ask, how can I get a spesific Door all distinct permissions? permissions_list = [] permissions_list.append(door.permission_set.all()) for group in door.door_group_set.all(): permissions_list.append(group.permission_set.all()) serializer = PermissionSerializer(permissions_list, many=True) return Response(serializer.data) I am getting all permissions but I can not serialize it with ModelSerializer class. Permissions Model: class Permission(models.Model): user = models.ForeignKey('users.EmailUser') door = models.ForeignKey('doors.Door', null=True, blank=True) door_group = models.ForeignKey('doors.Door_group', null=True, blank=True) days = models.CharField(validators=[validate_comma_separated_integer_list], max_length=13, null=True) start_hour = models.TimeField(default='00:00') end_hour = models.TimeField(default='00:00') created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(auto_now=True) def __unicode__(self): return 'Days: ' + self.days + ' Start:' + str(self.start_hour) + ' End: ' + str(self.end_hour) + ' User: '+ self.user.username def clean(self): # Don't allow draft entries to have a pub_date. if self.door_group is not None and self.door is not None: raise ValidationError('Choose between, group of doors or one door to give permission. Can not choosable both.') if self.door_group is None and self.door is None: raise ValidationError('Choose between, group of doors or one door to give permission.') -
Django Interchanging the urls by overiding regex part
When requesting[GET] 127.0.0.1:8000/restaurant/1 i get a clean json and 200 status code urlpatterns = [ url(r'^restaurant',views.Restaurant_List_Create.as_view(), name='all_restaurants'), url(r'^restaurant/(?P<pk>\d+)',views.Restaurant_Retrive.as_view(), name='specified_restaurant'), ] but when i interchange the url codes it runs the views.Restaurant_List_Create.as_view() (overrides the regex url) urlpatterns = [ url(r'^restaurant/(?P<pk>\d+)',views.Restaurant_Retrive.as_view(), name='specified_restaurant'), url(r'^restaurant',views.Restaurant_List_Create.as_view(), name='all_restaurants'), ] -
Django Python runserver error: Project is using Twilio for surveys
I'm currently working on a project that uses Twilio to have an automated survey. I'm trying python manage.py runserver and I get the following results: System check identified no issues (0 silenced). April 23, 2017 - 12:15:51 Django version 1.11, using settings 'vizeserver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x04406FA8 > Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\uti ls\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\management\commands\runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\con trib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\management\commands\runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\uti ls\module_loading.py", line 20, in import_string module = import_module(module_path) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\Thomas\Documents\Development\TwilioSurvey\vizeserver\vizeserver\wsgi.py", lin e 16, in <module> application = get_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\cor e\wsgi.py", line 14, in get_wsgi_application return WSGIHandler() … -
Use javascript to set action in django form
In django 1.10, I need to pass parameters from one html template back to view.py, and finally render again the same view. The problem is in setting action in the html to use javascript. This is my html template: <form method='POST' action='/res/{{link}}/{{page_id}}/{{email}}/'> <input type="hidden" name="email" value="{{email}}"> <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}> </form> {{page_id}} in action changes as the user interacts with the web page (using a drop-down selector). The following javascript would be able to catch this: <script> function post_redirect_link() { var page_id = document.getElementById("sel1").options.selectedIndex; return '/res/{{link}}/'+page_id+'/{{email}}/' } </script> And I tried to set action dynamically as: <form method='POST' action='post_redirect_link()'> <input type="hidden" name="email" value="{{email}}"> <input type="image" type='submit' src={% static "assets/images/twitter_icon.png" %}> </form> BUT instead, I get a redirect of the type /res/correct_link/post_redirect_link()/correct_email, where "post_redirect_link()" is taken as string rather than being the value returned by the js method. Any suggestion? -
string indices must be integers, not str - django
I am trying to pass this into a post from front end but I keep on getting this error on this line and I cannot figure out why is that {"isUpdated": true} passing this in my django, I have these body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) if data['isUpdated'] is not False: # more codes I keep on getting error on this if data['isUpdated'] is not False: Can someone give me suggestions what is happening? -
How to access Manager of through model
I've created a Manager for a through model and want to use it when accessing the Many-to-many objects. class Contact(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField() class ContactList(models.Model): name = models.CharField(max_length=50) contacts = models.ManyToManyField( Contact, through='ContactListEntry', blank=True, ) class ContactListEntry(models.Model): contact_list = models.ForeignKey(ContactList, related_name='contact_list_entries') contact = models.ForeignKey(Contact, related_name='contact_list_entries') removed = models.BooleanField(default=False) # Used to avoid re-importing removed entries. # Managers. objects = ContactListEntryManager() Manager: class ContactListEntryManager(Manager): def active(self): return self.get_queryset().exclude(removed=True) Is there any way to access the Manager of the through field? This here: class ContactListView(DetailView): model = ContactList template_name = 'contacts/contact_list.html' context_object_name = 'contact_list' def get_context_data(self, **kwargs): ctx = super(ContactListView, self).get_context_data(**kwargs) contact_list_entries = self.object.contacts.active() # <-- THIS HERE. ctx.update({ "contact_list_entries": contact_list_entries, }) return ctx Throws: AttributeError: 'ManyRelatedManager' object has no attribute 'active' -
Django page genarte from set of inclusion_tag
I have an idea but I don't know how this should work. I have page class where I have saved list of component on page: class Page(object): title = None slug = None inMenu = False parent = None # place for register parent page # array of components in page # { componentName: 'carousel', htmlConent: '', images: ['slide_01.jpg', 'slude_02.jpg'] } #(from carousel model) components = [] template = Template ('index.html') I have the components now as a templateTags as inclusion_tag in django I need render page component with args. I want do something like: {% extends 'base.html' %} {% block content %} {% for component in page.components %} {% render_component component%} {% endfor %} {% endblock %} Have you tried something like that? I don't know how exactly render the templateTags from the array with args. Could someone help me with this?.