Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework : <Objectname: Objectname object> is not JSON serializable
I have a customer model and an event model. event model refer to the customer. A customer has many events. My requirement is when I get the customer, I need the latest event object of the customer. When I call the customer Get API, it shows the following error, TypeError at /api/v1/customer <Event: Event object> is not JSON serializable My Models class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20, unique=True) #some more fields to go def __str__(self): return str(self.name) def latest_event_name(self): """Return latest event """ latest_event = self.customer_events.order_by('-event_date').last() return latest_event if latest_event else None class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event_name = models.CharField(max_length=200, unique=True) customer = models.ForeignKey(customer_models.Customer, db_index=True, on_delete=models.SET_NULL, related_name='customer_events', null=True) #some more fields to go serializer class CustomerSerializer(serializers.ModelSerializer): latest_event_name = serializers.ReadOnlyField() class Meta: model = Customer fields = '__all__' -
How do you get amazon SQS to work with Django celery
I am trying to get ques to work with Amazon SQS but tasks aren't run. However My tasks run out of the box with rabbitmq here are the links i have tried (among others) Celery with Amazon SQS https://www.caktusgroup.com/blog/2011/12/19/using-django-and-celery-amazon-sqs/ They seem to be quite dated. on my cues I do not get any messages received when i log into the amazon console but i see the celery logs have activity showing they are communicating with Amazon DEBUG b'<?xml version="1.0"?><ReceiveMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><ReceiveMessageResult/><ResponseMetadata><RequestId>f8d10c14-99f7-520b-a58d-5d2cc203ad8b</RequestId></ResponseMetadata></ReceiveMessageResponse>' Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Method: GET Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Path: /967610578225/transfer_files Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Data: Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Headers: {} Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Host: eu-west-1.queue.amazonaws.com Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Port: 443 Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Params: {'Version': '2012-11-05', 'Action': 'ReceiveMessage', 'WaitTimeSeconds': 0, 'MaxNumberOfMessages': 4} Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG Token: None Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log DEBUG CanonicalRequest: Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log GET Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log /967610578225/transfer_files Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log Action=ReceiveMessage&MaxNumberOfMessages=4&Version=2012-11-05&WaitTimeSeconds=0 Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log host:eu-west-1.queue.amazonaws.com Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log x-amz-date:20170307T065652Z Mar 7 08:56:52 ip-172-31-41-253 e-celery-worker.log , 'Authorization': 'AWS4-HMAC-SHA256 Credential=xxxxxx/20170307/eu-west-1/sqs/aws4_request,SignedHeaders=host;x-amz-date,Signature=xxxxxx', 'User-Agent': 'Boto/2.45.0 Python/3.4.3 Linux/4.1.17-22.30.amzn1.x86_64', … -
Upload a photo to Django in Swift 3 using Alamofire 4?
I can't seem to upload a photo correctly to Django. Here's the problem. request.FILES is empty. However, in the body I see a bunch of gibberish (which would be the photo data). I've tried this to make it work but it still shows as empty: In Django: class UploadPhoto(APIView): parser_classes = (MultiPartParser, FormParser, ) authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request, format=None): print(request.FILES) return Response(status=status.HTTP_200_OK) In iOS: func photoUploader(photo: UIImage, completion: @escaping (Bool) -> Void) { let imageData = UIImageJPEGRepresentation(photo, 0.8) guard let authToken = Locksmith.loadDataForUserAccount(userAccount: "userToken")?["token"] as? String else { return } let headers: HTTPHeaders = ["Authorization": authToken] var url: URLRequest? do { url = try URLRequest(url: EntityURLs.uploadPhotoURL, method: .post, headers: headers) } catch { print("Error") } if let url = url { upload(multipartFormData: { (mpd) in mpd.append(imageData!, withName: "file", mimeType: "image/jpeg") }, with: url, encodingCompletion: { (success) in debugPrint(success) }) } } -
Does Django model field default setting sets blank=True?
I have a question for the Django model field when applying the default setting. My problem is as follows: # Model description class aa(models.Model): a = models.FloatField(default=1) b = models.FloatField() When inserting an entry into the database, I apply the following functions to do the validation without any error: data = {'b': 1.1} # Just for demo... p = aa(**data) p.full_clean() p.save() Here is the problem, is the case that when I set the default value for a field, the blank is automatically set to True? P.S. I know what are the differences between null and blank, I just want to figure out the issues related to the default. -
Django shows Python socket.error: [Errno 104] Connection reset by peer
I have a django+mysql website on AWS. Client send post request to website, then the website query the mysql database and return a json. I am doing stress testing to it. I send 300 post requests simultaneously to the website and get responses correctly. But if I increase the number of post request to 400, it fails with following log. Server side : File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run self.finish_response() File "/usr/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response self.write(data) File "/usr/lib/python2.7/wsgiref/handlers.py", line 212, in write self.send_headers() File "/usr/lib/python2.7/wsgiref/handlers.py", line 270, in send_headers self.send_preamble() File "/usr/lib/python2.7/wsgiref/handlers.py", line 191, in send_preamble self._write('HTTP/%s %s\r\n' % (self.http_version,self.status)) File "/usr/lib/python2.7/wsgiref/handlers.py", line 391, in _write self.stdout.write(data) File "/usr/lib/python2.7/socket.py", line 328, in write self.flush() File "/usr/lib/python2.7/socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 104] Connection reset by peer Client side: HTTPConnectionPool(host='mywebsite.com', port=3456): Max retries exceeded with url: /project/result.json (Caused by <class 'socket.error'>: [Errno 104] Connection reset by peer) I have tuned the mysql configuration for higher max_connections and timeout but it doesn't work. Can anyone help me to resolve the issue? Thanks. -
When I add an image using django-pagedown, it automatically adds an "insert image description here" above the image url. How do I remove this string?
I'm using django-pagedown as a text editor for my django application (where users submit posts). django-pagedown allows users to click the img icon in the editor bar to paste an image URL. When the user enters a URL it adds this to the editor body: ![enter image description here][1] [1]: https://www.website/imagePastedFromTheUser.jpg I want to remove the "enter image description here". Here is the documentation for MarkdownEditor.js (the main file in django-pagedown which I think will allow me to remove it): https://github.com/timmyomahony/pagedown/blob/77f33b47bc670b50a3b19947a7a434f7138feabd/Markdown.Editor.js#L38 As you can see on line 38 I can change the contents of the string. However when I remove it I get an error in my console and the img upload buttons doesn't work: Uncaught TypeError: Cannot read property 'length' of undefined at TextareaState.setChunks (Markdown.Editor.js:834) at fixupInputArea (Markdown.Editor.js:1375) at linkEnteredCallback (Markdown.Editor.js:1793) at close (Markdown.Editor.js:1123) at HTMLFormElement.form.onsubmit (Markdown.Editor.js:1149) So removing it causes a chain of errors and i'm unsure how I can remove it while not affecting the image upload function. -
Pre-loading image in django admin add form from another model
I have a model, class Abc(models.Model): . . pic = models.ImageField(upload_to = path,default = 'images/nophoto.jpg') . . And in admin list view for this model, have an Add button column which will load add form of another model admin (Xyz) which also have an image field. What I want is to pre load image from selected Abc instance in Xyz add form. I have tried def add_view(self, request, form_url='', extra_context=None): . . g = request.GET.copy() g.update({ 'image': abc_instance.image, }) request.GET = g . . In Xyz admin, and it shows image in form but on saving image is not getting saved. What can I do to accomplish this? -
Troubles installing mysqlclient with pip3
I'm trying to set up a python 3.6 environment with Django. The installation instructions say I should install mysqlclient to be able to connect to mySQL. I get this: dennis@django:~$ sudo -H pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-4jiw3hvk/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4jiw3hvk/mysqlclient/ You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. mySQL is properly installed. What should be in the mysql_config file? When I try to upgrade pip3 I get this: dennis@django:~$ sudo -H pip3 install --upgrade pip3 Collecting pip3 Could not find a version that satisfies the requirement pip3 (from versions: ) No matching distribution found for pip3 You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade … -
how to add content into request.files without using enctype?
I'm using iOS to make requests to my server running my django app. Obviously, HTML is not necessary. However, when I try to upload a photo via iPhone, the request.body has the photo data (all gibberish) but it doesn't have that data inside request.FILES I'm reading the Django Docs and it says: Note that request.FILES will only contain data if the request method was POST and the that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty. However, I'm not working with forms. I'm using an iOS device to do the uploading, not a web page. Is there an alternative to using request.FILES in order to accomplish what I want? -
values() returns datetime with tzinfo = UTC in default, can I change the default timezone before calling values()?
{'began_datetime': datetime.datetime(2017, 3, 7, 2, 18, 3, 644392, tzinfo=<UTC>)} For example, values() return something like this. But I want it return the datetime with timezone = settings.TIME_ZONE. Is that possible? -
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3
I tried re-installing python 2 in my environment. Re-installed pip, setuptools when I try to run python manage.py runserver it throws the error django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 I tried installing sqlite 3 , its already installed I tried installing pysqlite2 , its already installed both python 2 and installed in my ubuntu 16.04, django version = 1.8.X Still unaware of what cause the error? -
PyCharm Run Issues Django With External Virtual Environment
I'm using Pycharm 2016.3.2 on Windows 10. I have a Django project using an separate virtual environment( ie. virtual environment is in totally separate folder to the project). I am using a Postgres server which is working fine and can be seen by Pycharm and can test connect. The problem I have is when I go to Run it in Pycharm the server is not starting. I get the following in the Run window: "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\bin\runnerw.exe" C:\Pyprojects\VirtualEnvs\venv2\Scripts\python.exe C:/Pyprojects/MyProject/manage.py runserver 8000 Process finished with exit code -1073741819 (0xC0000005) I can attest to this all actually working outside Pycharm. I can use 'runserver' from my virtual environment using Windows command prompt. I can then get into my django site once I've started it that way with no problems. Can anyone shed some light on how to make this work with Pycharm? I just purchased Pycharm professional and hopefully this will have some kind of easy fix. Thanks in advance for any help. Marco -
Configuration for Django web app that will be hosted on remote Windows Server
I am currently in the process of developing a web application as part of a senior project for a company (not paid purely academic). I am running Python 2.7.13 and am running the Django web app locally through Pycharm without problem. My group is at the point in the project where we need to attempt to start migrating this web application to an external server that is provided to us by the company. The way we have been given access to this server is first through Cisco Anyconnect Secure Mobility Client ( we use a specific URL, username, and password to access this). Once connected to this VPN, we use Remote Desktop Connection to connect to a given private IP address with correlating password. The Server is a Windows Server 2012 R2. As I stated above, I have had no problem up to this point developing the web app and running and testing locally. However, I do not have a whole lot of experience hosting a Django app on an external server. I'm assuming I need to add some authentication in my settings file, but my main question is how do I need to configure my Django project so that … -
request.FILES is empty when I try to upload photo in Alamofire
I'm trying to upload a photo to Django but when I check to see if there's anything in request.FILES is shows <MultiValueDict: {}>. Here's what is outputted in the console: success($ curl -i \ -X POST \ -b "csrftoken=iNA07wxmvR4ORBEgYssIUtqMIhEefiBY5LQitToBblXqZV1u0BdfnFDLsDRgfvdy;sessionid=46gur99eyig6p27v7fcn46pt0s55q75n" \ -H "Content-Type: multipart/form-data; boundary=alamofire.boundary.0fcf8517af30e7f5" \ -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ -H "Accept-Language: en;q=1.0" \ -H "Authorization: Token f5766977db0863354506a5be78c52680b017af18" \ -H "User-Agent: app/1.0 (com.user.app; build:1; iOS 10.2.0) Alamofire/1.0" \ "http://127.0.0.1:8000/uploadphoto/", false, nil) I'm not sure if I'm uploading the photo right but here's my function: func photoUploader(photo: UIImage, completion: @escaping (Bool) -> Void) { let imageData = UIImageJPEGRepresentation(photo, 0.8) guard let authToken = Locksmith.loadDataForUserAccount(userAccount: "userToken")?["token"] as? String else { return } let headers: HTTPHeaders = ["Authorization": authToken] var url: URLRequest? do { url = try URLRequest(url: EntityURLs.uploadPhotoURL, method: .post, headers: headers) } catch { print("Error") } if let url = url { upload(multipartFormData: { (mpd) in mpd.append(imageData!, withName: "xyz", mimeType: "image/jpg") }, with: url, encodingCompletion: { (success) in debugPrint(success) }) } } -
Custom Zinnia styles intermittently fail to load on deployed app
My Django project uses custom templates for the list and detail view of entries in a Zinnia blog, which are setup as described in the docs. This works perfectly on my local development environment. On the deployed version it also works perfectly... sometimes; other times it loads the default styling. When this happens there are no errors, it simply seems as if there are no custom html/css files at all. I estimate that it loads correctly 70% of the time and with the default format 30% of the time, and there is no pattern I can discern. The application is deployed to two Heroku apps, one for testing and the other production, and they both experience the same issue. The apps are deployed with Gunicorn and Whitenoise. I can not reproduce the error locally and have no idea where to look in order to fix this. Any help you can give me is much appreciated. Thank you. I am using django 1.10.5 and django-blog-zinnia 0.18. -
Is there a way to use youtube-dl to get the video url for the client on my web app by using Javascript or something else?
I am trying to extract the source urls from Dailymotion, Openload, and Google Video using youtube-dl. I am fully aware that a url retrieved from one computer will not work on another because each link is IP/cookie/user agent specific as well as time sensitive. source The issue with this approach is my attempt to retrieve the urls solely via the server. The solution would be if the client side was responsible for all the interactions and requests to retrieve the urls. I am not well-versed in Javascript but I am confident that it is the solution to the above problem. I know of the existence of a node.js variety of youtube-dl but it isn't actively maintained, a dead end. source There are node.js projects that are actively developed but only supports youtube. source Alltube, a web app variety of youtube-dl, used to be able to do this but has taken out the feature because it was too taxing to the server(?), mind you they used php server side to do this. source Does anyone know how to extract urls with Javascript for client side requests? Is there something other than youtube-dl that can accomplish this? -
Django count unique items in field and group by parent field with field selection
I'm using Django 1.10, python 2.7, mysql and I'm trying to get a count of each unique value in a particular field, but I would like a summary count for each of the parent instances. I'm fairly new to Django and database design so please do let me know if I've got my structure wrong. i.e. I have two models in question here TestRun: branch - Branch test was run on - charField requester - Who initiated test - charField commit - What commit id it is. - integerField instance - differentiate between rerun of same commit - integerField Each Testrun can have multiple test results TestResult: testrun - foreign key testcase = charField commit - same as in test run - duplicated for performance reasons result = charField i.e pass, fail, blocked, errored etc Now I would like to get a summary of results by instance: i.e. [{instance: 5, commit: 28000, resquester: bob, pass: 5, fail: 4, blocked: 4, errored: 6}, {instance: 500, commit: 28100, requester: sally, pass: 2, fail:3, blocked: 8, errored: 3}] The method I have working so far is as follows: Get distinct list of commits For each commit get unique instances For each instance use … -
python plugin for django template on sublime
i'm using 'anaconda' for adhering to pep 8. i just want to know if there is a plugin like 'anaconda' for Django templates (the html part). thanks i tried djaneiro ,but i'm still looking for other option. thanks -
is there a way to sort the columns of in admin models? django
Sometimes we are able to click on the column then the table will be sorted by what's clicked BUT some are not clickable and I do believe those none clickable are because it's not the fields in the model that it's either a foreign key or M2M I am wondering if there's a way to make them clickable to sort too? for example of the following, title and created_at are clickable but not SET Thanks in advance for any suggestions and help. -
django howt to autofill multiple field by ForeignKey (other table)
My Goal I'd like to create an autofill form whose initial value comes from other table. At first, I tried to create 2 models. The first one is "Initial Value group", and the second one is "Main table". For example, -------------------------- Initial value group table -------------------------- class Book_type_info(models.Model): id = models.AutoField( primary_key=True, ) book_type = models.CharField( "Book Type", max_length=10, ) sales_type = models.CharField( "Sales Type", max_length=10, ) -------------------------- Main table -------------------------- class Book_Stock(models.Model): id = models.AutoField( primary_key=True, ) book_title = models.CharField( max_length=20, ) book_type_id = models.ForeignKey( "Book_type_info", ) book_type = models.CharField( "Book Type", max_length=10, ) sales_type = models.CharField( "Sales Type", max_length=10, ) price = models.PositiveIntegerField( "Price", ) tax = models.PositiveIntegerField( "Price", ) ------------------------------------- Initial vales group has the following data. | id | book_type | sales_type | | 1 | paper | store | | 2 | ebook | amazon | | 3 | pdf | public | When I'd like to add data to main table, The input form is following. --------------------------------- id [ ] book_title [ ] book_type_id [ -- select -- ] book_type [ auto fill by "book type id", but can change ] sales_type [ auto fill by "book type id", but can change ] price … -
Comparing time between 2 lists in Django Template
I know there is something probably wrong with the logic and I have been working on this for some time and can't think straight right now and could really use some help. I am basically trying to print out a list of events of any given day in my Django template. The problem I am running into is when I have multiple events on any given day. The time_slots that has an event (which is coming in from my_workouts) prints out the book button as well on it's second or third run through the loop. {% for slot in time_slots %} {{ slot.time }} {% for event in my_workouts %} {% ifchanged %} {% if event.start_time <= slot.time and event.end_time > slot.time %} EventExists {% else %} <button type="button" class="btn">Book</button> {% endif %} {% endifchanged %} {% endfor %} {% endfor %} It currently prints out as... 09:00 EventExists [Book] 10:00 [Book] 11:00 [Book] 12:00 [Book] EventExists I would like it to print as... 09:00 EventExists 10:00 [Book] 11:00 [Book] 12:00 EventExists -
Django Channels vs. Creating sockets for clients all the time
I want to send messages to a python program, when I get requests in Django via a socket. import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('localhost', 8089)) serversocket.listen(5) # become a server socket, maximum 5 connections while True: connection, address = serversocket.accept() buf = connection.recv(64) if len(buf) > 0: print buf break Should, I create a client socket for each request: def testurl(req) clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('localhost', 8089)) clientsocket.send(req.GET['hello']) Or should I create a socket based system, the whole way with Django Channels or some such system TLDR My basic question is, is there a way to send data to a server socket from a Django website, without bothering to install channels? -
How to render xml in django template
How would I render the following properly? <pre> <code class="language-markdown"> {% autoescape on %} <Item>hello</Item> {% endautoescape %} </code> </pre> Basically, I want it to show the xml, like: <Item>Hello</Item> And not try and strip the tags. -
DJANGO background task always on
I am currently developing an Django based web application which does some sentiment processing on global tweets and displays them on a google map. I am currently stuck in one part that how do i get the Django application to keep collecting tweets in the background? like even if somebody is not accessing the web link of application, It should keep on collecting tweets and store them in Amazon elastic search. I have searched Google and reference materials but there are different views which are confusing. Can anybody help me? The application will be deployed on amazon elastic beanstalk. -
Django migration introducing unique_together
I have an existing Django application, that has fields A & B. Now a new requirement arises where I need to introduce unique_together('A','B'). So when I apply the migration I will be getting IntegrityError for the existing data that violate this new constraint. What would be the best solution for applying migration? Current I am imagining to write a snippet for RunPython or RunSQL that finds the existing duplicates and de-duplicate them by leaving one row as it is and for others simply append the B's value into A's value Any other better thoughts?