Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading file to server and include more parameters
I want to be able to upload a file to a server and send additional parameters in the payload. I have created an api in Django like this which works. class UploadFile(APIView): def post(self,request): if request.method != 'POST': return Response({"response":'Only POST requests are allowed'}) file = request.FILES['filetoupload'] with open('static/media/%s' % file.name,'wb+') as dest: for chunk in file.chunks(): dest.write(chunk) return Response({"response":'File uploaded'}) This is how I am sending a request through ajax. I want to add a media id to the payload. var formData = new FormData(); formData.append('filetoupload', $("#fileToUpload")[0].files[0]); var api_host = $("#api_host").val(); $.ajax({ url : api_host+'users/uploadfile', type : 'POST', data : formData, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', Cookies.get('csrftoken')) }, success : function(data) { } }); Any help is appreciated. -
How to create a public Query data base using Django?
I have been working on Data Science for last three years, this is the first time that I am working on a Public Data base project as I don't have any previous web Development experience. I want to create a simple data base which holds a list of countries: like this; Table-1. S. No. Country 1 Argentina 2 Bangladesh 3 Canada 4 India 5 Pakistan Now each country having some data that can be explore via clicking on a particular country name, Table-2 S. No. OutBreak Year Strains PMID 1 1 1935 O1/O131 123465 2 3 1996 O1 455465 3 5 2012 O131 238475 I have a Very basic knowledge of Mysql and want to pursue this project using Django, what would be the best tutorial or a Way that I can follow ?. I have search lots of tutorial on You tube and other sources but most of them dealt with blog creation or Social Networking. Please give a Suggestion how can I go with Django for this particular Task. Before down voting please give me a suggestion to improve the Question.. :) -
Thread1:EXC_BAD_INSTRACTION
I got an error Thread1:EXC_BAD_INSTRACTION. I am making Swift app and I wanna make a system in my app which upload a image to my Django server. When I did not select any image and I put "Send" button which send images to the server, this error happen. error Now,PhotoController(it is for the system)is import Foundation import MobileCoreServices import UIKit class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! @IBOutlet weak var myImageView: UIImageView! private var imagePicker:UIImagePickerController! @IBAction func uploadButtonTapped(_ sender: Any) { myImageUploadRequest() } override func viewDidLoad() { super.viewDidLoad() label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.text = "Tap the PhotoSelect or Camera to upload a picture" } @IBAction func PhotoSelect(_ sender: Any) { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(myPickerController, animated: true, completion: nil) } @IBAction func Camera(_ sender: Any) { let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera // カメラが利用可能かチェック if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){ // インスタンスの作成 let cameraPicker = UIImagePickerController() cameraPicker.sourceType = sourceType cameraPicker.delegate = self self.present(cameraPicker, animated: true, completion: nil) } else{ label.text = "error" } } // 撮影が完了時した時に呼ばれる func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { myImageView.contentMode = .scaleAspectFit myImageView.image = pickedImage } //閉じる処理 imagePicker.dismiss(animated: … -
How user traffic is monitored in Django?
I'm trying to understand someone else's django code. There he used this line : {# This information is cached and updated periodically via the context. #} <div id="traffic">Traffic: {{ TRAFFIC }} users visited in the last hour</div> I' not able to understand how it is working ? Let me know if you need the views.py file. -
Django, included template can't display login form errors
What I've done: It made sense to me to create a login app where I would handle user authentication. I added custom template tags allowing any of my projects to include html for a login / logout form. The login form has the method="/login/" so this will be resolved by the url patterns and my view will authenticate the user then redirect them to their previous url, whatever page they were on last. No problems all of this works as intended, login and logout is 100% functioning correctly. SO... This is the problem: Since I am not rendering the template from the login app I cannot pass a login error such as incorrect password to be displayed in the form. I apologise that I can't post code snippets and hope the description is enough. -
Embedding Video File in Django Site
I have a Django site that I'm creating, and I want some of the pages to have videos embedded in them. These videos aren't part of a model. I just want to be able to use the view to figure out which video file to play, and then pass the file path into the template. All the files are hosted locally (for now, at least). Is it possible to do with Django? -
Django UWSGI Mysql Access denied
I get a database access error when I use uwsgi Django Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user', 'database': 'db', 'user': 'user', 'password': '12345', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8' }, }, 'OPTIONS': { 'init_command': 'SET default_storage_engine=INNODB', }, } UWSGI settings: [uwsgi] env = LANG=en_US.UTF-8 # spooler spooler = /var/www/api_workon/uwsgi/tasks uid = uwsgi_user gid = www-data virtualenv = /var/www/api_workon/venv/ socket = /var/www/api_workon/run/api-wsgi.sock chmod-socket = 666 chdir = /var/www/api_workon/site/ wsgi-file = /var/www/api_workon/site/wsgi.py env = DJANGO_SETTINGS_MODULE=api.settings master = true processes = 10 vacuum = True max-requests = 10000 harakiri = 20 #disable-logging=True If I run uwsgi from the console everything works fine Uwsgi uwsgi.ini If I run django using python manage.py runserver everything also works fine But, if I run uwsgi via supervisor with the following settings: [program:api] #environment=/var/www/api_workon/venv/ command =/var/www/api_workon/venv/bin/uwsgi /var/www/api_workon/uwsgi/prod.ini autostart = true autorestart = true stderr_logfile = /var/www/api_workon/log/uwsgi/error.log stdout_logfile = /var/www/api_workon/log/uwsgi/access.log stopsignal = QUIT I get the following error: Exception Value: (1045, "Access denied for user 'uwsgi_user'@'localhost' (using password: NO)") -
Django messages: How do I remove floating message header on top of the page?
Using django messages automatically creates a header on the top of my page. views.py messages.error(request, 'Requested break is overlapping') Does anyone know how to remove the message header? I have figured out how to place messages around my site but I can't get rid of the one on the top of my page, which is messing with my already existent nav bar header. -
Django API + React = Encoding pickle
I built an API using Django Rest Framework, that takes data from a utf-8 encoded MySQL database and exposes it. Here the relevant parts. My settings.py includes: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) } My serializer: class UsersSerializer(serializers.ModelSerializer): class Meta: model = User # fields = ('ticker', 'volume') fields = '__all__' My view: class UserData(APIView): def get(self, request, idusuarioweb): users = User.objects.filter(idusuarioweb=idusuarioweb) serializer = UsersSerializer(users, many=True) return Response(serializer.data, headers={'Access-Control-Allow-Origin': '*'}) The index.html file from react also has: <meta charset="utf-8"> I am able to retrieve information from the database and render it on the browser. What I haven't figured out is why I keep seeing UTF-8 symbols instead of spanish accents and other characters. Everything compiles and there is no error messages whatsoever. Can you give me a clue of what am I doing wrong? Thanks in advance! Fede -
Django filter related field using related model's custom manager
How can I apply annotations and filters from a custom manager queryset when filtering via a related field? Here's some code to demonstrate what I mean. Manager and models class OtherModelManager(Manager): def get_queryset(self): super(OtherModelManager, self).get_queryset().annotate( some_flag=True ).filter( disabled=False ) class MyModel(Model): other_model = ForeignKey(OtherModel) class OtherModel(Model): disabled = BooleanField() objects = OtherModelManager() Attempting to filter the related field using the manager # This should only give me MyModel objects with related # OtherModel objects that have the some_flag annotation # set to True and disabled=False my_model = MyModel.objects.filter(other_model__some_flag=True) If you try the above code you will get the following error: TypeError: Related Field got invalid lookup: some_flag To further clarify, essentially the same question was reported as a bug with no response on how to actually achieve this: https://code.djangoproject.com/ticket/26393. I'm aware that this can be achieved by simply using the filter and annotation from the manager directly in the MyModel filter, however the point is to keep this DRY and ensure this behaviour is repeated everywhere this model is accessed (unless explicitly instructed not to). -
need db alias(connection_name) in django.db.backends sql query debug log
I am able to print the sql logs using the logger configuration in django settings as below when I have DEBUG=True 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, [14/Jun/2017 19:50:19] DEBUG [django.db.backends:execute] (0.213) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."session_key" = E'79a9c6354bf0f30967adbcb0d572707a' AND "django_session"."expire_date" > E'2017-06-14 19:50:18.019996' ); args=('79a9c6354bf0f30967adbcb0d572707a', u'2017-06-14 19:50:18.019996') But the information only I get is duration, sql & params Referring django-doc I have multiple DBs in my settings.py to connect and I am using DATABASE_ROUTERS to route my queries to master/slave replication. But I am unable to find the way to log the DB alias (connection_name) to the logger. Is there any way to print all queries with connection_name without using django-debug-toolbar in a log file ? -
Django test VS pytest
I am new to django unittest and pytest. However, I started to feel that pytest test case is more compact and clearer. Here is my test cases. class OrderEndpointTest(TestCase): def setUp(self): user = User.objects.create_superuser(username='admin', password='password', email='pencil@gmail.com') mommy.make(CarData, _quantity=1) mommy.make(UserProfile, _quantity=1, user=user) def test_get_order(self): mommy.make(Shop, _quantity=1) mommy.make(Staff, _quantity=1, shop=Shop.objects.first()) mommy.make(Order, _quantity=1, car_info={"color": "Black"}, customer={"name": "Lord Elcolie"}, staff=Staff.objects.first(), shop=Shop.objects.first()) factory = APIRequestFactory() user = User.objects.get(username='admin') view = OrderViewSet.as_view({'get': 'list'}) request = factory.get('/api/orders/') force_authenticate(request, user=user) response = view(request) assert 200 == response.status_code assert 1 == len(response.data.get('results')) And here is the pytest version def test_get_order(car_data, admin_user, orders): factory = APIRequestFactory() user = User.objects.get(username='admin') view = OrderViewSet.as_view({'get': 'list'}) request = factory.get('/api/orders/') force_authenticate(request, user=user) response = view(request) assert 200 == response.status_code assert 1 == len(response.data.get('results')) The benefit from pytest is fixture in another file. It makes my test case compact by let them be my input parameters. I have read on the internet about coverage. My company is not pay attention on that much Are they any benefit of using Django unittest than pytest? -
django development server not working
Problem: django developer server is not serving the Welcome to Django page following this django tutorial. Instructions Followed: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py sudo python3.5 get-pip.py sudo apt-get install libmysqlclient-dev mysqlclient build-essential python3-dev -y sudo -H python3.5 -m pip install mysqlclient sudo -H python3.5 -m pip install Django cd /mnt/web-server/ django-admin startproject mysite cd mysite Then to start up the developer server I ran the following command: webuser@web-server:/mnt/web-server/mysite$ python3.5 manage.py runserver 8080 & [1] 1649 webuser@web-server:/mnt/web-server/mysite$ Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. June 15, 2017 - 02:52:22 Django version 1.11.2, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CONTROL-C. ^M After going to my browser and trying to access the server on http://192.168.0.165:8080/ I still cannot get it to work. Observations: When I try the usual commands to see if the port is working this is what I get: webuser@web-server:/mnt/web-server/mysite$ netstat -nlp (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it … -
Deploy django rest api app to production
I have created django rest app with python version 3.4.1 and djnago version 1.11.1 abd I am using pyodbc to connect to sql server database. I want to know: Is it possible to host it using IIS and if yes then how? Or What is the best way to host it? -
Can't retrieve user images from from local server with django
I'm having trouble displaying user images in Django, it seems to be mostly working. When the user submits a picture it's successfully storing it in in the right folder. But I can't display the picture Views.py: def upload_pic(request): user = User.objects.get(id=request.user.id) form = ImageUploadForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return render(request, 'tracker/upload_pic.html') def album(request): user = User.objects.get(id=request.user.id) if request.method == "POST": user.extendedprofile.img = request.FILES['uploaded_image'] user.extendedprofile.save() #ExtendedProfile.objects.filter(pk=request.user.id).update(extendedprofile__img=request.FILES['uploaded_image']) return render(request, 'tracker/album.html', {"user": user}) settings.py (relevant portions) STATIC_URL = '/static/' STATIC_ROOT = '/viraone/tracker/static' MEDIA_URL = '/tracker/' MEDIA_ROOT = os.path.join(BASE_DIR, 'tracker/') models.py def user_directory_path(instance, filename): return 'user_images/user_{0}/{1}'.format(instance.user.id, filename) class ExtendedProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0, blank=True) img = models.ImageField(upload_to=user_directory_path) forms.py class ImageUploadForm(forms.ModelForm): #model to store the information about the pictures class Meta: model = ExtendedProfile exclude = () urls.py from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [url(r'^profile', views.profile, name='profile'), url(r'^login', views.login, name='login'), url(r'^export_info', views.export_info, name='export_info'), url(r'^product_page', views.product_page, name='product_page'), url(r'^(?P<object_id>[0-9]+)/$', views.product_details, name='product_details'), url(r'^upload_pic', views.upload_pic, name='upload_pic'), url(r'^album', views.album, name='album'), ] if settings.DEBUG: urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I think it's an issue with urls.py, in the debugging menu it's displaying a 404 error for the correct file path, but … -
Django queryset different behavior in view vs shell
I'm having some weird behavior in regards to a queryset that seems to be determined by what environment I run my code in - when I try to evaluate a queryset on a model in a view, I get nothing, but the same query works in the shell. I have the following model: class ConnectionInfo(models.Model): user = models.ForeignKey(MyUser, related_name='connection_info') app = models.ForeignKey(Application, related_name='connection_info') token = models.ForeignKey(AccessToken, related_name='connection_info') agent_id = models.CharField(max_length=255) class Meta: unique_together = (("user", "app"),) and I can create instances of it just fine. But when I try and get a list of the model's objects in a view, I get back nothing: list(ConnectionInfo.objects.all()) However, when I run the same code in a manage.py shell, it works. And if I get a particular object in the view, it will return it correctly: ConnectionInfo.objects.get(pk=1) I'm forcing the queryset to evaluate so I'm not really sure what's going on here. The same behavior happens with objects.filter() (whether I'm filtering on certain fields or just leaving it blank), and I've also tried the advice here and got nothing. I've verified that there are indeed rows in the db, and they do show up in the admin. This is on django 1.10.7 and … -
Django forms with slider
Is it possible to use a slider with Django Forms with Crispy Forms? I am using Foundation and the example code is below. <div class="slider" data-slider data-initial-start="50" data-end="100"> <span class="slider-handle" data-slider-handle role="slider" tabindex="1"></span> <span class="slider-fill" data-slider-fill></span> <input type="hidden" name="amount"> </div> -
Django: outputting JSON, not OrderedDict
I have a strange problem. I have an API built with the Django REST framework. I'm making a call and getting the following JSON back: { "success": true, "result": { "user_type": "ta", "email": "myemail@gmail.com", "first_name": "John", "last_name": "Smith", "mobile_phone": "555-555-5555", "id": "0f165a85-2da6-4dcb-97cb-bf04900a942b" } } I've tried to add a logging middleware when I'm trying to get the same output from response.data and writing int into a text field in my database. For the very same request response.data is this: (and this gets written into my db, instead of the desired JSON string from above): {'success': True, 'result': OrderedDict([('user_type', 'ta'), ('email', 'myemail@gmail.com'), ('first_name', 'John'), ('last_name', 'Smith'), ('mobile_phone', '555-555-5555'), ('id', UUID('0f165a85-2da6-4dcb-97cb-bf04900a942b'))])} Why is that? How can I get get rid of that OrderedDict and get a perfect JSON string from response.data? when I try json.dumps I'm getting an error about UUID that can't be serialized. However, my Django REST framework is capable of serializing it just fine in the above example... how is that done? -
Django DateTime
I'm using Django and when I retrieve instance (with objects.all()) the models.DateTime are changing so that 7 hours are added. I’m in PT timezone and I’m guessing that my DB is defined as UTC I’m using PostgreSQL and I can’t figure out where is the setting for timezone. If you have other thoughts I would love to hear them. One other thing I’m also getting this warning: RuntimeWarning: DateTimeField received a naive datetime while time zone support is active. RuntimeWarning) Maybe the two are connected. Thanks, Sophie -
uWSGI and Python > 3.4
I have a django project currently running with the following configuration: Debian 8 Python 3.4 uWSGI in emperor mode I installed Python 3.6.1 from source and created a new virtual environment with python 3.6 (I use virtualenvwrapper), but I seem to have some trouble getting the project to start up with uwsgi. Config file is as follows: [uwsgi] plugins = python3 project = %n module = myapp.wsgi:application home = path_to_new_env socket = /var/run/uwsgi-%n.sock chdir = path_to_new_env/myapp/myapp processes = 4 max-requests = 5000 chmod-socket = 666 chown-socket = user:user master = True vacuum = True logto = /var/log/%n_LOG.log buffer-size = 32768 I was under the impression that the python3 plugin would include support for python 3.6, but the log indicates that the Python 3.4.x interpreter is still being used. In my list of installed uwsgi plugins, I see support for python 2, 3 and 3.4 but nothing more. I'm not sure what needs to be done to have the correct interpreter set on startup. Any advice would be appreciated. -
Unable to install Python app on Docker that required GCC
I've added GCC to my Dockerfile, but am unable to "empyrical" due to the error below: building 'bottleneck.reduce' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/bottleneck creating build/temp.linux-x86_64-3.6/bottleneck/src gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/lib/python3.6/site-packages/numpy/core/include -I/usr/local/include/python3.6m -c bottleneck/src/reduce.c -o build/temp.linux-x86_64-3.6/bottleneck/src/reduce.o -O2 unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 My dockerfile: FROM python:3.6.1 RUN apt-get update && apt-get install -y \ gcc \ gettext \ mysql-client libmysqlclient-dev \ --no-install-recommends && rm -rf /var/lib/apt/lists/* # ENV PYTHONUNBUFFERED 1 RUN mkdir /var/www WORKDIR /var/www ADD . /var/www/ RUN pip3 install -r requirements.lock -
Django: Making a Notification Engine
I've been building a notification engine. A person or group can be subscribed to an object and if the object gets updated, the people/groups will be notified of the change by email/sms. Currently, I've implemented it as below: models.py class Subscription(models.Model): # subscribers people = models.ManyToManyField(Person) groups = models.ManyToManyField(Group) # mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() mixins.py class NotificationMixin(object): def perform_update(self, serializer): model_name = str.lower(serializer.Meta.model) old_obj = model.objects.get(id=serializer.data['id']) obj = serializer.save() self.notify(model_name, old_obj, obj) def notify(self, model_name, old_obj, obj): # All models have a GenericRelation field for reverse searching subscriptions = Subscription.objects.filter(**{ model_name: obj }) // *rest of logic to iterate over subscriptions and email people/groups Using django's ContentType generic relations, I can subscribe a person/group to any object. I want to add the capability to create global subscriptions using the same Subscription model so that they are all stored in the same table. A global subscription will not have an object that it is tracking, but when any object of a specific model is triggered, emails will be sent. I'm having trouble generalizing my subscription model to be able to accept a model instance or the model for triggering a … -
how to call multiple blocking processes in django view
I have the following view that calls to http requests: import requests def my_view(request): try: result = requests.get('http://example.com, timeout=15) except requests.exceptions.Timeout as e: print e try: result = requests.get('http://example2.com, timeout=15) except requests.exceptions.Timeout as e: print e I'm now getting the error: Script timed out before returning headers: wsgi.py I found answer here: that mention to up the threads in my WSGIDaemonProcess in the apache config like this: WSGIDaemonProcess mysite.com processes=6 threads=15 display-name=%{GROUP} I am guessing I need to run these on a thread? Is this possible to run on a thread and display in the view ? How can I show the results of http requests in a django view? -
factory_boy extract original kwargs
I'm building a factory with factory_boy that generates a django model. I would like to see what arguments the user inputs inline. My factory itself looks like this class SomeFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'Instance #{}'.format(n)) some_other_thing = factory.SubFactory(SomeOtherFactory) class Meta: model = SomeModel Now the user could say s = SomeFactory() and it would work fine, but I want to detect if the user input their own argument. For instance, to tell if the user passed in their own name, as in s = SomeFactory(name='Matt') What I've tried so far is Writing my own __init__ function in the SomeFactory class This gets mysteriously overwritten and is neither called when I call s = SomeFactory(), nor when I call s.__init__() Same goes for overwriting the __new__ method Overwriting the poorly named _adjust_kwargs This gives me all fields as kwargs, not just the ones the user defined. For instance, calling s = SomeFactory(name='Matt'), I would get a kwargs dict with keys for name and some_other_thing, which makes it impossible to tell input their own argument or not Overwriting _create Still encounter the same problem with overwriting _adjust_kwargs, in that kwargs doesn't contain the original kwargs, but rather all of the arguments … -
Serving Django Channels In Production-like Setting With Apache Directing Traffic
I have been playing around with Django Channels for a a little bit and I am stuck on how to get it to work outside of a local development server setting. Before someone just pastes a documentation page to me, I have exhausted my search of the Django Channels documentation and everywhere else I could find. I can get the local setup to work fine, but not externally. My philosophy over years has been to never develop with the Django development server ever under any circumstances anyways because of exactly this kind of situation. So here it is: I have a django site that has been served by apache for years and uses LDAP user authentication (this matter is beyond my control and pay grade). I've installed Django Channels, asgi_redis, redis-server, and interface server Daphne comes with Django Channels automatically. I'm also working in CentOS 6/7. I have so far worked out that I need to use apache as a reverse proxy to talk to ASGI/Daphne, but I just cannot find the info I need or figure it out myself, apparently. Here's the closest configuration I can figure out. I have my apache configuration file setup as (the URL is …