Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting amount to lakh and crore
How to convert amount to lakh and crore in django. for example if amount is 100000 I want to show 1 Lakh. Is it possible to do this by using a custom template tag? I'm a beginner so this is the code I wrote to get this done. But how to use this in template tag? if properties.expected_price >= 100000: expected_price_in = expected_price/100000 elif properties.expected_price >= 1000000: expected_price_in = expected_price/1000000 else: expected_price_in = expected_price -
Unable to suppress deprecation warnings
In my Django application, when I import one third party library, I get this warning in the console: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses If however I do the import inside Python shell, then everything is ok. I want to achive the same behaviour in Django. This is what I've tried based on answers in other OS threads: import warnings from django.utils.deprecation import RemovedInDjango110Warning warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning) The above code results in another error message, that says that RemovedInDjango110Warning does not exists. I also tried this: import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() from third_party_lib import some_module But still I get the very same error message. So, it seems like all previous answers to this problem got outdated. And we need some fresh fix. Thanks! -
Error starting `python manage.py migrate`
I am trying to run the project, but there is an error. I use Django 1.6. Windows 7 (Test) D:\ALEX\Test>python manage.py migrate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "D:\ALEX\Test\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line utility.execute() File "D:\ALEX\Test\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\ALEX\Test\lib\site-packages\django\core\management\__init__.py", line 272, in fetch_command klass = load_command_class(app_name, subcommand) File "D:\ALEX\Test\lib\site-packages\django\core\management\__init__.py", line 75, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "D:\ALEX\Test\lib\site-packages\django\utils\importlib.py", line 40, in import_module __import__(name) File "D:\ALEX\Test\lib\site-packages\south\management\commands\__init__.py", line 10, in <module> import django.template.loaders.app_directories File "D:\ALEX\Test\lib\site-packages\django\template\loaders\app_directories.py", line 25, in <module> raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) django.core.exceptions.ImproperlyConfigured: ImportError admin_tools.menu: No module named apps -
hosting angular 2 app to a django server
I am new to angular 2.When I was learning I used the angular quickstart plugin to host(given in the docs).But now I need to deploy it to a django server which in turn is hosted on a different laptop,for testing the app.I am having a problem while entering the ip of the server,and sending get and post requests .The url of the server gets prepended with localhost since I have to host the angular app via quickstart plugin in my system.Please help me with this problem -
dependencies reference nonexistent parent node error when migrate in django
I am dooing a project in which when i try to migrate in django,error come Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 63, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 321, in build_graph _reraise_missing_dependency(migration, parent, e) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 291, in _reraise_missing_dependency raise exc django.db.migrations.graph.NodeNotFoundError: Migration reviews.0001_initial dependencies reference nonexistent parent node (u'catalogue', u'0001_initial') I understand the problem but unable to solve it. i deleted all .pyc files and migration folder. i also deleted database also but this problem persist. How can i get rid off from this error. Thanks in advance. -
Make django-celery to look for specific tasks that are not in tasks.py
I need django-celery to look for specific periodic tasks when displaying in django admin in PeriodicTasks model. Tasks must be restricted by its name. Tasks are located in separeted package, not in app's tasks.py module. Is it possible to implement? The only idea is to override TasksLoader, but have no idea how to do it. -
NoReverseMatch in url with title in django app
I want to have title in url in my Django (1.8) app but I get message error: NoReverseMatch at /en/blog Reverse for 'details' with arguments '()' and keyword arguments '{'title': 'Test 5'}' not found. 1 pattern(s) tried: ['en/blog/(?P<title>[a-zA-Z_ ]+)$'] My html code in template: {% for i in object_list %} <li class="teaser-box"> <a href="{% url 'blog:details' title=i.title %}"> <h2>{{ i.title }}</h2> </a> <p>LIVE STREAM AM {{ i.livestream_from|date:'d.m.Y' }}</p> </li> {% endfor %} My code in url: url(r'/(?P<title>[a-zA-Z_ ]+)$', ArticleDetails.as_view(), name='details'), My view code: class ArticleDetails(DetailView): model = Article -
http://127.0.0.1:8000/ isn't working on Chrome but working fine on Internet Explorer
I've recently installed django on Windows Server 2012 R2. Installation was error free. But when I run python manage.py runserver it tell mes to use http://127.0.0.1:8000/ . Its working on Internet explorer but in Firefox and Chrome its not working. its **ERROR The requested URL could not be retrieved The following error was encountered while trying to retrieve the URL: http://127.0.0.1:8000/ Connection to 127.0.0.1 failed. The system returned: (111) Connection refused The remote host or network may be down. Please try the request again. Your cache administrator is administrator.** Kindly help as I'm newbie in django. -
Get the most top liked post ordered by time in django
models.py: class Post(models.Model): author = models.ForeignKey('User') text = models.TextField(max_length=320) created_date = models.DateTimeField(default=timezone.now) class Likes(models.Model): post = models.ForeignKey('Post') liker = models.ForeignKey('User') created_date = models.DateTimeField(default=timezone.now) class Meta: unique_together = ('post', 'liker') I want to Get newest posts which their likes are more than 70. how can I write that query set with django orm ? -
JS replace function gives undefined EOF when user push enter in message
inside dataTable I'm getting text from Django views, and send it to custom written js replace function for replacing certain characters with our native language alphabets. Works with single line perfectly, but when the user pushes enter inside message it gives undefined EOF. Here is the code Html {% for comment in comments %} <tr> <td> {{ comment.id }} </td> <td> {{ comment.req_id }} </td> <td> {{ comment.ans_id }} </td> <td> <script>**document.write(replace("{{ comment.comment_text }}"));**</script> </td> </tr> {% endfor %} enter image description here JS function replace(x) { var text = String(x); var lines = text.split("\n"); var returnedText=""; for(i=0;i<lines.length;i++){ returnedText += lines[i].toString().allReplace({'É™': 'ə', 'ı': 'ı', 'ö': 'ö', 'ü': 'ü','ç': 'ç','İ': 'İ','ÄŸ': 'ğ','ÅŸ': 'ş', 'Æ': 'Ə','Åž': 'Ş'}); returnedText += "\n"; } return returnedText; } String.prototype.allReplace = function(obj) { var retStr = this; for (var x in obj) { retStr = retStr.replace(new RegExp(x, 'g'), obj[x]); } return retStr; }; -
ChartJS options with Chartkick
I have a chartJS chart rendered in Django with chartkick. How do I specify the options. {% column_chart data %} For example I would like to add the following: options: { layout: { padding: { bottom: 5 } } } -
Django user update not works
I have this user serializer: class SimpleUser(models.Model): class meta: abstract = True email = models.EmailField(_('email address'), blank=False) password = models.CharField(_('password'), max_length=128) first_name = models.EmailField(_('first name'), blank=True) class UserSerializer(ModelSerializer): class Meta: model = SimpleUser And this is my view: class UserView(APIView): def patch(self, request, user_id): firstname = request.data.get('first_name', '') email = request.data.get('email', '') password = request.data.get('password', '') user = User.objects.get(id=user_id) serializer = UserSerializer(instance=user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) I send this json request, but only the password and email are updated and first_name not updated. { "password":"6524266", "email":"HH@bb.com", "first name":"dsfxvxc" } I get the status 200 OK and can get the saved object in serializer.save() What is wrong with my code? -
How do I receive file upload progress using Django/DRF
I'm not sure if there is an answer for this out there so here goes... I am building an rest API project using django and django restframework where consumers have the ability to upload files. I can't seem to find any docs or examples of how to report file upload progress to the requesting client. How do I go about this? -
How do I save authenticated user in a cookie in django?
Here's a snippet of my code : class LoginView(View): facility = 'unique-named-facility' audience = {'broadcast':True} form_class = LoginForm #This is a constructor def __init__(self,*args,**kwargs): #Initialize inherited parent calss by calling its constructor super(LoginView,self).__init__(*args,**kwargs) #Create an instance of redis publisher at the time od instaniation of Login View self.redis_publisher = RedisPublisher(facility=self.facility, **self.audience) def get(self, request): #Create a message ovject for websocket message = RedisMessage('A message has been passed to all clients listening to this unique-named-facility') #Publish the socket self.redis_publisher.publish_message(message) #Initialize the login form form = self.form_class() #Render the login form if request.COOKIES.get('user') != None: login(request,request.COOKIES.get('user')) return HttpResponseRedirect('/app/dashboard/') return render(request,'login/index.html',{'form' : form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): #Fetch username and password user_name = form.cleaned_data["user_name"] password = form.cleaned_data["password"] remember_me = form.cleaned_data["remember"] #Authenticate the User user = authenticate(username=user_name, password=password) if user is not None: #After authentication login the user login(request,user) # Redirect to the new page if authenticated succesfully response = HttpResponseRedirect('/app/dashboard/') if remember_me: response.set_cookie('user',user) return response else: # Empty previous form Content form = self.form_class() # If user is still not autheticated re render the view with warning message return render(request,'login/index.html',{'form' : form , "warning": "Please enter valid credentials"}) Also the screenshot of the browser return an error … -
Cannot increment object latest value in using django
I want to increment the value of the last id in the table so I could enter distinct values on the next rows. I'm using oracle 11g database for my python project. Please see my sample code... custID = Customer.objects.lates('CUSTOMER_ID') custID = int(custID) + 1 #received error custName = "Peter" Customer.objects.create('CUSTOMER_ID'=str(custID), 'CUSTOMER_NAME'=custName) #this line is ok and I got this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Customer' I tried to search online and changed my code like Customer.objects.create('CUSTOMER_NAME'=custName) but didn't worked because my it is not auto incremented on my database and python model. I also tried this.. custID = sum(int(custID), 1) Sorry, I'm just new in django. -
Getting Inverted image. Django based game
I am trying to make web-based snake&ladder game on Django, for which I am using matplotlib and mpld3 to create and display my game data on web page. I am able to get my image on the web page but it is inverted. Where am I going wrong in this code? my views.py file: import matplotlib.image as mpimg import os import mpld3 as mpld3 import numpy as np import matplotlib.pyplot as plt def home(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dir_img = os.path.normpath(os.path.join(BASE_DIR, 'resources')) image = mpimg.imread(os.path.normpath(os.path.join(dir_img, 'platform3.png'))) x = np.arange(0, 360, 0.01) y = 100 * np.sin(np.pi * x / 180) figure = plt.figure(dpi=100) subplot = figure.add_subplot(111) subplot.set_xlim(0, 10) subplot.set_ylim(0, 10) subplot.imshow(image, extent=[0, 10, 0, 10]) subplot.scatter(5.3, 0.8, marker="s", color='r', s=100, alpha=.7) subplot.scatter(0.8, 0.8, marker="^", color='b', s=100, alpha=.7) subplot.scatter(0.8, 0.3, marker="o", color='g', s=100, alpha=.5) subplot.scatter(0.3, 0.3, marker="*", color='#cccc00', s=150, alpha=.9) subplot.axes.get_xaxis().set_visible(False) subplot.axes.get_yaxis().set_visible(False) canvas = FigureCanvas(figure) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) dir_template = os.path.normpath(os.path.join(BASE_DIR, 'templates')) paths1 = str(os.path.normpath(os.path.join(dir_template, 'graph.html'))) with open(paths1, 'w') as f: f.write(mpld3.fig_to_html(figure)) f.write("Hello") return render(request, paths1) should I provide the generated graph.html file too? -
Django exercises
I did enough search in google before posting here about this topic and I didn't find what I am searching for. I just finished learning Django. Now,I would like to practise Django and become an expert in Django. I would like to practise Django by doing simple,intermediate and expert level Django exercises and assignments. Where Can I find such assignments or exercises? -
How to add forms to formset Dinamically on browsable django Rest API?
I want to add multiple forms dynamically in django rest API. Just like we do in django admin. we use modelforset and we dynamically add those formset with AJAX. i want to do the same in API.This image is the sample representation i need in API Thank You -
Is there a way to redirect from 127.0.0.1/8000 to Django admin site?
I changed page 127.0.0.1/8000 for an index page, now what I am interested to do is to put a button and that this button redirects me to the admin site of my app. I still do not know much about Django's urls and views, I would appreciate any tip or answer to help me with my problem. -
Python ImportError: No module named djng
Not sure what is the correct package to be installed. When I do pip install djng I get this error message. pip install djng Collecting djng Could not find a version that satisfies the requirement djng (from versions: ) No matching distribution found for djng -
Django template loader not loading templates from file system. TemplateDoesNotExist
OS: Windows 10, Django: 1.10.4, Python: 3.5.2 In the above image the django.template.loaders.filesystem.Loader should be listed, but it is not listed. Does this mean that it is not looking into the app directories? My settings.py(Template section) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Installed app section from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] My app directory structure: foo foo ... urls.py app_bar ... urls.py db.sqlite3 manage.py foo/urls.py urlpatterns = [ url(r'', include('app_bar.urls')), url(r'^admin/', admin.site.urls), ] app_bar/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), ] I can provide more info if required. -
centos 6.8 pip install error HTTPSHandler
hello I have a problem about pip install error when I type the pip in the terminal, it returns this massage Traceback (most recent call last): File "/usr/local/python2.7//bin/pip", line 9, in load_entry_point('pip==8.1.1', 'console_scripts', 'pip')() File "build/bdist.linux-x86_64/egg/pkg_resources/init.py", line 542, in load_entry_point File "build/bdist.linux-x86_64/egg/pkg_resources/init.py", line 2569, in load_entry_point File "build/bdist.linux-x86_64/egg/pkg_resources/init.py", line 2229, in load File "build/bdist.linux-x86_64/egg/pkg_resources/init.py", line 2235, in resolve File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/init.py", line 16, in from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/vcs/subversion.py", line 9, in from pip.index import Link File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/index.py", line 30, in from pip.wheel import Wheel, wheel_ext File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/wheel.py", line 39, in from pip._vendor.distlib.scripts import ScriptMaker File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/distlib/scripts.py", line 14, in from .compat import sysconfig, detect_encoding, ZipFile File "/usr/local/python2.7/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/distlib/compat.py", line 31, in from urllib2 import (Request, urlopen, URLError, HTTPError, ImportError: cannot import name HTTPSHandler How can I do to solve this? -
How to start afresh with a new database in Django?
I deleted my database. I want to start afresh with a new database. How can I do that ? I tried making a new datasource but it gives me an error while applying migrations/or migrating that it couldn't find the tables? Which is true because its an empty database. A similar scenario would be when some one pulls a version of my code. He wouldn't have migrations or the database (untracked). How would he run the application? -
Django Rest Framework Arbitrary Relationship Field
I am struggling to find a way to create an arbitrary relationship between two models in Django/Rest Framework. Consider a table the exists with a primary key, that logs actions permissible by some user or group, the table would look like this: Auth: pk | user | action And pk is an auto-generated integer. I need to create a view, or non-managed model, that correctly retrieves relationship info, as if it had a foreign key in this table. The general idea is that a route like this: /customauth/test/ Would produce all the things that user is authorized to do. Keep in mind that just making a custom attribute(s) and populating them with querysets in the view will not solve the problem, as I am using JSON-API, which specifically reports things that are relationships as such. Basically, I need to make a related field (either in serializers or models) that behaves like a completely custom dataset. I provide the relationship based on the queryset, or manually indicate what fields are 'related'. Here is a sample desired response: { "data":{ "type":"CustomUserAuthDetailView", "id":"test", "attributes":{ "user":"test" }, "links":{ "self":"http://127.0.0.1:8000/auth/test/" } }, "relationships":{ "auth":{ "links":{ "self":"/customauth/test/relationships/auth" }, "data":{ "type":"auth", "id":"1" } } } } the … -
Issue with django staticfiles amazon S3
i just having this issue, and I wonder if you can help me, I'm using django 1.7, my project runs great on local, I make a deploy in EC2 of amazon, with nginx, gunicorn, etc, the project runs well in the instance of EC2, but when I config the settings in the production.py, the styles, images upload to the bucket in S3, but doenst load in the project, in the main page. Im using pillow for the administration of the images and static.. I just dont know why it doesnt work, because the static files are in the bucket. Please help me, here I put the codes of my base.py, production.py. I used python manage.py collectfiles and , it collects, but it doesnt load the styles when I open the project in the web. BASE.PY from unipath import Path BASE_DIR = Path(__file__).ancestor(3) SECRET_KEY = '<my secret key>' DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) LOCAL_APPS = ( 'apps.eventos', 'apps.users', ) THIRD_PARTY_APPS = ( 'social.apps.django_app.default', ) INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'ueventos.urls' WSGI_APPLICATION = 'ueventos.wsgi.application' LANGUAGE_CODE = 'es' TIME_ZONE = 'UTC' DATE_FORMAT = …