Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
configure the django with Oracle 11g data base issue
Oracle database configurations with Django and while migrating the application facing the error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the dja ngo_migrations table (ORA-02000: missing ALWAYS keyword) application environment 1.windows10 2.Python 3.6.x 3.Django 2.0.2 4.oracle 11g XE in settins.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'abc', 'PASSWORD':'xxxx', 'HOST':'localhost', 'PORT':"1521", } -
django ugettext msguniq: too many errors, aborting
I was working with ugettext for translation and it was ok , but i dont know what has happened that when i write django-admin makemessages on command, it shows this lots of errors: CommandError: errors happened while running msguniq C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite \locale\d jango.pot:25:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:70:3: syntax error msguniq: too many errors, aborting I also have imported from django.utils.translation import ugettext as _ at the top of my codes -
HttpResponse. How to use it properly?
all. I am newest in Django and I have a question. I want learn what I need return to ajax get/post request. I have example, but I know it is not good. Can u please explain me about responses? When, what and why? I did not find any information about it. When I click on button, object will delete from data base. This is my ajax request: function removeProduct(){ $('.btn-remove').click(function(e){ e.preventDefault(); var data = {}; data["csrfmiddlewaretoken"] = $('#quantity_goods [name="csrfmiddlewaretoken"]').val(); var product = $(this); data.product_id = product.data("product_id"); var url = product.attr("action"); $.ajax({ url: url, type: 'POST', data: data, cache: true, success: location.reload(), }); }); } This is my view: def remove_product(request): """Remove product from basket.""" data = request.POST product_id = data.get('product_id') product = ProductInOrder.objects.filter(id=product_id) product.delete() return HttpResponse() -
working with django forms and templates
I am working with django frame work as fresher and my senior gave me the template and told me to create a Form which contains 4 fields(name,email address,phone number,message), the main task is the above field details when filled and clicked on send button the data should be received on his email address. Please help with this. {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <style> body{ background: url('{% static "img/new4.jpg" %}') no-repeat center fixed; - webkit- background: cover; - moz - background: cover; - o - background: cover; background-size: cover; } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Personality Leading.com</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom' %}"> --> <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom.css' %}"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <div class="mynav"> <div class="p-3 mb-2 bg-info text-white"><strong> PERSONALITY LEADING </strong></div> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand" href="index.html"></a> <button … -
how should I access a view function with a Custom name from urls?
I have a API view class with some custom named functions, like this: class UserList (APIView): def listusers (self , request): users = User.objects.all() jason = UserSerializer (users , many=True) return Response (jason.data) how could i tell the url patterns when you got an special url do what in this function? -
Django admin, changelist_view, ModelAdmin seems to act like a singleton
I noticed a strange behaviour while extending ModelAdmin. I have this code: class MakeModelAdmin(admin.ModelAdmin): ... def changelist_view(self, request, extra_context=None): if request.user.is_superuser: self.list_display = ['company', 'name'] # else: # self.list_display = ['name'] return super().changelist_view(request, extra_context=extra_context,) The goal is to change list_display dynamically based on user (supervisor or not). I log in with two different users, in two different browsers, one of them results to be a superuser, the other isn't. self.list_display is set by one of users but debugging the request with the other user I can see the variable still set, so it changes the next behavior of the other user's view. Uncommenting the lines it works but I don't like it at all. It seems to me it's acting like a singleton. I also tried to change to: super(MakeModelAdmin, self).changelist_view(request, extra_context=extra_context,) But it has the same effect. Is there any solution for that? Maybe this is not the right way to achieve my goal? -
(CSRF token missing or incorrect.) using AJAX in Django
So I am trying to create some basic search functionality to my Django project using Ajax. However, I keep getting an error about the CSRF token. Here is the javascript in my template: <script type='text/javascript'> var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $('#search').keyup(function () { var search_text = $(this).val(); console.log(search_text); $.ajax({ type: "POST", url: "/search/", data: { 'search_text': search_text, }, success: function (data) { console.log('it worked'); }, }); }); </script> Any ideas why this isn't working? -
How to display uploaded file to user
I have a django view function that allows the user to upload a file. After the upload completes, the user just needs to be shown a file on a page. If I save the file, I can find it the media cdn I've set up and can view it using the link generated in the table in django admin, but what I'm trying to do is return the image that the user uploaded as a response back to them to view it. Here is the code I have for the view: def home(request): title = "Upload your photo" form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): instance = form.save(commit=False) instance.save() name = "" for filename, file in request.FILES.iteritems(): name = request.FILES[filename] imageFileName = name imageUrl = imageFileName if form != None: return HttpResponseRedirect(imageUrl) context = { "title" : title, "form" : form } return render(request, "home.html",context) Right now, when the image is uploaded, the user is just redirected to a url with the filename concatenated to the original url but the image isn't displaying. How can I redirect the user to a page with the image they just uploaded? -
Failing to connect to mysocket.sock, connection refused (gunicorn, nginx)
Full error: 2018/03/12 04:59:08 [error] 1562#1562: *1787 connect() to unix:/home/mik e/movingcollage/movingcollage.sock failed (111: Connection refused) whil e connecting to upstream, client: 107.205.110.154, server: movingcollage .com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/mike/movin gcollage/movingcollage.sock:/", host: "movingcollage.com" My config is ok, this used to work; I pulled some new application code and am now getting a 502 bad gateway error (before I pulled the application code the site worked fine). I already did service gunicorn restart and systemctl restart gunicorn and am still getting the 502 bad gateway error. Can anyone help? This is a django project, for what it's worth. -
Django server redering and send react-like diff to client
I looking for a solution that allows me to work with Django in the server side but instead of sending a full page each view or change to the client, it kind automatically sends just the data like in a REST API. REST APIs have the advantages of just transmitting the data with little overhead. But for some kind of applications, Django is really neat and useful to solve the model and view handling, especially when handling a lot of forms and CRUD. I'm looking for a tool that allows the compromise of the Django utilities and a REST API ( in the sense of just sending the data). I think it's possible but I can't find any tool. One possible way to do it is keeping track of the client status of the page, like the last page rendered. When the user changes something (like go do next record), the server renders the page again, and then create a DOM diff from the previous page, in the way React framework does, and it sends the diff to the client instead of the full page. In the client, it takes this diff and applies it. So in the client perspective, … -
TemplateDoesNotExist at /hello/ Django error
I am a beginner at django python. I am getting an above error although I am having my template a correct directory. My view.py is like this. from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render def hello(request): return render(request,"C:/Users/Vivek/myproject/myapp/template/hello.html",{}) I am having hello.html at C:\Users\Vivek\myproject\myapp\template Below is the error I am getting. TemplateDoesNotExist at /hello/ C:/Users/Vivek/myproject/myapp/template/hello.html Request Method: GET Request URL: http://127.0.0.1:8000/hello/ Django Version: 1.11.10 Exception Type: TemplateDoesNotExist Exception Value: C:/Users/Vivek/myproject/myapp/template/hello.html -
How to prevent a row count from being sent to the db when paginator is disabled
I'm using Django 1.11, Django-tables2 1.19.0 with MS SQL via django-pyodbc-azure 1.11.0.0. I'm showing a table for a model that is for a rather slow view which unfortunately must run sub-queries for every row. I can't change the view, and so I've disabled the paginator for tables2 and done a slice to limit the number of rows the view subqueries will run on: def my_view(request): queryset = my_model.objects.all() table = my_table(queryset.all()[:25]) # <- only get top 25 RequestConfig(request, paginate=False).configure(table) return render(request, 'my_template.html', {'table': table}) I also disabled ordering for the columns. That works, however, when using django-admin-toolbar, I can see that a "...COUNT_BIG(*) FROM (SELECT TOP 25..." is nevertheless being sent to the server. I want to prevent that COUNT_BIG if possible for performance reasons, but my various misguided attempts over the last few days have all met with horrible failure. I'd really appreciate any help with this one. Thanks. -
Html slim for Django
So, I've been working with Ruby on Rails recently, and I currently use Html slim as it is easier to write Html and ruby code in it. So my question is: Is there a tool similar to Html Slim for Django? Regards, Anthony -
How to get the filepath for file in a media cdn
I have a django view function that allows the user to upload a file to the media cdn. After the upload completes, the file needs to be immediately opened with the user being redirected to a new page with the file. Right now, I can go directly to a page that displays the file using the url: localhost/media/<filename.png> but I haven't been able to figure out how to redirect the user to this page. In my view, I have the following code: def home(request): title = "Upload your photo" form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): instance = form.save(commit=False) instance.save() name = "" for filename, file in request.FILES.iteritems(): name = request.FILES[filename] imageFileName = name imageUrl = static(imageFileName) if form != None: return HttpResponseRedirect(imageUrl) context = { "title" : title, "form" : form } return render(request, "home.html",context) I was attempting to use the static() method to get the url for the image that is contained in the media cdn, but instead of including "media" in the path, it includes "static." In the Django docs, it says something about only using the path "/media/" locally, but I'm not sure how else this would … -
Django + Heroku celery module not found
I'm trying to push my lastest version of my webapp live to Heroku. I'm pretty comfortable pushing to Heroku and this just doesn't seem right. For some reason I feel like Heroku is skipping my requirements.txt. Just in case I manually installed celery on my Heroku app. I'm getting this specific problem with celery, but if Heroku is skipping my requirements.txt this might be a bigger problem. 1. If I run: heroku run pip install celery This let's me install the package over and over, shouldn't it kick back a "requirement already met" error? 2. When I try to push to heroku, I keep getting a File "/app/config/_celery.py", line 4, in <module> from celery import Celery ModuleNotFoundError: No module named 'celery' for the life of me I can't figure out why, I've uninstalled celery, reinstalled it locally. It's on my requirements.txt (Heroku should install it upon push to the remote). celery also seems to work locally just fine. I'll include what I think is necessary, but let me know if I'm missing something that might provide the answer. Here's my projects file structure: POTRTMS(overall project folder) | +-config(holds settings) | | | +--settings | | | | | __init__.py | … -
'JpegImageFile' object has no attribute '_committed' error when using PIL
I'm using PIL to compress uploaded images(FileField). However I'm getting an error which I believe is a problem of double saving? (saving my image, and then saving the whole form which includes the image). I wanted to perform commit=False when I'm saving the image but it doesn't appear it's possible. Here's my code: ... if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user if instance.image: filename = instance.image instance.image = Image.open(instance.image) instance.image.thumbnail((220, 130), Image.ANTIALIAS) instance.image.save(filename, quality=60) instance.save() returns 'JpegImageFile' object has no attribute '_committed' error on the last line (instance.save()) Can someone identify the problem? - and any idea how I can fix it? -
How do I perform save on all records in Django?
In one of my models I want to add a field that depends on other fields of the same model and will be calculated when the record is saved. In my database there are already records, so I thought that I could accomplish this by performing save. I have tried save on a single record and it seems to work. For more records can I use a loop like this: for each_product_record in Product.objects.all(): each_product_record.save() Is there a better way or are there any caveats I should know before hand ? -
Django admin change_view not called
I'm trying to redefine a ModelAdmin for a model in this way: class MakeModelAdmin(admin.ModelAdmin): ... # def changeform_view(self, request, object_id, form_url='', extra_context=None): # if not request.user.is_superuser: # self.exclude = ('company',) # extra_context = extra_context or {} # return super().changeform_view(request, object_id, form_url, extra_context=extra_context,) def change_view(self, request, object_id, form_url='', extra_context=None): if not request.user.is_superuser: self.exclude = ('company',) extra_context = extra_context or {} return super().change_view(request, object_id, form_url, extra_context=extra_context,) admin.site.register(Make, MakeModelAdmin) But method change_view is not called. At the same time, the commented code changeform_view is called. I checked and ModelAdmin contains both of methods. I can't figure out why "change_view" is not called where "changeform_view" is called (obviously when uncommented). Documentation suggests change_view: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.change_view I'm using Django 2.0.2 -
How to raise multiple ValidationError on Django?
from rest_framework.exceptions import ValidationError def to_representation(self, request_data): raise ValidationError({ 'field_name': ["Field not allowed to change"] }) In the example above how can I throw multiple validation errors? I want to throw them as dicts to show at the respective fields. -
KeyError when trying to compress image using PIL
I'm trying to compress uploaded images using PIL for quicker uploads. Here's my views: print(instance.image) #prints "imagename.jpg" instance.image = Image.open(instance.image) print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=3190x2159 at 0x10EE73A20>" instance.image.thumbnail((220, 130), Image.ANTIALIAS) print(instance.image) #prints "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=193x130 at 0x10EE73A20>" instance.image.save(instance.image, quality=60) that last line sparks the error. Traceback: File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/zorgan/Desktop/project/site/post/views.py" in post 55. instance.image.save(instance.image, quality=60) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/PIL/Image.py" in save 1713. format = EXTENSION[ext] Exception Type: KeyError at /post/ Exception Value: '' Any idea what the problem is? -
Django Suit - Django CMS 3.5 compatibility
I have a project built on Django 1.11 with Django CMS 3.5 for content management, but I would like to have Django Suit as the front end part of my admin. The problem is that Suit doesn't support Django CMS since version 2.4 and a lot of the functionalities that it adds to the admin don't work anymore. More specifically, the pages and content management view. I've been trying to fix the issues but haven't been able to find a way to make it work properly. Does anyone know how to get this done or if there's any other alternative that can give me the ui and features like Django Suit and that is compatible with Django CMS 3.5? -
Slugified subpages lead to NoReverseMatch
Still very new to Django. I am trying to create a website, where users can have profiles, and then profiles can have trip titles, e.g. site.com/user1/short-trip-to-canada I managed to display site.com/user1, and (after adding some additional code) I managed to display site.com/user/short-trip-to-canada separately. But in the latter case, if I go to site.com/user1, then i get the following error: NoReverseMatch at /app/hellothere/ Reverse for 'view_trip' with arguments '('chad-and-a-cheerful-anthem',)' not found. 1 pattern(s) tried: ['app/(?P<username>[\\w\\-]+)/(?P<trip_name_slug>[\\w\\-]+)/$'] I have been trying to figure out why, for a while. My views.py: @login_required def view_profile(request,username): user = get_object_or_404(User, username__exact=username) profile = get_object_or_404(UserProfile, user__exact=user) trips = Trip.objects.filter(owner=user).order_by('startDate').reverse() context_dict = {'user':user, 'trips':trips, 'profile':profile } return render(request,'view_profile.html',context_dict) def view_trip(request, username, trip_name_slug): context_dict = {} try: trip = Trip.objects.get(slug=trip_name_slug) context_dict['trip'] = trip except Trip.DoesNotExist: context_dict['trip'] = None return render(request, 'trip.html', context_dict) app/urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^pop_trips/$', views.pop_trips, name='pop_trips'), url(r'^recent_trips/$', views.recent_trips, name='recent_trips'), url(r'^best_travelled/$', views.best_travelled, name='best_travelled'), url(r'^most_active_travellers/$', views.contact, name='most_active_travellers'), url(r'^passport/$', views.passport, name='passport'), url(r'^add_trip/$', views.add_trip, name='add_trip'), url(r'^settings/$', views.settings, name='settings'), url(r'^my_trips/$', views.my_trips, name='my_trips'), url(r'^(?P<username>[\w\-]+)/$', views.view_profile, name='view_profile'), url(r'^(?P<username>[\w\-]+)/(?P<trip_name_slug>[\w\-]+)/$', views.view_trip, name='view_trip'), ] Templates: view_profile.html {% extends 'base.html' %} {% load staticfiles %} {% block title_block %} {{user.username}} {% endblock %} {% block body_block %} <h1>{{ user.username … -
Django filter with a lot of values ok PK
I do: qs = qs.filter(pk__in=qs_searches) with qs a (15000) QuerySet and sq_searches a big (+1000) haystack.query.ValuesListSearchQuerySet It takes a lot of time. More info: Indexation backend is Whoosh DB is currently sqlite pk has db_index=True (maybe useless) Is it possible to optimize it? -
Django: Programmatically save HTML page to PDF without using HTTP
views.py class PdfView(DetailView): model = TheModel template_name = 'pdf.html' urls.py urlpatterns = [ url( r'^(?P<pk>[0-9]+)/$', PdfDataView.as_view(), name='pdf-data', ), ] Visiting the relevant url, an html page is rendered. I need to programmatically save this html page to a pdf file on the server and avoid using an HTTP request or response to accomplish this. -
Django errors get overlapped, can't style them
I have a form and I decided to handle it manually. My form is actually from 2 forms, but that's not important. Thing is, that when I want to display the errors at the bottom of my form, they get overlapped on top of each other. I wanted to show one at a time, so I tried to use padding with overflow hidden for the form, but doesn't seem to work. Any style I apply won't work, except for margins. .alert { margin-top: 45% !important; } #errors { padding: 20px !important; } {% if form1.errors %} {% for field in form1 %} {% for error in field.errors %} <div class="alert alert-danger"> <strong id="errors">{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form1.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if form2.errors %} {% for field in form2 %} {% for error in field.errors %} <div class="alert alert-danger"> <strong id="errors">{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form2.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %}