Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-framework multiple serializers in the same request
I know there's something similar answered here, but my question is not the same. I'm using multi-table inheritance to model 2 different types of entities, and both of them can create posts. My problem is when trying to create a view that shows all the posts together. So I have my Entity model, and then my ETypeA and ETypeB models, which look like this: class Entity(models.Model): pass class ETypeA(Entity): # Here are some attributes pass class ETypeB(Entity): # Here are some attributes pass As you can see, the Entity model it's just for having a common primary key between ETypeA and ETypeB. The reason for this is to have just one common Post model, like this: class Post(models.Model): transmitter = models.ForeignKey(Entity, on_delete=models.CASCADE) text = models.CharField(max_length=500, null=False, blank=False) The problem now is that when I create a view to show the posts I get only the id of the transmitter but I need the whole information. The way of doing it in SQL should be joining the results with ETypeA, then with ETypeB and make a union between the results (keeping some fields as nulls). Then I should be capable of sorting them by date. How can I do that with … -
How do I see mail related errors in Django logs?
I'm trying to figure out why mail isn't being sent from a django application I copied from a perfectly working application where the mail works. I've tried in vain to get django to spit out something related to mail in the logs, but nothing shows up. Here are my settings in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'DEBUG', 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/ooto.log', 'formatter': 'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'django_opensso':{ 'handlers' : ['file'], 'level' : 'DEBUG', }, 'timekeeper':{ 'handlers' : ['file'], 'level' : 'DEBUG', }, } Can someone explain in detail or post an example of how I can get mail related errors out of django so I can troubleshoot the real problem? -
django rest framework : contenttype unique_together and serialization
I have a little problem with django rest framework about a generic relation which is also used in a unique_together constraint. I have this model : class VPC(models.Model): name = models.SlugField(null=False, max_length=100) deletable = models.BooleanField(null=False, default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = (('name', 'content_type', 'object_id')) It has a generic relation and a unique constraint : the name of the vpc + the generic relation(which is the owner). Here is the serializer: class VPCSerializer(serializers.ModelSerializer): class Meta: model = VPC read_only_fields = ('deletable', 'date_created', 'date_modified') fields = ('name', 'deletable') lookup_field = 'name' validators = [ UniqueTogetherValidator( queryset=VPC.objects.all(), fields=('name', 'content_type', 'object_id') ) ] In the fields I don't put the content_type and object_id as I don't want them to be displayed/set by the users. But I have to put them in the UniqueTogetherValidator in order to avoid a django.db.utils.integrityerror raised error when creating a VPC with the same account/name. But now when I try to create a VPC I got this error : {"object_id":["This field is required."],"content_type":["This field is required."]} So in my viewsets.ModelViewSet I tried to override perform_create() to set the object_id and content_type but it looks … -
Does django-rest-framework serializer not affect POST request?
This is my serializer : from django.utils import timezone from rest_framework import serializers from posts.models import Comment class DateTimeFieldWihTZ(serializers.DateTimeField): def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeFieldWihTZ, self).to_representation(value) class CommentModelSerializer(serializers.ModelSerializer): username = serializers.CharField( source="author.username" ) created_at = DateTimeFieldWihTZ( format="%Y-%m-%d %H:%M", ) class Meta: model = Comment fields = [ "content", "created_at", "username", ] The reason that I define DateTimeFieldWihTZ is that I want to customizing datetime format. It works pretty good on GET request : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "content": "야", "created_at": "2016-08-24 15:41", "username": "nada" }, { "content": "왜", "created_at": "2016-08-24 15:41", "username": "nada" }, { "content": "야새zi", "created_at": "2016-08-24 20:02", "username": "nada" }, { "content": "나 집에간다", "created_at": "2016-08-24 20:02", "username": "nada" }, { "content": "d", "created_at": "2016-08-25 09:03", "username": "nada" } ] But this serializer doesn't affect on POST request, even if I define the serializer_class like below : from rest_framework.generics import ListAPIView, CreateAPIView from rest_framework.response import Response from rest_framework import status from api.serializer import CommentModelSerializer from posts.models import Post from posts.forms import CommentForm class PostCommentListAPIView(ListAPIView): serializer_class = CommentModelSerializer def get_queryset(self): post = Post.objects.get(pk=self.kwargs.get("pk")) return post.comment_set.all() class PostCommentCreateAPIView(CreateAPIView): serializer_class = CommentModelSerializer def post(self, request, *args, **kwargs): form = … -
google calendar api doesn't respond when put in production
I have been trying to integrate the google calendar api in my django website so that when users make an event on the website it is automatically saved in the users' google calendar too. I am using the code from the google calendar api documentation and it works perfectly on my localhost but when i put it on my apache server, I do not get any response from the api and the page just keeps loading before timing out. Any type of help would be greatly appreciated. I am going to attach the code below but like i said before it's the same as the one from the google documentation and it works on my local machine so I know the code is right and working. Thanks SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = '/var/www/ambassador/events/client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store, flags) print('Storing credentials to ' + credential_path) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) eid = uuid.uuid1() obj.eid = … -
How do I set the DJANGO_SETTINGS_MODULE env variable?
I'm trying to fix a bug I'm seeing in a django application where it isn't sending mail. Please note that the application works great, it's only the mail function that is failing. I've tried to collect error logs, but I can't come up with any errors related to sending the mail. So, I made a example to try and force the errors. Here is the example: from django.core.mail import send_mail send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False) When I run the above code, I get the following error: Traceback (most recent call last): File "dmail.py", line 14, in <module> send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False) File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 59, in send_mail fail_silently=fail_silently) File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 29, in get_connection path = backend or settings.EMAIL_BACKEND File "/data/servers/calendar_1/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner self._setup() File "/data/servers/calendar_1/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. I managed to fix my test example by changing the code to this: from django.core.mail import send_mail from django.conf import settings settings.configure(TEMPLATE_DIRS=('/path_to_project',), DEBUG=False, TEMPLATE_DEBUG=False) send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False) However, when I try to add those settings to send_mail.py, I'm still not getting … -
docker + django : loop + break using forms
I am using django in a docker container. I have a page with two buttons: 'Run' and 'Stop'. When someone presses 'Run' it should start an optimisation process, when you press 'Stop', it should stop. views.py def runGA(request): form = runform.save(commit=False) # initiating the form, to allow writing form.stop to db.stop desdata = DesignModel.objects.get(SID=sid) # reading the database, to check db.stop if request.method=="POST": if request.POST.get("GA")=="Stop": form.stop = True if request.POST.get("GA")=="Run": for iteration in range(cycles): *optimise something with iteration* if form.stop: break form.stop = False return render(request,"runGA.html",{}) This works when I don't use the docker container but just run it locally. This structure allows to interrupt a loop, but it also allows to show an updating figure while running, or to check settings on other pages while running, etc... (so I need a solution that would work for all those problems as well) However, if I run this code in the docker container, it seems as though there's a problem with the request.POST. It executes all the requests after the loop is done, and not during as it should be. And this only happens when I run this in a docker container. Any ideas how come? Thanks! Docker version: Client: Version: … -
Where to put zip code into authorizenet request - Python
This is a very particular question, and Im hoping someone can answer it. I am using authorizenet for payment processing. In the documentation it says you can put in different zip codes to get different response codes, response codes for declined transactions, successful payments, etc. I can't find anywhere in the documentation where it says to put that zip code. Here is the sample code from the documentation to get started in Python. credentials = getattr(settings, 'AUTH_NET', None) merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = credentials['login'] merchantAuth.transactionKey = credentials['txn_key'] creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = card_number creditCard.expirationDate = exp_date payment = apicontractsv1.paymentType() payment.creditCard = creditCard transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = Decimal(price) transactionrequest.payment = payment createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest createtransactioncontroller = createTransactionController(createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response.messages.resultCode == "Ok": print("Transaction ID : %s" % response.transactionResponse.transId) return True else: print("response code: %s" % response.messages.resultCode) return False -
django javascript behaving oddly
I've a button called "Add new usage", basically, when user clicks it, it'll display the form, a pretty simple behavior, but I don't understand how it always triggers the action in the form underneath it, I'm very confused, here's my code: <div class="row" > <p style="padding-left: 0.5cm;"> <button id="create_new_spa" class="btn btn-small btn-primary" onclick="javascript:show_create_new_usage_form();" type='submit' onclick="this.disabled=true">Add new usage </button> </p> </div> <div class="row" id="create_new_usage_form" style="display:none"> <form method= "post" action ="/purchasing/item_info_spa_details_update/"> </form> </div> And here's my js code: {% block jquery2 %} function show_create_new_usage_form() { $("#create_new_usage_form").show(); }{% endblock %} So, I was expecting to click the "Add new usage" button, then the form shows up, however, now it displays form instantly, and following that, instantly within in like 20 ms, it quickly goes to action in the form, doesn't allow the user to see the form, and then quickly hides the form again. I cannot see anything wrong with the code, please help! Thanks a lot! -
Automatic db router for migrations in django
I am building a Django powered site and I want to have separate databases for some of the apps, I build a flexible router that routes each app to predefined database, this works fine. The problem is that when I am migrating my models I have to set the --database parameter every time and I find this annoying and redundant. Also many times I flooded my default database with tables from migrated app (by forgetting to add --database). I experimented with allow_migrate(...) function in my router but all I could achieve is safety mechanism that will not run the migration if I forget to specify the database. My question is: is there a way to set up a automatic database selection for models migrations in Django? -
Django JSON not sending proper data
I am developing a django python web application. In my webpage, I am sending a request to my API by sending a 'term' and my API is supposed to return the 'content' field of the search. My content contains 'xxx is good' in my database. Here is my code in views.py def get_RuleStatement(request): if request.is_ajax(): q = request.GET.get('term', '') rule_statements = RuleStatement.objects.filter(content__icontains = q )[:1] results = [] for rule_statement in rule_statements: rule_statement_json = {} rule_statement_json['content'] = rule_statement.content results.append(rule_statement_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) For some reason, whenever I send the following request: http://website.com/api/get_RuleStatement/?term=xxx It returns 'fail' even through my database contains data 'xxx is good'. Can anyone suggest where I am going wrong? -
Return multiple HttpResponse objects that are Excel spreadsheets
The desired outcome is to export a spreadsheet of all users in the database, but rather than export them all at once - break up the users into 3 groups and export each of these groups as a spread sheet. I am using xlsxwriter and StringIO Thus far the code is returning only the first HttpResponse object out of the 3 (aka the first chunk of users). I tried using StreamingHttpResponse but believe I misapplied it/it wasn't appropriate for this task. The question/s: Can I return multiple spreadsheets in one response? If not, what would be a better way to break this task up based on user groups? Thanks Much! Code below: def export_users(request): # all users users = User.objects.all() # breaks up all users into 3 groups user_groups = [users[x:x+2] for x in xrange(0, len(users), 2)] # FUNCTIONALITY NOTES --> idea is to split number of users for exporting into groups of 3 then export each group. right now it stops after the first group # list var for storing all responses full_response = [] for group in user_groups: response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=UserReport.xlsx' # user group print "group! ---> %s"%(group) # creates data variable to write … -
django user permissions not showing in production
I have a wierd problem , In production I can't see user permissions list in django admin and after openning group edit page it's show noting and page language transform to another language . I have some cusotm permission define in app models . what I done ? sync my local database with production database . setting default encoding in supervisor (i thought maybe if my app verbose name is a unicode name so thats why its wont load) UPDATE Im using django version 1.7 -
Extending an existing model in django.
I wanted to add an attribute to an existing model. However, when I make the migration, the values for that attribute is an empty string. Will I have to set the value of the attribute for each model after the migration, or is there a way to do this when initializing the migration? -
como sumar registros que tienen el mismo id en django
Necesito sumar todos los registros donde bonchador sea igual a determinado nombre. Y mostrar el que tenga mas resgistros, alguien que me ayude por favor. Esta es mi tabla. id bonchador fecha hora variedad bonches unidades grado lamina 1 Santiago 2016-08-23 14:01:00 freedom 15 20 40 Benchmark 2 Fredy 2016-08-24 12:55:54 freedom 12 25 40 Benchmark 3 Sandra 2016-08-24 12:57:12 vendela 10 12 40 Pet 4 Angie 2016-08-24 13:55:27 freedom 14 12 40 Pet 5 Angie 2016-08-24 13:55:27 freedom 14 12 40 Pet -
Connect docker container (django app) to windows lan
I would like to run a docker in our windows environment so that staff can access the application from their own computers, but cannot get it working. I have tried both solutions of NAT and bridged mode that were suggested here to no avail: How to connect to a docker container from outside the host (same network) [Windows] When I use NAT mode, I am able to connect to the app through the localhost of the host computer (127.0.0.1:8000), when I use bridged mode I am able to use the IP of the docker machine (192.168.99.100:8000) but I cannot access them from other computers in the LAN. I am able to ping the computer where the docker container is located from another one in the same LAN, but when I type its url into the browser, I get the standard IIS landing page. I deleted the default site in IIS in case it was taking up the port that I was trying to allocate to the docker container, but that did not work- I simply get a site cannot be reached page. Ultimately, I just want to be able to access the app in the docker container from another computer … -
Errors with django urls
I'm getting an error 404 when i click the link on django, i have spent so much time trying to see what i'm doing wrong but no luck. here is my index.html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>{{title}}</h1> {% for obj in object_list %} {% url "detail" id=obj.id %} <a href = '{{obj.get_absolute_url}}'> {{obj.title}}</a><br/> {{obj.content}} <br/> {{obj.timestamp}} <br/> {{obj.updated}} <br/> {{obj.id}} <br/> {% endfor %} </body> </html> This is my urls.py from django.conf.urls import url from django.contrib import admin from .views import ( post_list, post_create, post_detail, post_update, post_delete, ) urlpatterns = [ url(r'^$', post_list), url(r'^create/$', post_create), url(r'^detail/(?P<id>\d+)/$', post_detail, name='detail'), url(r'^update/$', post_update), url(r'^delete/$', post_delete), ] This is my views.py from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_create(request): return HttpResponse("<h1>Create</h1>") def post_detail(request, id): # retreive instance = get_object_or_404(Post, id=id) context = { "title": instance.title, "instance": instance, } return render(request, "post_detail.html", context) def post_list(request): # list of posts queryset = Post.objects.all context = { "title": "List", "object_list": queryset, } return render(request, "index.html", context) def post_update(request): return HttpResponse("<h1>Update</h1>") def post_delete(request): return HttpResponse("<h1>Delete</h1>") and this is my models.py from __future__ import unicode_literals from django.db import models # Create your models … -
django: how do I actually override admin site template
I know this is asked and answered several times but I basically went over all the post on stack overflow and still couldn't get this to work. Right now I am just trying simply change the admin site title. I have the following: #base_site.html {% extends "admin/base_site.html" %} {% block title %}{{ title }} | {{ site_title|default:_('NEW TITLE') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('NEW TITLE') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} And I tried to put this in my_site/templates/admin/base_site.html, my_site/templates/admin/my_app/base_site.html, and my_site/my_app/templates/admin/base_site.html, but none of these work. settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] I also tried just directly changing django\contrib\admin\templates\admin\base_site.html but still nothing happens. I am really frustrated now and definitely could use some help, thanks -
heroku django internal server error 500
sorry for repeating, i know this question was asked tonns of times, but i haven't manage to figure out what's wrong with my project (spent the whole day). i'm deploying my Django project on Heroku: https://jsayapina.herokuapp.com/port/ Everything works fine, except 1 page which throws 500 (internal server error). here're complete heroku logs: (venv)MacBook-Pro-White-seal:django_course_hw1 devs$ heroku logs 2016-08-24T18:11:38.339658+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi 2016-08-24T18:11:38.339659+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2016-08-24T18:11:38.339655+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker 2016-08-24T18:11:38.339650+00:00 app[web.1]: [2016-08-24 18:11:38 +0000] [8] [ERROR] Exception in worker process 2016-08-24T18:11:38.339660+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2016-08-24T18:11:38.339659+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi 2016-08-24T18:11:38.339661+00:00 app[web.1]: return self.load_wsgiapp() 2016-08-24T18:11:38.339662+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-08-24T18:11:38.339663+00:00 app[web.1]: __import__(module) 2016-08-24T18:11:38.339662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-08-24T18:11:38.339663+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app 2016-08-24T18:11:38.339664+00:00 app[web.1]: File "/app/portfolio/wsgi.py", line 15, in <module> 2016-08-24T18:11:38.339660+00:00 app[web.1]: self.callable = self.load() 2016-08-24T18:11:38.339665+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application 2016-08-24T18:11:38.339667+00:00 app[web.1]: self.load_middleware() 2016-08-24T18:11:38.339668+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/handlers/base.py", line 56, in load_middleware 2016-08-24T18:11:38.339666+00:00 app[web.1]: return WSGIHandler() 2016-08-24T18:11:38.339666+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 153, in __init__ 2016-08-24T18:11:38.339670+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in import_module 2016-08-24T18:11:38.339675+00:00 app[web.1]: ImportError: No module named 'rollbar' 2016-08-24T18:11:38.340126+00:00 app[web.1]: [2016-08-24 18:11:38 +0000] [8] [INFO] Worker exiting (pid: … -
Django channels to resize an image
I have a model for Photo, with two image fields. One is for the original image and the other is for the resized version of the original image. class Photo(models.Model): user = models.ForeignKey(User) image_original = models.ImageField( upload_to=get_upload_file_name, width_field="image_original_width", height_field="image_original_height", blank=True ) image_original_width = models.IntegerField(default=0) image_original_height = models.IntegerField(default=0) image_470 = models.ImageField( upload_to=get_upload_file_name, width_field="image_470_width", height_field="image_470_height", blank=True ) image_470_width = models.IntegerField(default=0) image_470_height = models.IntegerField(default=0) I will be using sorl-thumbnail for resizing. How can I use django-channels to resize the image to have width of 470px and auto height using sorl-thumbnail? -
Form field django python
I am new to python and django and I was wondering, lets say that a form posts a field. Is there any way I can analyze the content of the form field? So if I post something like "I like pizza", will django be able to analyze the content Ive sent? Hard to explain but my goal is to split the posted sentence of the form field to something words like "I", "like", "pizza" so I can process the words later on. Can django or python handle such a situation? Thanks in advance for reading my post. -
Optimizing django and mysql for peak requirement
I've coded the backend of my recently launched mobile application using django 1.9, and the database I've used is MySQL. I'm about to start a large promotional campaign so trying to gear up the backend for the same. Here's what I've done so far: I was using AWS RDS free tier till now, have set up mysql server on a (t2.micro) EC2 server. Helps maintaining more persistent connections since you cannot configure that in RDS instances, and is cheaper as well compared to the paid RDS tier. What more can I do to configure MySQL to perform optimally? My main challenge is reads, and I have all necessary indices in place already. Also, should I look for a bigger machine than a t2.micro? How can I decide for it? I'm setting up a load balancer, and will configure auto scaling too. What more should I do to be ready for a large number of hits? One issue that I'm constantly facing is that when I fire around 100 threads in a span of 10 seconds via Apache Jmeter, a large number (~60) of them do not get served and I see the following in django server logs: - Broken pipe … -
django: Unexpected data type exception trying to use django-excel
So I am trying to use django-excel: https://github.com/pyexcel/django-excel and just simply export a certain model into xls. I set up the settings according to the documentation, but I got this error when running: Exception at /calbase/export/sheet Unexpected data type <class 'django.db.models.fields.files.FieldFile'> Here is my views: def export_data(request, atype): if atype == "sheet": return excel.make_response_from_a_table( Equipment, 'xls', file_name="sheet") elif atype == "book": return excel.make_response_from_tables( [Equipment, Calibration], 'xls', file_name="book") elif atype == "custom": equipment = Equipment.objects.get(slug='ide') query_sets = Choice.objects.filter(equipment=equipment) column_names = ['choice_text', 'id', 'votes'] return excel.make_response_from_query_sets( query_sets, column_names, 'xls', file_name="custom" ) else: return HttpResponseBadRequest( "Bad request. please put one of these " + "in your url suffix: sheet, book or custom") and when I tried to go http://127.0.0.1:8000/calbase/export/sheet it gives me the exception above. By the way is there any good example using django-excel? I can't seem to run the one provided Environment: Request Method: GET Request URL: http://127.0.0.1:8000/calbase/export/sheet Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['calbase.apps.CalbaseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', 'whoosh', 'carton'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, … -
Django export CSV export while preserving column structure
I'm trying to export these responses I have from a form submission I built in Django as CSV, but to do this, the data columns need to match up with the heading columns, comma-per-comma, and currently, I'm getting varying lengths of the responses, meaning that something like the "ZIP code" field, might appear under the ZIP code column in one row, but an entirely different column for another row. I'm using list comprehensions on the responses, so I'd expect all the values to be present, but they aren't. def get(self, request, pk, format=None): queryset = models.SurveyResponse.objects.filter(question__survey_id=pk) sorted_queryset = sorted(queryset, key=lambda x : x.date_created) responses = [] if len(sorted_queryset) == 0 : return JSONResponse(responses) last = sorted_queryset[0].date_created current_index = 0 for q in sorted_queryset: delta = q.date_created - last if delta.total_seconds() >= 1 or delta.microseconds > 60000: # 6/100 of 1 second current_index = current_index+1 if len(responses) == current_index: responses.append([]) responses[current_index].append(q) last = q.date_created response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="responses_grouped.csv"' writer = csv.writer(response) writer.writerow(['response number', 'UTC date','ip_address','session_id']+['other_answer_numeric - ' + str(t.question.title) for t in responses[0]] + ['answer - ' + str(t.question.title) for t in responses[0]] + ['other_answer - ' + str(t.question.title) for t in responses[0]]) for i, res in enumerate(responses): … -
Set initial or default value in dropdown field in Django admin
How do you set the default value in a dropdown field in Django admin? I tried the following but did not work, def get_form(self, request, obj=None, **kwargs): form = super(MyAdmin, self).get_form(request, obj, **kwargs) form.base_fields['myField'].initial = 'DefaultValue' return form def get_changeform_initial_data(self, request): return {'myField': 'DefaultValue'}