Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
rich text editor for django with image upload and base64 convertor
I know this seems like a duplicate question but I couldn't find the answer to this specific problem on any other questions. I'm looking for a rich text editor on django which I can use in my form and upload some images. I need to be able to show these images. Also preferably I would like to be able to convert the images to base 64 and encode it in the message rather than saving an image file on my media folder. so far I have tried a few packages like tinyMCE and redactor. does anyone know a good package for this?? or how to get the packages I already tried to do this? thanks in advance -
Importing Custom Module In Django "No Module Named custom_module" Error
I wrote a simple module which I need to import into my Django settings file. The importation occurs in the following section in the libraries dictionary: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), #re-route the search for templates into this custom template directory os.path.join(os.path.join(BASE_DIR, 'templates'), 'tshirt-theme'), #Uncomment the line below to restore the original Oscar template #OSCAR_MAIN_TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', ], 'libraries': { 'promotion_tags': 'custom_oscar.templatetags.promotion_tags' } }, }, ] The trouble is that I get an error. Here it is: InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'custom_oscar.templatetags.promotion_tags': No module named custom_oscar.templatetags.promotion_tags The code works on my local machine, but fails when I migrate it to production (Ubuntu 16.01). The structure of my project is as follows: /var/www/vhosts/book/ ...book-site custom_oscar templatetags promotion_tags.py manage.py book settings.py wsgi.py .. ...book-env bin Initially I suspected that the problem may be with the path, so I checked the trace, and the correct path seems to be included: Python Path: ['/var/www/vhosts/book/book-site', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/var/www/vhosts/book/book-env/lib/python3.5/site-packages'] Could anyone tell me why this error occurs? How can I fix it? … -
django with ajax like and unlike
I , so I wrote an application with django and implemented a like and unlike function but I noticed that it works fine but the problem is if a user likes a post and decides to unlike it , the likes . count would go to -1 instead of 0 and thus it is possible for a two users like to become 3 but if one of the two unlikes it then it goes to 1 . below is my jQuery function jQuery $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) view.html <p><a class='like-btn' data-href='{{ obj.get_api_like_url }}' data-likes='{{ obj.likes.count }}' href='{{ obj.get_like_url }}'>{{ obj.likes.count }} Like</a></p> View.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions class PostLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) … -
mimeType error Django 1.9 Pinax-Referral
I am trying to run pinax referral app in my Django 1.9 project but get this error. I have tried to change the mimeType to content_type in the views.py but nothing changed in the error. Any ideas? /Library/Python/2.7/site-packages/pinax/referrals/views.py:47: RemovedInDjango110Warning: The context_instance argument of render_to_string is deprecated. context_instance=RequestContext(request) Internal Server Error: /referrals/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/django/views/decorators/http.py", line 42, in inner return func(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/pinax/referrals/views.py", line 50, in create_referral mimetype="application/json" File "/Library/Python/2.7/site-packages/django/http/response.py", line 283, in __init__ super(HttpResponse, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'mimetype' [13/Aug/2017 13:58:37] "POST /referrals/ HTTP/1.1" 500 77425 -
Django request.user is model, for admin and normal user
I want to autocomplete 2 fields: created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by') updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by') for normal users and for django admin. If for normal users I can use get request.user from my view(found some solutions here on the site),but this is not the case for admin/staff because I don't control the views, so I'm searching for a solution at the Model level by overwriting the save function. -
Where in my django view I should catch exceptions?
I have same code delivered to 2 identical heroku dynos but it behaves differently I am getting error on my customer PROD environment that I am not getting locally and in test . It is running on Heroku - All I am getting is 404 error in Debug mode. I am sure it is related to data base differences.And I am sure the way I am coding should be improved with regards on how to catch and handle errors. So some guidance will be great . How should I improve my view below to catch exceptions and to get clear picture on the issue? I assume best practise will be to add try and except. In what parts of this code It would be good idea to do it? @login_required def dashboard_rent(request): leasetermstotal = LeaseTerm.objects.all() count_leasetermstotal = leasetermstotal.count() leaseterms = LeaseTerm.objects.filter( is_active = True ) count_leaseterms = leaseterms.count() leaselist = Lease.objects.filter( is_active = True ) count_lease = leaselist.count() leaselisttotal = Lease.objects.filter() count_leasetotal = leaselisttotal.count() negative_balance_term = [obj.id for obj in leaseterms if obj.current_balance < 0] count_negative_balance_term = LeaseTerm.objects.filter(id__in=negative_balance_term).count() try: general_id_dict = General_configurations.objects.filter(is_active = True ).aggregate(Max('id')) if general_id_dict: general_id = general_id_dict['id__max'] general_dict = get_object_or_404(General_configurations, pk=general_id) else: general_dict = "no data" except … -
Using FileType with django custom management commands?
I have a CSV file with data I want to import using a custom command from the Django Custom Management commands. I'm using Python 2.7 and Django 1.10. Here is the code. import csv import argparse from awards.models import Student, HomeRoom from django.core.management.base import BaseCommand, CommandError homeroom = 'HR 12C' class Command(BaseCommand): help = "Import students by homeroom." def add_arguments(self, parser): parser.add_argument('csvfile', nargs='+', type=argparse.FileType('r')) def handle(self, *args, **options): student_list = [] hr = HomeRoom.objects.get(name=homeroom) with open(options['csvfile']) as csvfile: reader = csv.DictReader(csvfile) for row in reader: student_list.append(Student(name=row["Student Name"], studentidnum=row["School ID"], homeroom=hr)) Yeah, homeroom is hard-coded. I'd rather pull that value from the filename (which is 'HR 12C.csv') but I'm not sure how to do that. But that's not the real problem. When I run the above code with this command: python manage.py importcsv 'awards/12C.csv' I get the following error: File "/home/ssidollars/dollars/awards/management/commands/importcsv.py", line 18, in handle with open(options['csvfile']) as csvfile: TypeError: coercing to Unicode: need string or buffer, list found I have no idea what I'm doing wrong. It seems to think thinks I'm passing it a list, but... I don't see any lists which it could be. Any ideas what I'm doing wrong? -
Deploying Django app to Azure throws Error occurred while reading WSGI handler
I'm trying to deploy a Django App to Azure App Services through Visual Studio 2015 and stuck with an error on server. This question already have been posted but no valid work around has given. I'm using: Python 3.4 Django 1.11.3 On localhost everything is working perfectly The error displayed on browser. The page cannot be displayed because an internal server error has occurred. I have enabled logging for wsgi from 'App Settings' and got detailed error: Error occurred while reading WSGI handler Traceback (most recent call last): File "D:\home\site\wwwroot\env\Lib\site-packages\django\apps\config.py", line 111, in create entry = module.default_app_config AttributeError: 'module' object has no attribute 'default_app_config' Here is the log file with all traceback : log file This is my uwsgi.py file : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xSettings.settings") application = get_wsgi_application() Web.config and ptvs_virtualenv_proxy.py are the same as pointed in documentation Configuring Python with Azure App Service Initial I was thinking it's a problem with my python version and have created a dummy Django app, created the environment from the same python version, installed all packages from requirements.txt from my real project and published it, and everything worked perfectly (see the dummy app) Any idea, thoughts on what I'm … -
Django: Implementing a Form within a generic DetailView
After working through several google search result pages, I am still desperately stuck at the same problem. I am trying to implement a comment field underneath a blog post. I am thankful for any hints and advice! I am working on a Blog in Django which is set up with a first, generic ListView to display briefly all available blog posts and with a second, generic DetailView to show the specific blog post in more detail. I now want to place an add_comment_field underneath the specific blog post with all other comments shown underneath. It works when the comment form is displayed on a separate page but not on the same page as the DetailView, which is the desired outcome. I suspect this has to do with the interplay between views.py and forms.py but I cannot figure out the problem. Again, thank you so much for your help! views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Post, Comment from .forms import CommentForm from django.views.generic.detail import DetailView class ParticularPost(DetailView): template_name='blog/post.html' model = Post def add_comment_to_post(self, pk): post = get_object_or_404(Post, pk=pk) if self.method == "POST": form = CommentForm(self.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) … -
How to slice the list of results in django [on hold]
I have a list of category results in 56 records. I would like to divide it into about 3-4 columns. I'm using a slice tag {% for wpis in wpisy_kat %} <a href="{% url 'detale_kat' slug_kat=wpis.slug_kat %}">{{ wpis|slice:":15" }} </a> ({{ wpis.cnt_witryna }}) <br /> {% endfor %} but it does not work. -
Integrate django project with dajngo cms
I want to dynamic my web content like wordpress. I have already built the website using django. Recently I have heard about dajngo-cms. Is it efficient if I want to move from django to dajngo-cms or can I add table for every page contents? I want anyone can change the content from admin panel. If suggestion is to integrate django project with dajngo-cms then how can I create my existing template and make it dynamic? -
Django-Celery : worker does not execute task
I've been trying to run some test with Celery, RabbitMQ, Django.. The problem is that once i have spawned a worker, i use django to send a task thanks to .delay() which is received by the worker but from what it looks like, the worker does not find a task of that name to execute. Weird thing since this task with the exact same name is is the list of tasks the worker is supposed to be able to execute. Here it is: -> settings.py BROKER_HOST = "127.0.0.1" #IP address of the server running RabbitMQ and Celery BROKER_PORT = 5672 BROKER_URL = 'amqp://' CELERY_IMPORTS = ('notify') CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = "amqp" CELERY_IMPORTS = ("notify") -> __init__.py (under notify module) import celery from celery import app as celery_app from notify.user.tasks import send_email -> tasks.py (under notify module) import os from celery import Celery, task from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.config_from_object('app.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=False) @task() def send_email(recepient, title, subject): print('sending email') And here is how i spawn my worker at the root of my project: celery worker -n worker_one -l debug -A notify Here is the error i get when the worker receive notification of … -
can't get media files in heroku
I deployed mu project in heroku successfully. The only problem is that I can't find media files on heroku. When I type .../media/pic1.png locally , I get the picture in the browser. But, in heroku,, that gives Page not found (404) Request Method: GET Request URL: ...../media/pic1.png Raised by: django.views.static.serve Path ...../media/pic1.png doesn't exist settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') project/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^admin_platform/', include('admin_platform.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
making migrations for django project folder
I'm building a Django app from an existing database. The existing database is all set up and working as I need it to. The models for this existing project were automatically placed in my project directory. Here is a rough idea of the relevant directories: myProject | manage.py | myProject | | models.py <- auto generated models were placed here (also new models here) | app1 | | models.py | | migrations I figured my new models would be accessed by all apps I install, so I've included some more models in the same models.py as the auto generated one. Running makemigrations does not seem to pick up any changes I've made. (I've even included 'myProject' in installed apps) How do I migrate these changes? -
Using django select_for_update without rolling back on error
I'm trying to utilize django's row-level-locking by using the select_for_update utility. As per the documentation, this can only be used when inside of a transaction.atomic block. The side-effect of using a transaction.atomic block is that if my code throws an exception, all the database changes get rolled-back. My use case is such that I'd actually like to keep the database changes, and allow the exception to propagate. This leaves me with code looking like this: with transaction.atomic(): user = User.objects.select_for_update.get(id=1234) try: user.do_something() except Exception as e: exception = e else: exception = None if exception is not None: raise exception This feels like a total anti-pattern and I'm sure I must be missing something. I'm aware I could probably roll-my-own solution by manually using transaction.set_autocommit to manage the transaction, but I'd have thought that there would be a simpler way to get this functionality. Is there a built in way to achieve what I want? -
Need help finding installed_app setting in Django
I am having trouble finding where the installed_app setting is in the django folder. i can't seem to find anything related to this "setting". Can anyone help? -
The category view is repeated many times instead of once in django
I have a problem displaying a category view from a Kategorie class. The query shows me correctly the number of pages added to a category, but this action is repeated more than once. When I check the detailed view for the displayed categories in one loop, each of the displayed categories has the same address. This action is repeated for each category where the next loop displays a detail view for the next category and so on. This mis my views.py for that method: def widok_kategorii(request): kategorie = Kategorie.objects.all().order_by('glowna') return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie}) def index(request): wpisy_kat = Kategorie.objects.annotate(cnt_witryna=Count('witryna')).order_by('glowna') return render(request, 'firmy/index.html', {'wpisy_kat': wpisy_kat}) The widok_kategorii.html {% for kategoria in kategorie %} {% for wpis in wpisy_kat %} <a href="{% url 'detale_kat' slug_kat=kategoria.slug_kat %}">{{ wpis }} </a> ({{ wpis.cnt_witryna }}) <br /> {% endfor %} {% endfor %} And the part of index.html to display the widok_kategorii.html <h3><center>Kategorie</center></h3> <center>{%include 'firmy/widok_kategorii.html'%} </center> -
How to configure i18n_patterns in Django Cookiecutter generated urls.py?
The Django Documentation gives the following example for adding language prefixes in urls: from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from about import views as about_views from news import views as news_views from sitemap.views import sitemap urlpatterns = [ url(r'^sitemap\.xml$', sitemap, name='sitemap-xml'), ] news_patterns = ([ url(r'^$', news_views.index, name='index'), url(r'^category/(?P<slug>[\w-]+)/$', news_views.category, name='category'), url(r'^(?P<slug>[\w-]+)/$', news_views.details, name='detail'), ], 'news') urlpatterns += i18n_patterns( url(r'^about/$', about_views.main, name='about'), url(r'^news/', include(news_patterns, namespace='news')), ) But the urls.py file generated by Django Cookiecutter is the following: urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), # Django Admin, use {% url 'admin:index' %} url(settings.ADMIN_URL, admin.site.urls), # User management url(r'^users/', include('lingodream.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Where should I add i18n_patterns in there? Thanks a lot! -
Single page applications Django Python and SEO
I want to run my single page app in production. Since I'm using rest API and ajax calls to deliver the content from the backend to the front end for SEO reasons I need to have a no javascript version of my content available for the crawler bots. I have a url for no javascript version of the content but since the webserver is running on port 8000 to access the no javascript files I need to navigate to mydomain.com:8000/nojs. My apps url looks like the code below: urlpatterns = [ url(r'^nojs/$', views.nojs), url(r'^blog/all/$', views.allTitles), url(r'^post/(?P<id>[\d+]+)/(?P<title>[\w+]+)/$', views.viewArticle) ] and my nojs method is simply a hello message: def nojs(request): return HttpResponse("Hello") I'm guessing I need to create some changes in my Nginx configuration to access the nojs method without using the 8000 port after my domain name. How can I navigate to mydomain.com/nojs and get the hello message without using the 8000 port? -
Django S3storage collectstatic ConnectionAbortedError
I'm using django version 1.11, and try to attach Amazon S3 Storage with boto3. I choose Tokyo Region and Set IAM Roles, policies and settings.py according to documents. But when I try "manage.py collectstatic", ConnectionAbortedError happens when uploading more than 50KB files. I tested several times with different size of files, and I found that It fails when it uploads each file which size is over 50KB. Is there any default settings for upload file size, or connection time? If I remove all static files which size is less than 50KB, It works well.. -
Referencing a particular element in a list in django
I am trying to copy the elements of one list to another, and i am using this piece of code to do that: {% for i in range(2,7) %} {{ list1.append(list2|lookup:i) }} {% endfor %} list1 is an empty list. I have also defined this custom filter lookup like this: @register.filter def lookup(d, key): return d[key] But this does not work , I am getting this error: TemplateSyntaxError at / expected token ',', got ':'. What am i doing wrong. I am new to django and jinja template. -
Django celery ImportError: no module named celery when using gunicorn bind?
I have been searching everywhere for an answer to this. I am setting up a server for my Django website on Ubuntu 16.04 (digital ocean) and my Django site requires the use of celery for some periodic tasks. It works in my development environment. And running python manage.py celery beat and python manage.py celery worker work just fine. It was all installed inside a virtualenv as well. Here are my files: # __init__.py from __future__ import absolute_import from .celery_tasks import app as celery_app # noqa # celery_tasks.py from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') from django.conf import settings # noqa app = Celery('myproject') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) And this is the error that has been happening: # gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application File "/root/myproject/myproject/__init__.py", line 2, in <module> from .celery_tasks import app as celery_app # noqa File "/root/myproject/myproject/celery_tasks.py", line 4, in <module> from celery import Celery ImportError: No module named celery [2017-08-13 07:29:36 +0000] [5463] [INFO] Worker exiting (pid: 5463) [2017-08-13 07:29:36 +0000] [5458] [INFO] Shutting down: Master [2017-08-13 07:29:36 +0000] [5458] [INFO] Reason: Worker failed to boot. There is also … -
django.contrib.auth.models.DoesNotExist: User matching query does not exist
I tried to create an instance of a user in python shell using the following commands. from django.contrib.auth.models import User User.objects.all() <QuerySet [<User: admin>]> me = User.objects.get(username='rohan') After which I got the following errors. Can someone please help. Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name django.contrib.auth.models.DoesNotExist: User matching query does not exist. -
How to get user specific object using django generic class detailview?
How do I get the current user related object using django's generic class DetailView? Using function based views, I can obtain the object like this: def foo(request): friendProfile = get_object_or_404(request.user.profile.friends,username="admin") What is the equivalent using detail view? I'm guessing it's something related to get_object or get_context_data but I can't fully understand the documents. Thank you. -
Why is {% load static %} a dependency for {% get_media_prefix %}?
I've been using {% get_media_prefix %} for a very long time. I was explaining this to someone when he pointed this out. Why do I need to declare {% load static %} in order to use it? It even uses in the documentation's example code here. To an extent I understand that static files and media files are similar in nature. Even when we use them with combination of nginx+gunicorn, nginx handles both of them(we let everything else proxy, but not these). But still we have a separate MEDIA_URL and STATIC_URL as well as MEDIA_ROOT and STATIC_ROOT defined for these files. Then why {% load static %} needs to be declared in order to use {% get_media_prefix %} ? Thanks in advance.