Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST UnitTest No file was submitted
I successfully implement with small cases. Then I started to work with bigger structure. And I got the error. Error: No fie was submitted. import tempfile from unittest import skip from django.conf import settings from django.contrib.auth.models import User from django.core.files import File from django.core.files.uploadedfile import SimpleUploadedFile from model_mommy import mommy from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIClient class CustomerFromExcelViewsetTest(APITestCase): def setUp(self): self.client = APIClient() self.soken_staff = mommy.make(User, username='spearhead') self.user = mommy.make(User, username='Justin') settings.MEDIA_ROOT = tempfile.mkdtemp() def test_upload_file(self): """Expect created_user, and updated_user correct set""" file = File(open('./soken_web/apps/uploaded_files/complete-customer.xlsx', 'rb')) uploaded_file = SimpleUploadedFile('new_excel.xlsx', file.read(), content_type='multipart/form-data') data = { file: uploaded_file, } self.client.force_authenticate(user=self.user) response = self.client.post(reverse('api:customer_from_excel-list'), data, format='multipart') response.render() self.assertEqual(status.HTTP_201_CREATED, response.status_code) Here they are the models, serializers, and viewsets models.py https://gist.github.com/elcolie/52daf2bd144af82b348f7353656be434 serializers.py https://gist.github.com/elcolie/7f097642c4a752e76044c6938c49e097 viewsets.py https://gist.github.com/elcolie/34fa66632209f14624899d997919d3fb After a day I could not figure out where is the that bug. References: DRF APITestCase not use `multipart` with other param -
Django: Basic Auth for one view (avoid middleware)
I need to provide http-basic-auth for one view. I want to avoid to modify the middleware settings. Background: this is a view which gets filled in by a remote application. -
Migrating Django from 1.9 to 1.11: forms.MultiWidget.format_output disappeared
This method was very usefull to render MultiWidget in Django 1.9: format_output(rendered_widgets) I use it in many places, here is an example of use: def format_output(self, rendered_widgets): items = [ '%s %s' % (rendered_widgets[i], f) for (i,f) in enumerate(self.fieldnames) ] if self.aligned: return '<li>' + '</li><li>'.join(items) + '</li>' else: return ' '.join(items) It disappears in Django 1.11, and I don't find a natural replacement. The render method seems to be the unique alternative, but I don't understand how to use it correctly. Does anybody have ideas? -
Django call script in view from template
I have a view, that displays entries from one date to another, about a certain project. The project model is called "DNN" and times on there are in the "Vnos" model. views.py: def po_nalogu(request, dnn = None): dnn = None form = PregledDNNForm( request.GET or None, ) from_date = get_month_start(timezone.now()) to_date = from_date + relativedelta(months=1) if request.GET: if form.is_valid(): from_date, to_date, dnn = form.save() entries_qs = Vnos.objects.filter(dna__dns__dnn = dnn) month_entries = entries_qs.timespan(from_date, to_date=to_date).order_by('start_time') sestevek = 0 for entry in month_entries: sestevek = sestevek + entry.hours template = 'porocila/po_nalogu.html' context = { 'form' : form, 'from_date': from_date, 'to_date': to_date - relativedelta(days=1), 'entries': month_entries, 'sestevek' : sestevek, } return render(request, template, context=context) Now, I want to add a conditional sentence, so I could print PDF. Is there a way to add something like: if request.method == "PDF" do code and in template: <form action="" method="PDF"> <input type="submit" /> </form> I don't want to do a separate view for the PDF file, because of the from and to dates, as it is a lot of computing one more time. Thank you -
Is there any way to separate py and pyc files while building Django project using pybuilder
I was trying to build a Django project using pybuilder where I need to separate the pyc files and resource files. This is regarding protecting the source code, I know we can achieve this by the licencing mechanism. Our requirement is distributed the pyc file to the client instead of actual py file. -
How to allow googlebot to crawl publically visible pages on my django site that are behind login?
I've found several posts about this but can't seem to get a straight answer for my case. I'm using django allauth to make users sign up before posting anything. However, all the pages are visible to the public and don't require login to view. How do I allow google to crawl the pages without having to go through the login? Would a simple sitemap work? I looked into first click free but from what I read it only crawls the first page after the login? Or should I whitelist the IP's? Any direction would be great, thanks. -
I need to paginate results in django using hundreds of thousands of rows without running the query again
I need to paginate a very large result (300,000 rows) but I don't want to run the query again. Is there a way to make two search(request): the first one to give me the list with the data, and the second result(request): to post the queried data from the first request. I'm trying to do this so I don't have to run the query again and again after displaying every page. Any help would be appreciated! -
Call a Django python function from tag script in the template
This is some content of my Django template. ... <a id="ID" href="">Do operation with database.<a/> ... <script type="text/javascript"> window.onload = function () { var a = document.getElementById("ID"); a.onclick = function () { if (confirm("do you really want to perform task?")) { /** call python function in order to perform some operations with database **/ } return; } </script> ... The function is for example(we can imagine the function is in views.py): def performtask(): #do my operation with the database My question is, how it is possibile to call performtask() function from the script tag in my template? -
How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax?
In models I have calculated field total And I want to see this field in my dynamic drop boxes generated with Ajax. But I just get undefined in dropdown. My data flows in following way: 1-I have sterilizer in my api class LeaseTermSerializer(serializers.ModelSerializer): class Meta: model=LeaseTerm fields = '__all__' 2-I have api method in view @api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid): leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True) leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True) response = Response(leaseterm_serializer.data) return Response(response.data,status=status.HTTP_200_OK) 3-In my template I build it like this function getleaseterm() { //get a reference to the select element $select = $('#leaseterm'); //request the JSON data and parse into the select element var l_id = ($("select[name='lease'] option:selected").attr('value')); l_url = "/api/get_leaseterm/"+l_id+"/"; $.ajax({ url: l_url, dataType:'JSON', success:function(data1){ //clear the current content of the select $select.empty(); $select.append('<option value="-1">Select term </option>'); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('<option value="' + val.id + '">' + val + val.total + '</option>'); }) }, }); } How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax? -
AppRegistryNotReady after installing django-ckeditor
I added the django-ckeditor to my app but I get the AppRegistryNotReady error. I tried to move the ckeditor app in the INSTALLED_APPS list without any change. Versions: Python==2.7.10 Django==1.8.9 django-ckeditor==5.3.0 The traceback Traceback (most recent call last): File "/Users/karim/dev//myop//manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/karim/Dev/cml/myop/myop/domain/service_filtering/__init__.py", line 1, in <module> from myop.domain.service_filtering.service_filter import ServiceFilter File "/Users/karim/Dev/cml/myop/myop/domain/service_filtering/service_filter.py", line 10, in <module> from myop.domain.buyer.models import BuyerRole File "/Users/karim/Dev/cml/myop/myop/domain/buyer/models.py", line 11, in <module> from myop.domain.core.models import Organisation, OrganisationAssociation File "/Users/karim/Dev/cml/myop/myop/domain/core/models/__init__.py", line 3, in <module> from .organisation import * File "/Users/karim/Dev/cml/myop/myop/domain/core/models/organisation.py", line 6, in <module> from ckeditor.fields import RichTextField File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/fields.py", line 6, in <module> from .widgets import CKEditorWidget File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 54, in <module> class CKEditorWidget(forms.Textarea): File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 59, in CKEditorWidget class Media: File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 68, in Media static('ckeditor/ckeditor/'), File "/Users/karim/Envs/cml/lib/python2.7/site-packages/js_asset/js.py", line 14, in static if apps.is_installed('django.contrib.staticfiles'): File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 231, in is_installed self.check_apps_ready() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded … -
Redirect page in reactjs and django
I have a question that, i am stucked to redirect my page from signup to login. I have added allauth,rest_auth for token authentication in app and in reactjs i have added one form.js file. I have added views in views.py for get and save data from database. Now my rest-auth/login url works fine. But whenever i hit only login/ url which is calling our django view and form.js that is also works fine separately. Now i want to integrate this both so that at the time of signup i can create token for User. And also redirect from signup to login after user signup. What and Where i need to add these much things to get successful app? -
Django Translation not working and showing trans tags
I have a template I have created to add my project and I am using Django's translation module. I works fine with my already existing pages but on this one the translations are not rendered and instead it shows all the raw tags. I've compiled messages etc and still nothing. How do I fix this? I've looked at the following questions but no dice: django - how to make translation work? django internationalization and translations issue How to setup up Django translation in the correct way? http://askbot.org/en/question/8948/weve-edited-djangopo-files-but-translations-do-not-work-why/ See picture: html: {% load static %} {% load staticfiles %} {% load i18n %} {% block bonos %} <div class="container" > <div id='titleb' class="container"> <h2 style= "color:black; align=center">MILINGUAL BONO</h2> </div> <div id='titleb' class="container"> <h1 style= "color:black; align=center">MILINGUAL BONO</h1> </div> <div> <p>{% trans 'The Milingual Bono offers you more classes for much lesser. It saves you the hasslse of pasying each time you book a class, at the same time offering you the flexibilty of attending any Milingual class or event, anytime you want. Pick the 3 class bono if you would like to give it a try firt or book the <b>season bono</b> for unlimited access for 3 months.' %} </p> </div> … -
Parse date from json in Django
I try to parse date field inside JSON object : { "year": 1, "name": "marko", "date": "2015-10-1 3:00 PM GMT+1:00" } I try to something like: db_object.date = datetime.datetime.strptime(dictionary.get('date'), '%Y-%m-%d %I:%M ') but I get error... I know that %d is should be a zero based like: 01 but I get 1 in JSON. -
Celery task will not execute
I've followed the instruction process to installing and setting up celery, now I'm trying to execute my task. My project tree looks like this: bin app ----- | -------app -------- | --------celery.py --------tasks.py --------views.py -------manage.py -------templates include lib Here's my code: settings.py CELERY_BROKER_URL = 'amqp://localhost' #not exactly sure what this does celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from celery import shared_task @shared_task def print_this(): print('ONE MINUTE') app.views add_question.delay() So my celery function doesn't work, it doesn't execute the print statement. What I want to do is execute the function every minute. Any idea what the problem is? -
Use Kinect on web app
I want to create a web app that display my motion using my Kinect. Question Is there a possible programming language like PHP, Python(Django), .Net or JSP to deal with Kinect on browser? -
Django models and join sql tables
i wanted to try using django instead of having to call my stored procedure on the DB. So i created a new model, taking informations from two differents models class TbMouvementinit(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. dateheurecreat = models.TextField(db_column='DateHeureCreat') # Field name made lowercase. dateheureclot = models.TextField(db_column='DateHeureClot', blank=True, null=True) # Field name made lowercase. id_pesee = models.BigIntegerField(db_column='Id_Pesee') # Field name made lowercase. id_proteine = models.BigIntegerField(db_column='Id_Proteine', blank=True, null=True) # Field name made lowercase. id_humidite = models.BigIntegerField(db_column='Id_Humidite', blank=True, null=True) # Field name made lowercase. id_espece = models.BigIntegerField(db_column='Id_Espece', blank=True, null=True) # Field name made lowercase. id_produit = models.BigIntegerField(db_column='Id_Produit', blank=True, null=True) # Field name made lowercase. id_codeechantillon = models.BigIntegerField(db_column='Id_CodeEchantillon', blank=True, null=True) # Field name made lowercase. id_traitement = models.BigIntegerField(db_column='Id_Traitement', blank=True, null=True) # Field name made lowercase. id_circuit = models.BigIntegerField(db_column='Id_Circuit', blank=True, null=True) # Field name made lowercase. code_source = models.CharField(db_column='Code_Source', max_length=20, blank=True, null=True) # Field name made lowercase. code_destination = models.CharField(db_column='Code_Destination', max_length=20, blank=True, null=True) # Field name made lowercase. nomos = models.CharField(db_column='NomOS', max_length=30, blank=True, null=True) # Field name made lowercase. codesite = models.CharField(db_column='CodeSite', max_length=9, blank=True, null=True) # Field name made lowercase. type_mouvement = models.CharField(db_column='Type_Mouvement', max_length=3, blank=True, null=True) # Field name made lowercase. sous_domaine = models.CharField(db_column='Sous_Domaine', max_length=1, blank=True, null=True) # Field name … -
No module named admin_view_permission, CircleCI?
When I run my Django project on CircleCI I get the following error: "ModuleNotFoundError: No module named 'admin_view_permission'" The project runs with no problems locally on my computer. I added the module admin_view_premissions, to settings, from this page: https://github.com/ctxis/django-admin-view-permission Then I ran "pip install django-admin-view-permission", and it worked fine. The migration also did not have any problems. Does anyone know why CircleCI is not able to find the module? Thank you for your time! -
Django messages are not shown if chrome data saver is enabled
Google data saver compresses data to reduce traffic usage. It is enabled by default in mobile (android) chrome and might be used in desktop chrome as plugin. Whe GDS is on django messages are NOT displayed. I created a sample application (Python 3.5, Django 1.10.8, uwsgi+nginx) to catch this bug. This app has one "submit" button on main page that triggers the view method: def welcome_view(request): if request.method == 'POST': messages.add_message(request, messages.INFO, "succeed") return HttpResponseRedirect('/') else: return render(request, 'index.html') Full app sources are here. Deployed application available at fqtest.ru Steps to reproduce: Deploy to some server (or use mine fqtest.ru). Don't forget to specify allowed hosts in settigs.py. Turn off chrome data saver plugin if you have it or use launch ingognito mode. Open main page and click Go bitton. Result: message shown as expected Turn on data saver plugin or install it (or open site from android chrome) Open main page and click Go bitton. Result: message NOT shown while it should be. Questions: What are reasons of this behavior? How can it be fixed/worked around? Hope for help. Thanks! -
How to query PointField - MongoEngine
I was trying to update PointField in my flask app with upsert_one. But it always inserts new document. I know the problem is with the query which I'm passing. Below is my model. class Location(db.Document): location_name = db.StringField(required=True) geoCoords = db.PointField() And the update query. Location.objects(geoCoords=loc["geoCoords"]).upsert_one(location_name=loc["location_name"], geoCoords=loc["geoCoords"]) #loc["geoCoords"] = [77.6309395,12.9539974] I also tried running get. But I'm getting the error message "Location matching query does not exist." for the below query. loc = Location.objects(geoCoords=[77.6309395,12.9539974]).get() I have following entries in my location collection. > db.location.find() { "_id" : ObjectId("59c5019727bae70ad3259e67"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" } { "_id" : ObjectId("59c5022d27bae70ad3259ea2"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" } > I couldn't find any related information on querying the PointFiled. -
After configure apache2 for django website it shows apache default page on browser
<VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly.\ ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /root/myproject/static Require all granted <Directory /root/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/root/myproject python-home=/root/myproject/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias /myproject /root/myproject/myproject/wsgi.py</VirtualHost> Above is my 000-default.conf apache2 file. I have configured it for my django project named myproject and it is in root directory. And my virtualenv for this project is myprojectenv inside of myproject directory. -
How to analysis the result of django debug toolsbar?
From the debug result ,i can see my website Browser timing is really long. Basically i create 13000 item for the blog table. Seems like it takes not a long time to do sql query. The debug result My questions is how can i Identify bottlenecks from debug result. Why it loads so slowly ,takes near 20s .How can i reduce the domContentLoadedEvent and domloading Time. Thanks. -
Fom missing 1 required positional argument: 'request' in form
I am trying to get my form work using previous stackoverflow answers and google but nothing seems to work for me. I have a model Project and a project team and I would like the user to be able to choose from one of the teams that he created and link it to the project. I am using a custom user called MyUser that is my form in order to select a team: from django import forms from django.contrib.auth.models import User from registration.models import MyUser from .models import Project, Team from django.contrib.auth import get_user_model User = get_user_model() class EditSelectTeam(forms.Form): team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None) def __init__(self, User, request, *args, **kwargs): super(EditSelectTeam, self).__init__(*args, **kwargs) self.fields['team_choice'].queryset = Team.objects.all().filter(team_hr_admin = request.User) my views: def TeamSelect(request): if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): print('sucess') else: print('Fail') else: select_form = EditSelectTeam(request) return render(request,'link_project.html', {'select_form':select_form }) If in my form I put request.User I get the error in my view that : TypeError: init() missing 1 required positional argument: 'request' Do not know what to do to make it work please helllpp ;) thx -
Showing error messages in template in DefaultUserCreationForm - django
I am having a problem in displaying an error message in the HTML page. I am using Django's default UserCreationForm for signup page. It has two password fields - one original and one for confirmation. When the user enters different passwords, I am getting at /signup/ whereas I want the error message to be displayed in the HTML page saying that the passwords didn't match. I have gone through the docs and I have added some related lines in my code, I don't know where I'm going wrong. Here is my views.py: def adduser(request): if request.method == 'POST': form = UserCreationForm(request.POST) print(request.POST) if(form.is_valid): try: user = employees.objects.get(emp_id=request.POST['username'] ) except employees.DoesNotExist: user = None print(user) if( user != None ): if request.POST['username'] in employees.objects.values_list('manager_id__emp_id',flat=True): g = Group.objects.get(name='Managers') newuser = form.save() newuser.groups.add(g) else: g = Group.objects.get(name='Employees') newuser = form.save() newuser.groups.add(g) return render(request,'login.html',{'form': form}) else: form = UserCreationForm() return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'}) else: form = UserCreationForm() return render(request,'signup.html', {'form': form}) and here is my signup.html: <body> <div class="container"> <div class="page-header"> <h1>Sign-up Here</h1> </div> {% block body %} <form method="post"> {% csrf_token %} <font color="orange" size="5px"><p> * Enter your Employee id, as username * </p></font> {{ form.as_p }} <font … -
python is asckin of existing argument in test
I try to test signals. I have signal item in app.signals.py from django.dispatch import Signal task_completed = Signal(providing_args=['balance']) Func is in user.views and it update balance according to task cost from django.contrib.messages import success from users.models import User from django.db.models import F from freelance.signals import task_completed def update_balance(cls, balance): User.objects.select_for_update().filter(user_type=User.CUSTOMER).update( balance=F('balance') - balance ) User.objects.select_for_update().filter(user_type=User.EXECUTER).update( balance=F('balance') + balance ) if success: task_completed.send_robust( sender=cls, balance=balance, ) func is called in task.models after task creation @receiver(post_save, sender=Task) def task_post_save(sender, instance, **kwargs): instance.assignee.update_balance(instance.money) And finally test that I want to make for all this things class TestCharge(TestCase): def test_should_send_signal_when_charge_succeeds(self): self.signal_was_called = False self.total = None def handler(sender, balance, **kwargs): self.signal_was_called = True self.total = balance task_completed.connect(handler) update_balance(100) self.assertTrue(self.signal_was_called) self.assertEqual(self.total, 100) task_completed.disconnect(handler) But it gives mistake like TypeError: update_balance() missing 1 required positional argument: 'balance' -
How to display instances from two different django models on the same template, inside the same table?
In a django app I've created different models and everything looks okay until I try using data from two different models inside the same table. To sum it up: in the homepage, I need to create a table that contains data from both the models, ordered by date. The two models I need to display are the following. models.py class Document(models.Model): number = models.CharField(max_length=10) description = models.CharField(max_length=50) assigned = models.BooleanField validity_date = models.DateField is_issued = models.BooleanField class Program(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=100) validity_date = models.DateField Then, I tried to create a view that would allow me to work with different models. This is my view.py: class BaseView(generic.ListView): template_name = 'base/base_list.html' context_object_name = 'base_list' def get_queryset(self): queryset = Document.objects.order_by('due_date') return queryset def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['Programs'] = Program.objects.all() context['Employees'] = Employee.objects.all() return context Now how can I create inside the template a table that shows both the models at once, ordering each entry by validity date (no matter if the entry belongs to Program or to Document)? Thank you in advance!