Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Linode Django uwsgi Nginx
The following setup is only letting me see the default Nginx html page. How can I get to Django? I've been following Linode's documentation on how to set this up (and numerous other tutorials), but they don't use systemd, so things are a bit different. https://www.linode.com/docs/websites/nginx/deploy-django-applications-using-uwsgi-and-nginx-on-ubuntu-14-04 I am using Linode with Fedora24. I have installed my virutalenv at /home/ofey/djangoenv and activated it, Django is installed using pip at /home/ofey/qqiProject Into the virtualenv I've installed uwsgi. Firstly, /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/home/ofey/djangoenv/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target This executes, /etc/uwsgi/sites/qqiProject.ini [uwsgi] project = qqiProject base = /home/ofey chdir = %(base)/%(project) home = %(base)/djangoenv module = %(project).wsgi:application master = true processes = 2 socket = %(base)/%(project)/%(project).sock chmod-socket = 664 vacuum = true Also, /etc/nginx/sites-available/qqiProject server { listen 80; server_name qqiresources.com www.qqiresources.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/qqiProject; } location / { include uwsgi_params; uwsgi_pass unix:/home/django/qqiProject/qqiProject.sock; } } The file /etc/nginx/nginx.conf has not been changed. The user is ofey, I've used, $ sudo systemctl daemon-reload $ sudo systemctl restart nginx $ sudo systemctl start uwsgi.service Started Django with, $ python manage.py runserver To Django's settings.py I turned off … -
Import pandas crash my web app on Amazon Beanstalk
I have got to put my app on Amazon Beanstalk, all work perfectly before to import pandas. When I import pandas, the console doesn't not show any error but takes too long processing and then says: "Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log." When I try to look into my logs, I just can see "[core:error] [pid 3016] ... Script timed out before returning headers: wsgi.py" This is just when I import pandas. On my local machine it works perpectly. Somebody knows how to solve this problem? I couldn't find any clue about resolving this issue. Thanks -
Accesing to JSON nested values (arrays) from Django templates
I have the following JSON document, which have a defined structure: { "paciente": { "id": 1234, "nombre": "Pablo Andrés Agudelo Marenco", "sesion": { "id": 12345, "juego": [ { "nombre": "bonzo", "nivel": [ { "id": 1234, "nombre": "caida libre", "segmento": [ { "id": 12345, "nombre": "Hombro", "movimiento": [ { "id": 1234, "nombre": "Flexion", "metricas": [ { "min": 12, "max": 34, "media": 23, "moda": 20 } ] }, { "id": 12345, "nombre": "Extensión", "metricas": [ { "min": 12, "max": 34, "media": 23, "moda": 20 } ] } ] }, { "id": 12345, "nombre": "Escápula", "movimiento": [ { "id": 1234, "nombre": "Protracción", "metricas": [ { "min": 12, "max": 34, "media": 23, "moda": 20 } ] }, { "id": 12345, "nombre": "Retracción", "metricas": [ { "min": 12, "max": 34, "media": 23, "moda": 20 } ] } ] } ], "___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración", "iteraciones": [ { "victoria": true, "tiempo": 120 }, { "victoria": false, "tiempo": 232 } ] } ] } ] } } } Some times, the segmento array "paciente": ... "sesion": ... "juego": ... **"segmento":[{"id": ...,"nombre":...},{"id": ...,"nombre":...},{"id": ...,"nombre":...}]** came with more that one value, two, three and until four … -
Implementing HTML & CSS into Django
I'm trying to make my views.py point to a HTML page I've made that has embedded CSS, is this the best approach? I'm also running Django locally for testing purposes until it is moved to a production server how would I make local links to point to my HTML ? -
Django database connection issue
I am trying to teach myself Python and Django and so far I am doing ok but I have hit a snag. I have been following the Django MVA as well as using the "Hello Web App" book and searching the web for help when needed but I can't seem to get past this one so here goes... I set up a very simple web app with Django with only one table and one model. I was able to set up the admin module and I can view and manipulate the data in my database in the admin view and the shell but when I launch the site my view doesn't seem to be finding any of the data. My Views.py from django.shortcuts import render, render_to_response from django.http import HttpRequest, HttpResponse from django.template import RequestContext from datetime import datetime from app.models import Order from app.models import *; def MMIR(request): order_list = Order.objects.all(); return render(request, 'app/MMIR.html',{'oder_list':order_list}); My template: MMIR.html {% extends "app/layout.html" %} {% block content %} <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>MMIRs</title> </head> <body> <h2>MMIRs</h2> <ul> {% for order in order_list %} <li>{{order.MMIR}}</li> {%empty%} <li>Sorry there are no orders to display</li> {% endfor %} </ul> </body> </html> {% … -
How can I identify CSS style paths in a bootstrap template?
I'm adding bootstrap templates to my Django project. When loading the page and seeing the content I notice that it does not load the CSS style and when I try to edit the files I get confused a bit by identifying the paths and adding the correct paths where I added the folders with the files where the CSS style is. I would appreciate anyone helping me resolve my question. This is the original file (bootstrap template): <!DOCTYPE html> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Freelancer - Start Bootstrap Theme</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Theme CSS --> <link href="css/freelancer.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> Here is my setting.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' My app(crm)\urls.py file: from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ … -
@staff_member_required is throwing "object has no attribute 'user'"
I'm using this decorator to make this page staff-only: class MyModelAdmin(admin.ModelAdmin): @staff_member_required def dostuff(self, request): return HttpResponse("This is secret") def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = [ url(r"^dostuff/$", self.dostuff) ] return my_urls + urls But for some reason I'm getting: AttributeError: 'MyModelAdmin' object has no attribute 'user' Without the decorator, the view works fine (but anyone can see it). -
Django app deployed to Heroku producing Server error 500
am trying to deploy my first Django app to Heroku. Getting a 500 server error and I can't see why. I've read through my logs and nothing stands out. I had previous issues with the static files but I think these have been sorted as the error now has moved on to a different error. I've attached the log files below: 2016-11-28T22:32:41.153156+00:00 heroku[run.9916]: Awaiting client 2016-11-28T22:32:41.177310+00:00 heroku[run.9916]: Starting process with command python manage.py migrate 2016-11-28T22:32:41.345827+00:00 heroku[run.9916]: State changed from starting to up 2016-11-28T22:32:49.559177+00:00 heroku[run.9916]: Process exited with status 0 2016-11-28T22:32:49.580111+00:00 heroku[run.9916]: State changed from up to complete 2016-11-28T22:32:59.408978+00:00 heroku[run.1808]: State changed from starting to up 2016-11-28T22:32:59.417078+00:00 heroku[run.1808]: Awaiting client 2016-11-28T22:32:59.469233+00:00 heroku[run.1808]: Starting process with command bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput 2016-11-28T22:33:06.511082+00:00 heroku[run.1808]: Process exited with status 1 2016-11-28T22:33:06.502315+00:00 heroku[run.1808]: State changed from up to complete 2016-11-28T22:35:35.165139+00:00 heroku[slug-compiler]: Slug compilation started 2016-11-28T22:35:35.165177+00:00 heroku[slug-compiler]: Slug compilation finished 2016-11-28T22:35:35.488014+00:00 heroku[web.1]: Restarting 2016-11-28T22:35:35.488928+00:00 heroku[web.1]: State changed from up to starting 2016-11-28T22:35:36.129925+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2016-11-28T22:35:36.137263+00:00 app[web.1]: [2016-11-28 22:35:36 +0000] [9] [INFO] Worker exiting (pid: 9) 2016-11-28T22:35:36.137381+00:00 app[web.1]: [2016-11-28 22:35:36 +0000] [8] [INFO] Worker exiting (pid: 8) 2016-11-28T22:35:36.140145+00:00 app[web.1]: [2016-11-28 22:35:36 +0000] [4] [INFO] Handling signal: term 2016-11-28T22:35:36.242634+00:00 app[web.1]: [2016-11-28 … -
How to add CSS classes to Django Built-in forms
I'm using Django Built-in forms, more precisely the PasswordChangeForm. It works perfectly until the point where I want it to look like the rest of the website (Bootstrap). I followed the approach in this answer that is inheriting the class and built a new one by myself: class PasswordChangeCustomForm(PasswordChangeForm): old_password = CharField(required=True, widget=PasswordInput(attrs={ 'class': 'form-control'})) new_password1 = CharField(required=True, widget=PasswordInput(attrs={ 'class': 'form-control'})) new_password2 = CharField(required=True, widget=PasswordInput(attrs={ 'class': 'form-control'})) But it annoys me to repeat all this code. Is there another way to achieve the same thing (add the class form-control to the each field) without re-writing each field? -
How do I create a Django model field that is the union of several queries, in order to implement overriding fields?
I'm working on a user/group API (using django-rest-framework for most things), and am getting hung up on the settings dict that is part of each object. My basic models look like this: class Group(models.Model): name = models.CharField(null=False, unique=True) is_active = models.BooleanField(null=False, default=True) description = models.CharField(max_length=512) class User(models.Model): name = models.CharField(null=False, unique=True, db_index=True) group = models.ForeignKey('Group', related_name='users') is_active = models.BooleanField(null=False, default=True) The JSON returned is simple (views omitted, only notable thing is that I'm not using a PrimaryKeyRelatedField for the users field). Group: { "id": 1, "name": "Basic Group", "is_active": true, "description": "Just a simple group", "users": [ "Test User 1", "Test User 2" ] } Users: { "id": 1, "name": "Test User 1", "group": 1, "is_active": true }, { "id": 2, "name": "Test User 2", "group": 1, "is_active": true } I would like to enhance this by having a "settings" dict for both Group and User object types, that are overriding. That is, the settings dict for a Group will include all global settings, unless a setting with the same name has been set on the group. Similarly, the settings dict for a user will have all of the global settings, overridden by group settings, unless a setting with the … -
Do you know any django package with implementation of python interactive console?
I am looking for some example (open source) of interactive python console, like this one: http://doc.pyschools.com/console - the best would be django package. Do you know any package like this? -
Creating post from Android results in empty json objects
I'm try to create a POST to my django server over the django rest framework, via an android device. The post is initiated on a button press on android. My server does receive something, because my question model gains a new object every time I press the button on the android device, but it's an empty model without text. protected String doInBackground(Void... voids) { Snackbar.make(findViewById(R.id.back_white), "Answered!", Snackbar.LENGTH_SHORT).show(); JSONObject jsonParam = null; StringBuilder sb = new StringBuilder(); try { URL url = new URL("http://" + IpAddress.getIp() + "/category/"); jsonParam = new JSONObject(); jsonParam.put("question", "Question text here, POSTED via Android!"); jsonParam.put("button_pressed", "true"); jsonParam.put("under_this_category", "1"); HttpURLConnection urlConn; urlConn = (HttpURLConnection) url.openConnection(); urlConn.setReadTimeout(10000); urlConn.setConnectTimeout(15000); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("ENCTYPE", "multipart/form-data"); urlConn.setRequestProperty("Authorization", basicAuth); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConn.setRequestProperty("Accept", "application/json"); urlConn.setRequestProperty("Transfer-Encoding", "chunked"); urlConn.connect(); OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream()); Log.v("JSON>>>>>>>", jsonParam.toString()); wr.write(jsonParam.toString()); wr.close(); int HttpResult = urlConn.getResponseCode(); if(HttpResult == HttpURLConnection.HTTP_OK){ BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8")); String line = null; while((line = br.readLine()) != null){ sb.append(line + "\n"); } br.close(); Log.v("Built string>>>>>>>>>>>", sb.toString()); } else { Log.v("RESPONSE :", urlConn.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } finally { //if() } return null; //getServerResponse(jsonParam.toString()); } My expected result: { "id": 57, "question": "Question text here, POSTED … -
How can I increase page load speed?
I need to have multilingual site. For this purpose I wrote django module, which collects lots of info about countries, cities and their translations to almost all languages. Below is the short version of models of this module: class LanguagesGroups(models.Model): class Meta: verbose_name = 'Language Group' class Languages(models.Model): iso_code = models.CharField("ISO Code", max_length=14, db_index=True) group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Group of ISO', related_name='group', db_index=True) class Cities(models.Model): population = models.IntegerField(null=True) territory_km2 = models.IntegerField(null=True) class CitiesTranslations(models.Model): common_name = models.CharField(max_length=188, db_index=True) city = models.ForeignKey(Cities, on_delete=models.CASCADE, verbose_name='Details of City') lang_group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Language of city', null=True) class Meta: index_together = (['common_name', 'city'], ['city', 'lang_group']) I want to show to users some data about places which user requested with translated versions of cities (depending on user settings): class Profile(models.Model): title = models.CharField(_('title'), max_length=120) info = models.TextField(_('information'), max_length=1500, blank=True) city = models.ForeignKey(Cities, verbose_name=_('city'), null=True, blank=True) def get_city(self): user_lang = get_language() # en lang_group = Languages.objects.get(iso_code=user_lang).group # 1823 return CitiesTranslations.objects.get(city=self.city, lang_group=lang_group).common_name template.html {% for item in object_list %} {{ item.title }} {{ item.get_city }} {{ item.info }} {% endfor %} When I add {{ item.get_city }}, in case of pagination and just 25 items per page, the page load speed goes down up to 18 times and … -
Post issues to Bitbucket via Python requests
I'm trying to post issues to bitbucket via their api. If I understand correctly it seems I can go the basic authentication route rather than OAuth. When making the request, though, when print(r.status_code) runs I'm getting a 400 code back in the terminal. The problem seems to be in either the json (which I doubt) or the authentication. I'm running this in a django project and my code is as follows: views.py if request.method == "POST": getUser = request.user form = IssueForm(request.POST) if form.is_valid(): data = {"priority": "major", "title": "title", "kind": "bug", "content": "content"} headers = {'Content-Type': 'application/json',} r = requests.post('https://api.bitbucket.org/1.0/repositories/{my_username}/{my_repo}/issues/', headers=headers, json=data, auth=({username},{password})) print(r.status_code) return HttpResponseRedirect("/main/") else: form = IssueForm() context = { "form": form, } return render(request, "issue_form.html", context) Possibly basic authentication is not allowed for posting issues and instead OAuth is necessary? However, I have not found any documentation that has indicated as such. Username, repo, and password are filled in accordingly. Any help would be much appreciated. -
paypalrestsdk with Django integration issue
I am trying to setup Paypal express checkout with REST API but when I click checkout with Paypal I get modal window and it just spins forever. Payment create view: def payment_create(request): logging.basicConfig(level=logging.INFO) paypalrestsdk.configure({ 'mode': settings.PAYPAL_MODE, 'client_id': settings.PAYPAL_CLIENT_ID, 'client_secret': settings.PAYPAL_CLIENT_SECRET }) # Create payment object payment = paypalrestsdk.Payment({ "intent": "sale", # Set payment method "payer": { "payment_method": "paypal"}, # Set redirect urls "redirect_urls": { "return_url": "http://127.0.0.1:8000/checkout/payment_done/", "cancel_url": "http://127.0.0.1:8000/checkout/payment_error/"}, # Set transaction object "transactions": [{ "amount": { "total": "10.00", "currency": "USD"}, "description": "payment description"}]}) # Create Payment and return status if payment.create(): print("Payment[%s] created successfully" % (payment.id)) request.session["paymentID"] = payment.id # Redirect the user to given approval url for link in payment.links: if link.method == "REDIRECT": print("Redirect for approval: %s" % (link.href)) return HttpResponseRedirect(link.href) else: print("Error while creating payment:") print(payment.error) Cart.html template: <div id="paypal-button"></div> <script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script> <script> paypal.Button.render({ env: 'sandbox', // Optional: specify 'sandbox' environment payment: function(resolve, reject) { var CREATE_PAYMENT_URL = 'http://127.0.0.1:8000/checkout/payment_create/'; paypal.request.post(CREATE_PAYMENT_URL) .then(function(data) { resolve(data.paymentID); }) .catch(function(err) { reject(err); }); }, onAuthorize: function(data) { // Note: you can display a confirmation page before executing var EXECUTE_PAYMENT_URL = 'http://127.0.0.1:8000/checkout/payment_execute/'; paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID }) .then(function(data) { window.location.replace("http://127.0.0.1:8000/checkout/payment_done/") }) .catch(function(err) { window.location.replace("http://127.0.0.1:8000/checkout/payment_error/") }); } }, '#paypal-button'); </script> From … -
Django - Query for any objects where any item from list is in ManytoMany field
I have a model in Django that has a ManytoMany field called 'accepted_insurance'. I have a form that submits a get request with a query string that contains of list of insurance providers. I am trying to write a query that says 'If any of the items from the query string list, are in the ManytoMany field list, than filter those objects.'. Is there a Django query shortcut for this ? I attempted to use 'contains', but I got a type error that the related field got an invalid lookup, and I'm sure that would simply say if the list contained the list. models.py class Provider(models.Model): title = models.CharField(max_length=255, null=True, blank=True) first_name = models.CharField(max_length=255, null=True, blank=True) middle_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=40, null=True, blank=True) extension = models.CharField(max_length=10, null=True, blank=True) company = models.CharField(max_length=255, null=True, blank=True) age = models.IntegerField(null=True, blank=True) about = models.TextField(default='', null=True, blank=True) position = models.CharField(max_length=255, null=True, blank=True) cost_per_session = models.CharField(max_length=255, null=True, blank=True) accepts_insurance = models.BooleanField(default=False) accepted_insurance = models.ManyToManyField('Insurance', blank=True) payment_methods = models.ManyToManyField('PaymentMethod', blank=True) request.GET http://localhost:8004/directory/?search=timothy&insurance=cigna,aetna,optum_health,united_behavioral,blue_cross_blue_shield <QueryDict: {'insurance': ['cigna,aetna,optum_health,united_behavioral,blue_cross_blue_shield'], 'search': ['timothy']}> views.py Query for param in request.GET: if param.lower() == 'insurance': all_providers = all_providers.filter(accepted_insurance__contains=param) -
Django Rest Framework - Extending token authentication class
I want to use the built in Token Authentication provided by the DRF. However, I only want Token Authentication to run if "mode=1" is not passed into the header. If that is passed into the header, then I want to use custom permission that does not involve user. Is there any way I can extend the functionality of the already existing Token Authentication to do this or will I have to make a custom Token Authentication from scratch? TLDR: If request.META.get('HTTP_MODE', None) == '1': # Don't use token authentication, use custom permission class instead. else: # Use built in token authentication -
Removing EXIF information from photos getting uploaded in a Django app
I'm having issues with photos getting rotated upon upload in my Django app. I have pinpointed the issue to EXIF data that tells the browser to rotate the images. For example: Make : Apple Camera Model Name : iPhone 4 Orientation : Rotate 90 CW What is the recommended way of removing EXIF data from Images in a python Django app? Among other things, I also don't want EXIF data for privacy reasons. -
Why I Can't import CSS/JS code in an error page using django
I've a custom error_page in my django app that I call when something got wrong. The problem is when I try to load my 'base.html' or anything related to javascript, CSS, or python code I got errors like: ValueError: The file 'style.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7ff3b288d9d0>. Here my code: URLS.PY from django.conf.urls import handler400, handler403, handler404, handler500 handler500 = main_views.server_error MAIN_VIEWS.PY def server_error(request): return render (request, 'error_page.html', status=500) ERROR_PAGE.HTML {% extends "account/base.html" %} {% block head_title %}Error Page{% endblock %} {% block content %} <script> setTimeout(function() { $.get("{% url 'home_page' %}") // Do something after 5 seconds }, 5000); <script/> <h1><b>AN ERROR OCURRED! THIS PAGE DOESN'T EXISTS OR COULDN'T BE FIND! YOU WILL BE REDIRECTED TO HOME PAGE IN 5 SECONDS...</b></h1> {% endblock content %} What's wrong? -
Pass Django CSRF token to Angular with CSRF_COOKIE_HTTPONLY
In Django, when the CSRF_COOKIE_HTTPONLY setting is set to True, the CSRF cookie gains the httponly flag, which is desirable from a security perspective, but breaks the standard angular solution of adding this cookie to the httpProvider like so: $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; Through Django 1.9, there was a workaround where you could just pass the cookie directly to the app by putting this in the template: <script> window.csrf_token = "{{ csrf_token }}"; </script> And putting this in the angular app: angularApp.config(["$httpProvider", function($httpProvider)e { $httpProvider.defaults.headers.common["X-CSRFToken"] = window.csrf_token; }] Unfortunately, this doesn't work for single page angular apps in Django 1.10+ since the CSRF cookie changes after every request. How do you make post requests from Angular to Django 1.10+ with the CSRF_COOKIE_HTTPONLY setting on? Disabling CSRF protection is not an acceptable answer. -
Custom querysets and annotation
It turns out that annotation works incorrectly with custom querysets ? Consider the following model: class FooQuerySet(models.query.QuerySet): def my_custom_filter(self): return self.filter(...) class Foo(models.Model): field_a = ... field_b = ... val = ... objects = FooQuerySet.as_manager() And the view: def my_view(request): a = a.objects.my_custom_filter().values('field_a'). .annotate(Sum('val')) Now consider a sample queryset: field_a | field_b | val a1 | b1 | 10 a1 | b2 | 20 a2 | b3 | 30 a2 | b4 | 40 The anticipated result: a1 - 30 a2 - 70 The actual result: a1 - 10 a1 - 20 a2 - 30 a2 - 40 Why I blame this on custom querysets? If I remove the custom filter and write pure-Django code, everything is fine. Any ideas ? -
Django turn url to image / views
Hı, i have a model in my django code that stores urls of images but how am I going to write a view that displays them as images in a list? class Blog(models.Model): photo = models.CharField(max_length=200, unique=True) story = models.TextField(unique=True) pub_date = models.DateTimeField('date published', default=datetime.datetime.now) -
tweet.favorited returns false tweepy even the tweet is favorited
I want to favorite tweets, which user hasn't tweeted yet. For the same, I wrote following: try: tweets = api.user_timeline(screen_name = handleSubmit,count=retweetCount) for tweet in tweets: if not tweet.favorited: print tweet api.create_favorite(tweet.id) if not tweet.retweeted: api.retweet(tweet.id) except Exception as e: raise e But, in some cases tweet.favorited returns false, even if tweet is already favorited, leading to following error: [{u'message': u'You have already favorited this status.', u'code': 139}] What am I doing wrong here? -
Django: TypeError preventing attaching a bytes-like object to email
I am trying to use xlsxwriter to generate a xlsx file and then send it as an attachment in email. Here is what I have now: def WriteToExcel(project): output = BytesIO() workbook = xlsxwriter.Workbook(output) #putting in data workbook.close() xlsx_data = output.getvalue() # xlsx_data contains the Excel file return xlsx_data def project_email (request, project_id): project = Project.objects.get(id = project_id) xlsx_data = WriteToExcel(project) message = EmailMessage("Heading", 'Here is the message.', 'intranet.mailsender@pctestlab.com', ['lihansong1993@gmail.com']) message.attach_file(xlsx_data) message.send() And when I tried to send the email, I have the following error: TypeError at /projstatus/1/email cannot use a string pattern on a bytes-like object Is there any way that I could go around it? Like, make the xlsx file non-binary or if there is a function in email to attach binary file? -
django 1.10.3 Cannot resolve bases empty models.py and droped tabels
I have a playground for model developement. The Error django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for ... Keeps occuring though i tried a hell of a lot: of course python manage.py makemigration <appName> python manage.py migrate <appName> drop all tables from the app python manage.py squashmigrations main 0001 emptied the models.py file uncommented the app in settings read everything i could find on that Any idea, how to solve this? Thanks, Daniel