Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does django differentiate between 2 management forms on same page?
I have 2 formsets based on 2 different models. While debugging a validation problem where my formsets were failing is_valid validation (see errors below): (Pdb) FormsetItem.errors [{'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That … -
how to get item from select option html Django?
I tried to implement 2nd dropdown based on the 1st dropdown and get the item from two dropdowns. <select class="js-example-basic-single" name="select1" id="select1"> <option value="1">Disease</option> <option value="2">Drug</option> <option value="3">Problem</option> <option value="4">Test</option> <option value="5">Treatment</option> </select> <select class="js-example-basic-single" name="select2" id="select2"> {% for item in content1 %} <option value="1" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content2 %} <option value="2" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content3 %} <option value="3" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content4 %} <option value="4" itemY="{{item}}">{{item}}</option> {% endfor %} {% for item in content5 %} <option value="5" itemY="{{item}}">{{item}}</option> {% endfor %} </select> and in JS: <script type="text/javascript"> $("#select1").change(function() { if ($(this).data('options') === undefined) { /*Taking an array of all options-2 and kind of embedding it on the select1*/ $(this).data('options', $('#select2 option').clone()); } var id = $(this).val(); var options = $(this).data('options').filter('[value=' + id + ']'); $('#select2').html(options); $("#select2 option:selected").text(); var conceptName = $('#select2').find(":selected").text(); }); </script> In views.py f2 = request.POST.get('select1',False) f3 = request.POST.get('select2',False) it return the value not item............ I want the item. Based ont he -
Getting error of to many arguments were given - django project
I have a django project with a django app called users. in the projects url settings I have it connected to the users app url python file. I want to connect them and have the urls base off of the url patterns in the users urls file.. WHile doing so, I am getting an error that there were to many arguments that were being passed and I have no idea what it means or any reference as to how I can fix this error. This is the main error that I am getting I am getting the error when i run the following command python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108629378> Traceback (most recent call last): File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = … -
What is happening when I run `python manage.py test` and on which port the django test server is listening?
I wrote a test for for a signup feature. When I do manually, the signup process sends email to the user, but when I do it with test script the email is not sent. So I was wondering what is happening inside? And what is the port for the test server? Is there any relation for the test server to send mail with it? Can I specify the test server port? -
How do you call a user defined function in views.py DJANGO
The requirement is to display the logged in username and his role in the organization in all the pages at the top right corner. The role can be identified by the permissions he is given. My approach: I thought of creating a user-defined function in views.py and call it in each and every other function. The function that I create should check the current user's permissions and based on them his role should be decided. All these details must be sent to base.html so that it will render and display the username and his role every time the page is loaded. Any suggestions on other approaches are welcomed and if my approach is entirely wrong please let me know. -
Django Session Data lost after clearing browser Data
Im using django 1.11.7 and the session objects to store data from users that are login works fine but when I clear the browser data the session object is lost, as far as I know if you use this 'django.contrib.sessions', you're setup to save the session object in the DB and im able to see Data in the Db each time someone logs in but the problem is that for some reason I cant use this data when i fetch it maybe is the way I fetch the data because the data is being saved in the DB here is how I fetch the data in the views: this is the normal way that works until I clear the browser data in_test = request.session['in_test'] then in some reading they suggest that even if the data is being saved in the db some cookies are created to match that data and they use this to some how also get the data from the session obj but same result: in_test = request.session.get('in_test') but at least there is a hint that the browser cookie is obviously missing since I cleared but the question is how to pair or directly fetch the session object … -
how to instantiate recursive foreign key in django?
class Notebook(models.Model): title=models.CharField(max_length=10) father = models.ForeignKey('self', on_delete=models.CASCADE) How to use it? n1=Notebook(title='a', father='???') n2=Notebook(title='b', father=n1) how to set the value for father attribute of n1? -
How to override Django admin `change_list.html` to provide formatting on the go
In Django admin, if I want to display a list of Iron and their respective formatted weights, I would have to do this. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight_formatted',) def weight_formatted(self, object): return '{0:.2f} Kg'.format(object.weight) weight_formatted.short_description = 'Weight' I.e: 500.00 Kg The problem with this however is that I would have to write a method for every field that I want to format, making it redundant when I have 10 or more objects to format. Is there a method that I could override to "catch" these values and specify formatting before they get rendered onto the html? I.e. instead of having to write a method for each Admin class, I could just write the following and have it be formatted. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight__kg',) def overriden_method(field): if field.name.contains('__kg'): field.value = '{0:.2f} Kg'.format(field.value) I.e: 500.00 Kg -
python two dictionary dynamically in for loop if condition based upon store
db fetched data key based upon generated for loop def data(request): from_date=2009-01-01 todate=2009-01-31 with connection.cursor() as cursor: cursor.execute("select id,name,no_of_apsent,no_of_lop,amount from pay where from_date='%s' and todate='%s'"%from_date,todate) fetched_data=cursor.fectall() a={} b={} for c,d,e,f,g in fetched_data: if f<=e: h=g*10/100 a[c]=h else: i=g/31 b[c]=i print(a,b) return render(request,hai.html,{'a'a,'b',b}) db fetched data key based upon generated for loop if condition true and key value based upon store for example {0:1,1:0,2:9} like this if the key value 1 is false the key value store 0 true means store required value. This is the trouble -
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?