Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django To template From JS
i have data from Template to JS: var tests = {{tests|safe}} But i need filter it on JS side: var newTest = tests.filter...map..sort() - just for example. It's posible to use newTest like Diango template? {% for index in newTest %} ... Can I do something on the JS (without using a python) -
Can I use django authentication system on my hybrid app
I am developing a web service by using django framework and I am using django authentication system to web client. But I also have a client application by using cordova framework. I have no idea how can I apply django authentication system to my cordova application. Can I still use django authentication system on my app? Please let me know. -
NoReverseMatch at /password_reset/done/
I have just learned from this tutorial to reset password in django. But I am not able to resolve the the error: NoReverseMatch at /password_reset/done after searching from many resources url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), -
How to sort list on the basis of count in django?
I have a list of data and there is a total count field is one field which has total no of users I want to sort the data on the basis of the total count. I tried to use dictsort:"users_set.all.count" but didnt shows error. <tbody> {% for item in data_list |dictsort:"users_set.all.count"%} <tr> <td>{% if item.users_set.all.count != 0 %} <a href="{% url 'cms:university-specific-display-of-student' %}?uni_id={{ item.id }}" id="{{ item.id }}">{{ item.name }}</a>{% else %}{{ item.name }}{% endif %}</td> <td class="text-center">{{ item.users_set.all.count }}</td> <td class="text-center"> {{ item.users_set.all|user_active_count:'2' }}</td> <td class="text-center">{{ item.users_set.all|user_active_count:'1' }}</td> <td class="text-center">{{ item.users_set.all|user_active_count:'3' }}</td> </tr> {% endfor %} </tbody> -
How to create multiple instance for one-to-one field in django from base model inheritance?
I have two type user model inherit from User model: class User(AbstractBaseUser): user_uuid = models.UUIDField(primary_key=True) @property def is_manager(self): return hasattr(self, 'manager') @property def is_salesman(self): return hasattr(self, 'salesman') class Manager(User): user = models.OneToOneField(User, parent_link=True) class Salesman(User): user = models.OneToOneField(User, parent_link=True) Now, the Manager could be a Salesman too. But I can't create Salesman like below: manager = Manager.objects.first() salesman = Salesman.objects.create(user=manager) assert salesman.user_uuid == manager.user_uuid Is there any way I can do that through Django model without add row in Salesman table by SQL directly? Any suggestion will be helpful, Thanks! -
django-reversion and django-reversion-compare how to build?
Hello I have some problems to add django-reversion and django-reversion-compare modules. I created new project and I want to track user_auth log changes with django-reversion (after register User model with django-reversion i wanna use django-reversion-compare). from django.contrib import admin from django.contrib.auth.models import User from reversion.admin import VersionAdmin @admin.register(User) class UserModelAdmin(VersionAdmin): pass when I want to register model User I got error django.contrib.admin.sites.AlreadyRegistered: The model User is already registered But when I use admin.site.unregister(User) @admin.register(User) class UserModelAdmin(VersionAdmin, SomeAdminModel): pass I dont know what I should replace with SomeAdminModel -
( Django RESTful ) How to send http request without login in "api-auth/login/" in browser
Since django restful can generate apis automatically,I just have a try. In the Quickstart, it use the command line tool: bash: http -a admin:password123 http://127.0.0.1:8000/users/ I just want to send an ajax request to the api by a javascript function,but just get an error: {"readyState":4, "responseText":"{"detail":"Authenticationcredentials were not provided."}", "responseJSON":{"detail":"Authentication credentials were not provided."}, "status":403, "statusText":"Forbidden"} If I log in the "api-auth/login/" page before sending the request ,it works successful. So my question is how to include the login information in the http request. Thanks in advance. -
Django - ModelForms rendered indexed by foreignKey and that value POSTed
A simple and logical extension of the tutorial polls app would be showing several questions per page with a single 'submit' button. I've got a hybrid design that uses ModelForms for multi-field questions but individually rendered fields for single-field questions. So the standard question_set page is rendered by: {% load custom_tags %} {% block question_set %} <form action="{% url 'polls:answer' user.username %}" method="POST"> {% csrf_token %} {% for question in page_question_list %} <hr/> {% if question.answer_type == "CH" %} {% include "polls/Choice_Answer_form.html" %} {%endif%} {% if question.answer_type == "SA" %} {% include "polls/Short_Answer_form.html" %} {%endif%} {% if question.answer_type == "LA" %} {% include "polls/Long_Answer_form.html" %} {%endif%} {% if question.answer_type == "E3" %} {% include "polls/EJ_Answer_form.html" with form=forms|get_item:question%} {%endif%} {% if question.answer_type == "E4" %} {% include "polls/EJ_Answer_form.html" with form=forms|get_item:question%} {%endif%} {% if question.answer_type == "BS" %} {% include "polls/brainstorm_form.html" %} {% endif %} {% endfor %} <br/> <hr/> <input type="submit" value="Submit" /> </form> {% endblock %} I have a sense that I have missed something fundamental about how forms are supposed to work. When you create a ModelForm object and send it out to be rendered, it knows what instance (in my case, question number and user_id) it corresponds to … -
foreignkey backwards manager not working django
This seems simple.. I have a Restaurant model and Recipe model, all I want is to be able to look up all the Recipes by a certain Restaurant. I am using the backwards manager FOO_set and cant seem to make it work: models.py class Restaurant(models.Model): restaurant_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') class Recipe(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='recipe') views.py def dashboard(request): user = request.user try: user.restaurant recipe_list = user.restaurant.recipe_set return render(request, 'usermanage/dashboard_restaurant.html',{'recipe_list':recipe_list}) When i run this i get an exception in the dashboard view. Looking at my database the user.restaurant object has recipes associated with it. If i just do recipe_list = user.restaurant it returns the restaurant object. Just when I add recipe_set it fails. Also tried recipe_set.all and all(). I have migrated everything. Django 1.11 -
PYTHON - looping the argument that have multiple information with same starts and ends
I've tried to find this solution but unable to get the correct answer. I want it to display all the id inside the text file. This is my data in a file sep id_775435 sep tmane_information site_area sep id_123123123 sep I've had try one example also from stackoverflow... with open('C:/JIR File/A.txt') as input_data: for line in input_data: if line.strip() == 'sep': break for line in input_data: if line.strip() == 'sep': break print (line) Output : id_775435 My concern is to display both of the visual id and maybe more than one with the same special characteristic. Output : id_775435 id_123123123 Hope you guys can understand it. Thanks for helping in advanced. -
request.method == post is not working in Django
I created a form in template to insert data in database but form is not working.When i submitted form nothing happened.please review my all code and give me some suggestion. add.html Template file: <h2>Add Article</h2> <form action="" method="post"> {% csrf_token %} <label>Title</label> <input type="text" name="title" placeholder="Enter Title"> <label>Category</label> <select name="cate"> <option value="">Select Category</option> {% for cat in get %} <option value="{{ cat.cate }}">{{ cat.cate }} </option> {% endfor %} </option> </select> <label>Discription</label> <textarea name="desc" rows="15"> </textarea> <input type="submit" value="submit" class="btn btn-default"> </form> I created 2 views.in first view i rendered all categories which add in form select menu and 2nd view is for handling form views.py from django.shortcuts import render, redirect from .models import article, category def get_category(request): get = category.objects.all() context = { 'get':get } return render(request, 'blog/add.html', context) def add(request): if request.method == 'POST': title = request.POST['title'] cate = request.POST['cat'] desc = request.POST['desc'] art = article(title=title, disc=desc, cat=cate) art.save() return redirect('blog/index.html') else: return render(request, 'blog/add.html') Models.py from django.db import models class category(models.Model): cate = models.CharField(max_length=100) def __str__(self): return self.cate class article(models.Model): title = models.CharField(max_length=250) disc = models.TextField() cat = models.ForeignKey(category, verbose_name="Category") posted = models.DateTimeField(auto_now_add=True, editable=False) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title urls.py from django.conf.urls import url from … -
Is it possible to use angular 2 as front-end and python(Django) as back-end?
I tried to make angular 2 as front end and python (Django) as back end.But i am failed to do it?help me. I tried this the following tutorial.But i got error while finding Systemjs.config.js https://4sw.in/blog/2016/django-angular2-tutorial/ -
Unknown migration for 'djcelery:0001_initial' when migrating Django application using South
I got following error when migrating my Django application using South. from django.db import models, migrations ImportError: cannot import name migrations I use Django==1.5.7 django-celery==3.2.1 and South==1.0.1 in my application. This is the log, UnknownMigration: Migration 'djcelery:0001_initial' probably doesn't exist. Traceback (most recent call last): File "/env/env/local/lib/python2.7/site-packages/south/migration/base.py", line 310, in migration migration = __import__(full_name, {}, {}, ['Migration']) File "/env/env/local/lib/python2.7/site-packages/django_celery-3.2.1-py2.7.egg/djcelery/migrations/0001_initial.py", line 4, in <module> from django.db import models, migrations ImportError: cannot import name migrations Can anyone please help me with this? -
Calling external HTTP api from HTTPS django+angular server on AWS
Is this possible? I am building a ecommerce site that requires calling external api service built on HTTP. My site is built on AWS EBS, with django(backend) and angular2(frontend). If I try to call the HTTP api from angular side, mixed-contents errors pops up, which is apparently the chrome browser blocking the call. Is there a way to do this? I found this answer regarding proxy, but because I'm a newbie, I don't really get how to I can proxy the call with django or angular. Thanks. -
Django 1.11 admin form add search box to oneToOne field
I have a user, admin and employee models, both employee and admin are related to the user model with a oneToOne field what i would like to do is in the admin form i have one field "user" instead of having a drop down field with all users i would like to have a search box so that when i search for a specific user i find him and choose him to be an admin. how? i also tried to add user's fields to admin's form but i couldn't i tried the inline thing, the parent_link in the admin's model... but i couldn't find a solution Now i would like to minimise the search through the long users list by adding a search box to the field -
django-allauth email verification: works for @gmail test account but not @yahoo?
This is pretty weird to me. For a while I thought the account verification was not working. I was testing it with an @yahoo.com email address. Then I decided to test it with an @gmail.com email address. I have tested both accounts multiple times and am certain I do not have a typo in the @yahoo.com email. How is this even possible? It doesn't make sense to me but if someone can shed some light on the issue I would really appreciate it. Obviously this will not fly. Thanks. Django 1.11, Python 3, and latest AllAuth. #AllAuth Settings ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_EMAIL_VERIFICATION = "mandatory" #ACCOUNT_USER_MODEL_USERNAME_FIELD = "email" ACCOUNT_USERNAME_REQUIRED = False -
Flask debug screen not properly formatted as expected
I am following the Quickstart tutorial for Flask. On running into an error, I am supposed to see a nicely formatted debug screen (As demonstrated in the tutorial), instead I am seeing an unformatted debug screen. Also, when I enter and send the debug pin, the page just refreshes and nothing changes(it still shows Console locked). I am running Python 3.5.3 |Anaconda 4.2.0 (64-bit) and Flask 0.11.1. A picture from my browser is shown below. How do I fix it? -
Django: How to translate the models' fields
I'm using the internationalization of django to translate my web app. I look this tutorial for that http://www.marinamele.com/taskbuster-django-tutorial/internationalization-localization-languages-time-zones But I want to know how to translate the fields of my models with the internationalization of django or how I can translate my models' fields Thanks a lot! -
failure to import djangfo.conf when running dev_server.py
When trying to access the app page through localhost:port the following error is thrown: INFO 2017-08-22 02:29:23,992 devappserver2.py:116] Skipping SDK update check. WARNING 2017-08-22 02:29:24,086 simple_search_stub.py:1169] Could not read search indexes from /tmp/appengine.None.agasfer/search_indexes INFO 2017-08-22 02:29:24,087 api_server.py:313] Starting API server at: http://localhost:45545 WARNING 2017-08-22 02:29:24,087 dispatcher.py:287] Your python27 micro version is below 2.7.12, our current production version. INFO 2017-08-22 02:29:24,130 dispatcher.py:226] Starting module "default" running at: http://localhost:9999 INFO 2017-08-22 02:29:24,130 admin_server.py:116] Starting admin server at: http://localhost:8000 INFO 2017-08-22 02:29:42,091 module.py:832] default: "GET / HTTP/1.1" 302 - INFO 2017-08-22 02:29:42,285 module.py:832] default: "GET /favicon.ico HTTP/1.1" 302 - INFO 2017-08-22 02:29:49,407 stubs.py:50] Sandbox prevented access to file "/home/agasfer/old_projects/app_engine/rsrss/main.pyc" INFO 2017-08-22 02:29:49,408 stubs.py:51] If it is a static file, check that `application_readable: true` is set in your app.yaml ERROR 2017-08-22 02:29:50,022 cgi.py:122] Traceback (most recent call last): File "/home/agasfer/old_projects/app_engine/rsrss/main.py", line 350, in <module> main() File "/home/agasfer/old_projects/app_engine/rsrss/main.py", line 344, in main template.register_template_library('filters.localdatetimefilters') File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/ext/webapp/template.py", line 269, in register_template_library django.template.add_to_builtins(package_name) File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/_internal/django/template/__init__.py", line 1047, in add_to_builtins builtins.append(import_library(module)) File "/usr/lib/google-cloud-sdk/platform/google_appengine/google/appengine/_internal/django/template/__init__.py", line 993, in import_library raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e)) InvalidTemplateLibrary: ImportError raised loading filters.localdatetimefilters: No module named django.conf INFO 2017-08-22 02:29:50,027 module.py:832] default: "GET / HTTP/1.1" 500 - ^CINFO 2017-08-22 02:30:11,681 shutdown.py:45] … -
appending anchor tag in django template
the working anchor tag- <a href="{% url 'comments:delete_question_comment' pk=comment.pk %}" title="delete" class="btn btn-simple"> <span class="glyphicon glyphicon-remove text-danger"></span> <span class="text-danger icon-label">Delete</span> </a> my attempt at appending- *dom node*.append("<a href='{% url \"comments:delete_question_comment\" pk=comment.pk %}'</a>") the error- Could not parse the remainder: '\"comments:delete_question_comment\"' from '\"comments:delete_question_comment\"' I'm not sure what's going wrong. the quote escaping should work as appending just \"comments:delete_question_comment\" works fine, so if anyone knows what the problem is I'd be greatly appreciative -
Unable to install django
When I install Django-1.8.18 by using pip,it shows pip install django File "", line 1 pip install django ^ SyntaxError: invalid syntax And if I use winpython control pancel,it shows invalid mode('wb') or filename: 'c:\users\lenovo\appdate\local\temp\wppm_8ohady\Django_1.8.18\tests\staticfiles_tests\apps\test\static\test\xe2\x8a\x37.txt' -
TypeError: expected string or bytes-like object after switching from RichTextField to StreamField in one of my page models
Still in development, I decided to switch over the body field for one of my wagtail.Page models from RichText to StreamField. In the wagtail admin interface I can create pages using this model without a problem, and StreamField seems to work fine. However, when viewing the resultant page I get the following error: Template error: In template D:\Documents\Dropbox\Work\TravelSite\travelnews\travelnews\templates\base.html, error at line 14 expected string or bytes-like object 4 : 5 : 6 : <!DOCTYPE html> 7 : <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> 8 : <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> 9 : <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> 10 : <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> 11 : <head> 12 : <meta charset="utf-8" /> 13 : <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 14 : <script src="https:/ /ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 15 : {% load bootstrap3 %} 16 : {% bootstrap_css %} 17 : {% bootstrap_javascript %} 18 : {% bootstrap_messages %} 19 : 20 : <title> 21 : {% block title %} 22 : {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %} 23 : {% endblock %} 24 : {% block title_suffix %} Traceback: File "C:\Users\Ben\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) … -
Django Rest Framework Validator to include FK field
Let's say i have this structure: class RouteSerializer(ModelSerializer): class Meta: model = Route fields = ('origin', 'destiny') class NetworkSerializer(ModelSerializer): routes = RouteSerializer(many=True) class Meta: model = Network fields = ('name','routes') How can i set up a UniqueTogetherValidator with both origin, destiny and name (since Route has a FK from Network) -
django blog zinnia Template Customizing
I was wondering what is the best way for customizing zinnia because by default when installing via pip it installs in site packages do I need to open the site package directory and edit it from there? Just want to know. Plus do I need to do some extreme tweaking to zinnia in other for it to work since all I want is a simple post that, displays entries as a list and detail or I just leave it as it is after installation. -
Django: AttributeError: module 'User.views' has no attribute 'User'
I have a few apps within my Django project and all of them seem to be working, except for the User app. All the apps are installed in the settings. Whenever I type "python manage.py runserver", I see a long line of code that ends with this: File "/Users/Name/Desktop/Project_Name/MyProject/User/urls.py", line 5, in <module> url(r'Home/', views.User, name='Home'), AttributeError: module 'User.views' has no attribute 'User' MyProject/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('Home.urls')), url(r'^Application', include('Application.urls')), url(r'^Login', include('Login.urls')), url(r'^User', include('User.urls')), ] User/urls.py from django.conf.urls import url, include from User import views urlpatterns = [ url(r'Home/', views.User, name='Home'), url(r'Matrices/', views.User, name='Matrices'), ] User/views.py from django.shortcuts import render def Home(request): return render(request, 'Home.html') def Matrices(request): return render(request, 'Matrices.html') If I remove "url(r'^User', include('User.urls'))" from MyProjects/urls.py, everything is working fine (but of course I cannot access the urls from User app). All the other apps have only one "url" and only User app has multiple urls. Is that where the issue lies? Would greatly appreciate any help. Thanks!