Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to login as another user using Django?
I've got a site being built on Django to replace a previous custom site built using straight PHP. The site is built so that a business owner can sign up for a master account and create user accounts for all his employees. The master account can then display a list of all their users and click on a certain button for each of their users and login as that user - no need to enter username or password. We set a few cookies that declare the current user is now the employee as well as another cookie that tells the system this is still a master account so there's a new button at the top that lets the user click it to go back to their previous master account session. I'm struggling how to accomplish this in Django. Everything is so modular, I'm not sure how to start a session for a new account without requiring the user to enter username and password again. -
Apache WSGI no module named django whitout virtualenv
wsgi.py: import os,sys sys.path.append('/var/www/html/yuyyu/yuyyu') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yuyyu.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() apache.conf: ... WSGIDaemonProcess yuyyu python-path=/var/www/html/yuyyu WSGIProcessGroup yuyyu WSGIScriptAlias / /var/www/html/yuyyu/yuyyu/wsgi.py \ process-group=yuyyu application-group=%{GLOBAL} ... here is my error in error.log: [Fri Dec 02 19:07:55.862266 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] mod_wsgi (pid=1414): Target WSGI script '/var/www/html/yuyyu/yuyyu/wsgi.py' cannot be loaded as Python module. [Fri Dec 02 19:07:55.862323 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] mod_wsgi (pid=1414): Exception occurred processing WSGI script '/var/www/html/yuyyu/yuyyu/wsgi.py'. [Fri Dec 02 19:07:55.862353 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] Traceback (most recent call last): [Fri Dec 02 19:07:55.862393 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] File "/var/www/html/yuyyu/yuyyu/wsgi.py", line 23, in <module> [Fri Dec 02 19:07:55.862398 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] from django.core.wsgi import get_wsgi_application [Fri Dec 02 19:07:55.862418 2016] [:error] [pid 1414] [remote 213.14.244.3:2784] ImportError: No module named 'django' my project path is /var/www/html/yuyyu/ my wsgi file path is /var/www/html/yuyyu/yuyyu/ im get also 500 Internel Server Error and im not using virtualenv so what can i do for solve this problem? -
Used csrf_exempt decorator but still getting CSRF token missing or incorrect
I can't figure out why I'm getting error: POST http://127.0.0.1:8000/scrape/test-xpath/ 403 (Forbidden) when trying to use AJAX post to the view because I use @csrf_exempt decorator. Could you check it and tell me why it raises this error? JS: function checkXpath(xpath) { var test = $.post('/scrape/test-xpath/', {'xpath': xpath}); test.done(function (data) { alert(data); }) } $(document).ready(function () { $('#test-xpath').click(function () { var xpath = $('#id_xpath').val(); checkXpath(xpath) }); }); VIEW: @csrf_exempt def ajax_xpath_test(request): xpath = request.POST.get('xpath') if test_xpath(xpath): return JsonResponse({'valid':1}) return JsonResponse({'valid':0}) URLS.PY of scrapeapp: urlpatterns = [ url(r'^test-xpath/$',scrapeapp_views.test_xpath, name='test_xpath'), ] URLS.PY: ... url(r'^scrape/', include('scrapeapp.urls')), ... -
Change what's displayed in a Django template using the Python variables
I have recently started working on some software that has been written in Python/ Django, and I am looking to change what information is displayed on one of the webpages. The page currently displays a number of tabs, with different information from the database displayed on each tab. The tabs are titled: Overview, Budget, Works, & Items. On the Items tab, there are four columns: Items, Initial Sum, Latest Sum, & Notes. There are views in the Python code that are used to set up what's displayed on each tab, and the one for the Items tab that I want to change is defined with: def report_ccis(request, project_id): """ CCI items styled for pdf """ project = Project.objects.get(id=project_id) budget = get_current_budget(project_id) cci_total_exc = budget.cci_total_exc_vat_final cci_grouped_items = budget.cci_items.all().order_by('project_room', 'name') context = { 'project': project, 'cci_total_exc': cci_total_exc, 'cci_grouped_items': cci_grouped_items, 'webview': 1, } try: context['current_budget'] = project.budget_versions.get(current_marker=1) #For option name/date on top of pdfs except ObjectDoesNotExist: pass if request.GET.get('stage') == 'pd': """ Render post deposit homepage """ context['html'] = render_to_string('costing/report2_ccis.html', context) context['active_tab'] = '4' return render(request, 'costing/reports_post_deposit.html', context) else: """ Render pre deposit homepage """ context['html'] = render_to_string('costing/report_ccis.html', context) context['active_tab'] = '5' return render(request, 'costing/reports_pre_deposit.html', context) I want to remove the 'Latest Sum' … -
How to define billing address in Paypal page for payments without login
I'm using paypal in my site in the checkout page and I already have the shipping and billing addresses set by the user in my site. The problem is that I want to send the billing address the user put in my site to the paypal payment page (when the user wants to pay without login in) but It always shows this fields empties. Can I remove the form for the billing address in the paypal page or at least send the address in the request? I've tried the adress1, city, country, ... but the form is still empty. -
Django modelform widget readonly render text not input field
I have a modelform with readonly fields that render as a HTML input widget with an ugly 'no-entry' mouseover image (firefox) when the text inside the input box is selected - default behaviour for 'models.TextField' fields to render as input I believe. self.fields['project_path'].widget.attrs['readonly'] = True self.fields['media_path'].widget.attrs['readonly'] = True self.fields['responsible'] = SysEventChoiceField(User.objects.all().order_by('first_name')) I want to render the modelform with a mixture of read only fields as pure text without the input boxes in the form. The result should look something like this in html.. <p>D:\This\Path</p> <p>E:\This\other\path</p> <input value="Bob Smith" name="user"></input> -
Writing generic functions for all types of Django models
What I need to achieve is best described by example. Imagine that I have multiple models (let's say, model Task and model Animals) that have a field named foo and my goal is to perform identical set of MySQL transactions for all of these models. For example, I want to increment by one all the foos of a given instance along with subsequent instances (with larger id's). Something like: def example_view(instance): instance.foo = instance.foo + 1 instance.save() id = instance.id INSTANCE_MODEL.objects.filter(id__gt = instance.id).update(foo = foo + 1) The question is, is it possible in Django to write generic functions in a sense that I can use example_view with Animals, Tasks, etc, as long as all of them have fields mentioned in the view ? And if yes, what is the valid syntax for INSTANCE_MODEL.objects.... ? -
How do I make Django call a put rather than get request?
In the Djano code below how do I make the url(r'^hello-world/$', MyView.as_view(), name='hello_world') call a PUT rather than a GET? url(r'^hello-world/$', MyView.as_view(), name='hello_world'), class MyView(View): def get(self, request, *args, **kwargs): return HttpResponse("Hello, World") -
SSL error on Django app for Heroku deployment
I am trying to setup SSL for my Django app, using Heroku to deploy, and am getting an "Unknown SSL protocol error in connection to localhost:24466" when I run the "$ curl -v https://localhost:24466/" request from my local machine (ie cutting out the entire Heroku stack). My app runs fine on Heroku when DEBUG = True but gets a connection error when DEBUG = False and I believe this is the issue. Here are the relevant settings I am using in settings.py: STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True Does anything look wrong for deployment with DEBUG=False? Here is the full result from "$ curl -v https://localhost:24466/": ~ $ curl -v https://localhost:24466/ * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 24466 (#0) * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * SSLv3, TLS handshake, Client hello (1): [2016-12-01 16:49:39 +0000] [18] [CRITICAL] WORKER TIMEOUT (pid:23) * Unknown SSL protocol error in connection to localhost:24466 * Closing connection 0 curl: (35) Unknown SSL protocol error in connection to … -
Access to field in another model via ForeignKey in django rest
I want to build api part of my app in django 1.8 (with django rest framework) and I want to get access to field in another model via ForeignKey but I get an error. My code (models.py): class Event(models.Model): ... is_date_end_confirmed = models.BooleanField(default=True) room = models.ForeignKey('events.Room', related_name='bookings') room_description = models.CharField(max_length=255) ... serializers.py class BoxSerializer(serializers.ModelSerializer): room = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Evnet fields = ('id', 'date_start', 'room') And I get Type error: 'Room' object is not iterable -
how to increase expires_in time in oauth_provider django drf
Blockquote how to increase expires_in time in oauth_provider toolkit django rest framework django Blockquote -
Django: Order by two fields (one nullable)
i have the following model class Model1(models.Model): parent = models.ForeignKey("self", models.SET_NULL, null=True, blank=True)` Sample data: [{'id': 1}, {'id': 2, 'parent': 1}, {'id': 3, 'parent': 1}, {'id': 4}, {'id': 5, 'parent': 1}, {'id': 6, 'parent': 3}, {'id': 7, 'parent': 4}, {'id': 8, 'parent': 3}, {'id': 9, 'parent': 1}] I would like to order each parent node with all it's children using the django ORM, the expected output for the sample data would be something like this: 1, 2, 3, 6, 8, 5, 4, 7, 9 for each parent show its children after them. Any ideas on how this could be done? I was thinking that maybe with some aggregated field and sorting by it, but i'm a bit stuck on this one. Thanks in advanced! -
python - ImportError: cannot import name import_module
I'm trying to run chatterbot example with this guide: http://chatterbot.readthedocs.io/en/stable/tutorial.html So i'm getting this import error: ➜ examples git:(master) python basic_example.py Traceback (most recent call last): File "basic_example.py", line 2, in <module> from chatterbot import ChatBot File "/Library/Python/2.7/site-packages/chatterbot/__init__.py", line 4, in <module> from .chatterbot import ChatBot File "/Library/Python/2.7/site-packages/chatterbot/chatterbot.py", line 4, in <module> from .logic import MultiLogicAdapter File "/Library/Python/2.7/site-packages/chatterbot/logic/__init__.py", line 1, in <module> from .logic_adapter import LogicAdapter File "/Library/Python/2.7/site-packages/chatterbot/logic/logic_adapter.py", line 3, in <module> from chatterbot.utils import import_module ImportError: cannot import name import_module Any help? -
How to create search field in django and html with css
I am new in Django.How create Seach feild in django .Seach feild in Django mysql Table.I was Create Table in mysql database. My Quesstion is First i was selete th User type using radio button.then sort the table backend than I was select the chiefield which contain coloumn name in seleted radiobutton than enter the field means name of the selected column name. -
Djando: prepare query but don't execute it
I am trying to make some efficient queries with Django in the following loop: for division in divisions: playoffs = league.playoff_set.filter(division=division, double_elimination=True) I thought maybe filtering playoffs before the loop by selecting only those with double_elimination=True would enhance it: playoffs = league.playoff_set.filter(double_elimination=True) for division in divisions: division_playoffs = playoffs.filter(division=division) But now I am concerned that this is firing the query from playoffs in every run at the loop instead of filtering on the previously retrieved result. Is it working as expected or as I am fearing? Should I use Q instead to build these better-performing queries? -
Multi search query on django 1.3
I'm trying to do implement on my search filters to more than one column but I always get a query error back: This is my models.py: class Livro(models.Model): codigo = models.AutoField(primary_key=True) nome = models.CharField("Nome", max_length=50) autor = models.CharField("Autor", max_length=50) edicao = models.CharField("Edição", max_length=30) disciplina = models.ForeignKey(Disciplina) tipo = models.CharField("Tipo", max_length=20, choices = Choices.tipo) ano = models.CharField("Ano", max_length=30, choices = Choices.ano) situacao = models.CharField("Situação", max_length=30, choices = Choices.situacao, default = Choices.situacao[0][1], blank = True, null = True) def __unicode__(self): return self.nome This is my views.py: def consultar_livro(request): if request.method == 'POST': nome = request.POST['nome'] livro = Livro.objects.filter(nome__icontains=nome).order_by('nome') return render_to_response('consultar_livro.html', locals(), context_instance = RequestContext(request)) Instead of just the name I also need to use situacao, disciplina, tipo e ano. How should I do it? I've tried both just adding like I did with name and using the Q() function but it doesn't wotk, how to proceed? -
Django + Celery + SQS setup. Transport not correct
I am trying to setup Celery together with Amazon SQS in development environment of Django app. Celery worker is starting but transport is not correct. Have a look below: My celery.py looks like: 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', 'dance.settings') app = Celery('dance') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) The essential part of the Django celery settings responsible for transport: BROKER_URL = 'sqs://{}:{}@'.format(AWS_ACCESS_KEY_ID, quote(AWS_SECRET_ACCESS_KEY, safe='')) BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-west-1', 'polling_interval': 3, 'visibility_timeout': 300, 'queue_name_prefix':'dev-celery-', } When I am trying to launch working within virtual environment with following command: DJANGO_SETTINGS_MODULE='dance.settings' celery -A dance worker -l info I recieve following output: -------------- celery@universe v4.0.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.8.0-28-generic-x86_64-with-debian-stretch-sid 2016-12-02 14:20:40 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: dance:0x7fdc592ca9e8 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] ... task1 task2 ... Tasks are found … -
Django-Haystack: Create complex faceted field
I want to create search index for Product and show faceted search for every product attribute, splited by values e.g.: Attribute1: Value11 Value12 Attribute2: Value21 Value22 Value23 How I can reach this goal? Via 'prepare_attribute' function? Here model relationship that I use: class Product(models.Model): # some other fields attributes = models.ManyToManyField( 'Attribute', through='ProductAttribute') class Attribute(models.Model): # some other fields name = models.CharField(max_length=128) class ProductAttribute(models.Model): # some other fields attribute = models.ForeignKey(Attribute) product = models.ForeignKey(Product) value = models.CharField(max_length=128) -
Problems using Ajax with Django
I am having problems trying to update a block of my site (which includes another templates) by issuing an Ajax call. The that needs to be updated works just fine, but the JS script that is inside that template does not work (before, I was just adding the full request to my template, but that caused to have twice the content of the parsed template, but JS scripts were working). PD: I am kind new to JS and have some experience with Django (still just digging in the world of Web Apps development). My template: {% load staticfiles %} <script> $(document).ready(function() { var current_item_id = null; var current_item_title = null; var selected_items = null; // Selección en las tablas $('.table tr').on('click', function() { $(this).toggleClass('selected'); }); // Comportamiento del toolbar flotante $('.table tr').on('click', function() { selected_items = $('.selected'); current_item_id = $(this).attr('id'); current_item_title = $(this).attr('name'); if (selected_items.length === 0) { $('.modify-big').attr('disabled', true); $('.delete-big').attr('disabled', true); } else if (selected_items.length > 1) { $('.modify-big').attr('disabled', true); } else { $('.modify-big').attr('disabled', false); $('.delete-big').attr('disabled', false); } }); }); </script> <div id='notifications'> {% if notifications %} <table class="table"> <thead> <tr> <!--<th class="text-left table-id">ID del Item</th>--> <th class="text-left">Item</th> <th class="text-left">Link de descarga</th> <th class="text-left">Plantilla</th> </tr> </thead> <tbody class="table-hover"> {% … -
Django - Remove HTTPS redirect
I've a django app hosted on pythonanywhere servers. Some days ago, while editing this website, I've added in the settings.py file some variables about the https and ssl connection. Obviously I didn't want the https while I don't have the certificate, but I forgot those variable in the settings file. After the upload of files, going on the site, I saw that I've forgot those variables. I've immediatly deleted the variables from the settings file and re uploaded, but the problem persists. I mean, if I go to the site there is a redirect to https that I don't want. The outcome is "Connection is not private" whit a red barred https. Could you please tell me how to fix this problem? how to remove the automatic redirect to https and aboid the message "connection is not private" ? Thank you in advance!!! -
How to insert data on django template without database?
I want to insert data from django template form, but don't use database. This is my view code : from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext def home(request): if request.POST: nama_mask = request.POST.get('nama_maskapai') nama_maskapai.append(nama_mask) return render_to_response('page.html', context_instance=RequestContext(request, {'nama_maskapai': nama_maskapai})) return render_to_response('page.html', locals(), context_instance=RequestContext(request)) I want to insert data from template and this is my template: <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} Nama Maskapai : <input type="text" name="nama_maskapai"><br> Jam Terbang : <input type="text" name="jam_terbang"><br> <input type="submit" value="kirim" name="submit"><br> </form> <table border="1"> <thead> <tr> <th>No</th> <th>Nama Maskapai</th> <th>Jam Terbang</th> <th>Action</th> </tr> </thead> <tbody id="data"> {% for nm in nama_maskapai %} <tr> <td class="num"></td> <td>{{ nm }}</td> </tr> {% endfor %} </tbody> </table> <select id="mask"> <option value="all">-Pilih Maskapai-</option> {% for nm in nama_maskapai %} <option value="{{ nm }}"> {{ nm }} </option> {% endfor %} </select> <select class="wak"> <option value="allwak"> -Pilih Waktu- </option> <option value="pagi">pagi</option> <option value="siang">siang</option> <option value="malam">malam</option> </select> <br> </body> How can i insert from template and the data can be save in the table, because if i insert with this code my code always renew and the table cannot add data. -
xcode 8 swift 3 json parser, xcode gives me an unresolved error
I'm getting an unresolved identifier when I try to use this code... //parse dictionary func parseDictionary(dictionary: [String: AnyObject]) { // 1 guard let array = dictionary["results"] as? [AnyObject] else { print("Expected 'results' array") return } // 2 for resultDict in array { // 3 if let resultDict = resultDict as? [String: AnyObject] { // 4 if let wrapperType = resultDict["wrapperType"] as? String, let kind = resultDict["kind"] as? String { print("wrapperType: \(wrapperType), kind: \(kind)") } } } } I put this code in the right after the "searchBarSearchButtonClicked()" parseDictionary(dictionary) Can someone please tell me why I get this error, or help me change the code? Thank you, -
Check date and take another item from django queryset
I have django app (with django app 1.8 and django rest framework 3.3.1). I have model wiht Event and I want to display only last 4 events but if is 10 min after date_start I want to get another last 4 event. I'm not sure if my code it works correctly. class BoxView(generics.ListAPIView): queryset = Events.objects.all() serializer_class = BoxSerializer def get_queryset(self): last_events_list = Events.objects.all().order_by('-date_start')[:4] for i in last_events_list: if i.date_start < now() + timedelta(minutes=10): return last_events_list else: return last_events_list -
Adding authentication in django for different users to view only details that belong to them
I've developed a django application with details belonging to different users. The details will be added through the admin page only by the administrator and be rendered through template in the frontend. I want to add an authentication that will enable those users to log in and view details only belonging to them in the frontend. Could someone please help me to achieve this. -
Redirect requests to Django application using Apache
I have an Apache web-server and a PHP application. It all works great. The httpd.conf file at this moment looks like so: ... LoadModule wsgi_module modules/mod_wsgi.so ... Listen 8080 DocumentRoot "c:/Apache24/htdocs" <Directory "c:/Apache24/htdocs"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <IfModule dir_module> DirectoryIndex index.html index.php </IfModule> As you can see, I've already downloaded mod_wsgi.so and when I resart Apache it's all ok. So, when I go to localhost:8080, I see my PHP application running. Well done. Now, I have a second teene-weeny Django application. It's not even a full-blown application, because it's role will be to answer to one certain request from the same PHP application. Still, I will call it Django application. I run it like so: C:\django\project> python manage.py runserver 127.0.0.1:8081 As you can see I run a non-production server, but it works good. When I go to 127.0.0.1:8081, I see the result returned from my index view: def index(request): return HttpResponse("Hello, world") So, it's just a simple Hello world page and it works. Now what I want is to use Apache server, so that when I go to localhost:8080/django, I would see the very same Hello world page. I do not know how to implement …