Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database for saas application
I have to make a Django saas (Software as a service) application for ecommerce website. Each website feeds his database (Product and Customer tables) on my server and I have one Postgresql database. I know that django-tenant-schemas exists to separate data for each website but I actually can't use it because my application will be used by ecommerce website's customers thanks to a Javascript widget (It means that the sender could have any IP address). When I receive a request from customer, I identify the website origin with an unique key for each ecommerce website. I have already created the Django project with the two models Product and Customer. My question is how to create with Django these two tables for each website and how to select the right table thanks to the unique key when a customer call my API ? Thank you for your response. -
How might I send an API's result to an Arduino to control LED glow?
I have written JavaScript (I'm considering having this in a Django app) that takes input from the webcam and returns a parameter. Based on this parameter, I would like the Arduino to decide which LED should glow. What would be the best way to send an API's response to an Arduino to control an LED accordingly? -
Celery not picking CELERY_ALWAYS_EAGER settings
I am running Django 1.8 + Celery 4.0.2 Celery is configured well and can run my django tasks locally on redis backend. But when I try to use CELERY_ALWAYS_EAGER = True settings, this settings has no effect. WHich is not the case with other settings, e.g. CELERY_TIMEZONE Specifically, in pdb I see that app.conf.task_always_eager is False lib/python2.7/site-packages/celery/app/task.py(520)apply_async() So somehow CELERY_ALWAYS_EAGER is not picked up and has no effect on app.conf.task_always_eager What can cause this? I know that Celery 4.x is in transition from old setting names to new ones, but they still promise old settings names still would be used as well. -
Django ORM get return value of model-class method in QuerySet
I'm programming a farming game to learn Django. For one of my views, I would like both the fields of an Object, as well as the result value of one of its methods. Preferrably in the same collection. My model looks like this: class Planted(models.Model): farm = models.ForeignKey(Farm, on_delete=models.CASCADE, null=False, blank=False) crop = models.ForeignKey(Crop, on_delete=models.CASCADE, null=False, blank=False) date_planted = models.DateTimeField(auto_now=True) # ... def can_be_harvested(self): # Returns value to be included in QuerySet I've tried including it in a QuerySet as an extra()-value. My attempts failed and Django's documentation mentions possible deprecation on this modifier, so this is most likely not the way to achieve what I want. How can I query my model so that fields as well as method-results are returned in one collection? -
Django Celery Worker Not reciving the Tasks
Whenever I am running the celery worker I am getting the warning ./manage.py celery worker -l info --concurrency=8 and if I am ignored this warning then my celery worker not receiving the celery beat tasks After googled I have also changed the worker name, but this time I am not receiving the warning but celery worker still not receiving the celery beat scheduled tasks I have checked the celery beat logs, and celery beat scheduling the task on time. I have also checked the celery flower and its showing two workers and the first worker is receiving the tasks and not executing it, how to send all task the second worker? or how can i disable the first kombu worker, what is djagno-celery setting that i am missing? My django settings.py RABBITMQ_USERNAME = "guest" RABBITMQ_PASSWORD = "guest" BROKER_URL = 'amqp://%s:%s@localhost:5672//' % (RABBITMQ_USERNAME, RABBITMQ_PASSWORD) CELERY_DEFAULT_QUEUE = 'default' CELERY_DEFAULT_EXCHANGE = 'default' CELERY_DEFAULT_ROUTING_KEY = 'default' CELERY_IGNORE_RESULT = True CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery_enable_utc=True import djcelery djcelery.setup_loader() -
Create a container object, then add an image object into that container object after it has been created
form_image_container = ImageContainerForm(request.POST or None, request.FILES or None) if form_image_container.is_valid(): instance_container = form_image_container.save(commit=False) instance_container.user = request.user instance_container.save() return redirect(# redirect to the recently created canvas page) # somehow need to create image container first, then add the a image into the image container form_image = ImageForm(request.POST or None, request.FILES or None) if form_image.is_valid(): instance_image = form_image.save(commit=False) instance_image.user = request.user instance_image.image_container = instance_container instance_image.image = obj.image instance_image.save() Is there a way to create the first object (container for images) and then add the second object (image) into the first (container for images) -
Nginx (I think) saves files with wrong permissions when request is too large
So, I'm completely new to hosting and Linux and all, so please forgive me if I'm saying things that are wrong. I'm still learning :) I'm working a small personal website created using Django. I wanted to get it online to see if everything would work. I got a cheap server from linode and using a guide from Digital-Ocean (the irony) I got everything working. I was happy. But... There's one major problem and I've read half the internet and can't find any similar problems: when the post request is larger than ~4MB (uploading images etc.) the files are being saved with the wrong permissions. When the request size is smaller than about 4MB, everything works without a single problem. When the request size is bigger, everything gets uploaded and saved to the server without a single problem, but from there on I can't access the files from the browser anymore and the site keeps throwing 403 forbidden on those files. That's because the files are suddenly saved with wrong permissions or something like that. Permissions of a forbidden file: -rw------- 1 merlijn root 7900880 May 12 08:24 filename1.pdf Permissions of a working file: -rw-r--r-- 1 merlijn root 207420 May … -
Django Rest Framework Response is not JSON serializable error
I have the following custom exception handler in Django REST framework. class ErrorMessage: def __init__(self, message): self.message = message def insta_exception_handler(exc, context): response = {} if isinstance(exc, ValidationError): response['success'] = False response['data'] = ErrorMessage("Validation error") return Response(response) I want a JSON output as shown below "success":false, "data":{ "message" : "Validation error" } But I get the error TypeError: Object of type 'ErrorMessage' is not JSON serializable. Why is a class as simple as ErrorMessage above not JSON serializable? How can I solve this problem? -
Django feature (custom method from admin) missing: why, security?
A feature I have been missing several times is a simple way to create a button in the model detail view in the admin, which triggers some custom method of the model. I have searched thoroughly, I hope, so I'm pretty sure it's not available to do this easily. There are admin-actions, but only for the list view (and they require special methods), there is the possibility to provide a custom ModelForm, and maybe more: but why nothing easy. Like by creating a ButtonField (this is my invention) in the ModelAdmin. I think it really would be a common use-case! Should I file a feature request/try to write this feature myself? Or is there a reason why this shouldn't be implemented? -
What is the Current Web Development languages in trend 2017?
i am in doubt, which language to study next. python and django or ruby and ruby on rails. which one does the companies use currently 2017 and which one do they suggest. -
How to release the occupied GPU memory when calling keras model by Apache mod_wsgi django?
My server configuration is as follows: apache 2.4.23. Mod_wsgi 4.5.9 By using the Django framework and apache server, we call the Keras deep learning model. And after the successful calling of the model, the model has been always running in the GPU memory, which causes the GPU memory can not be released except by shutting down the apache server. So, is there any way to control the release of GPU memory when calling a Keras model by Apache+Mod_wsgi+Django? Thanks! Runtime memory footprint screenshots -
Django unable to connect to postgres database through
I am trying to provision a server with a django applciation with postgresql as its backend. After installing the required packages, database and environment when I try to run migrations, I get the following error Traceback (most recent call last): File "/var/envs/traveldbapi/lib/python3.4/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/var/envs/traveldbapi/lib/python3.4/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/var/envs/traveldbapi/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/var/envs/traveldbapi/lib/python3.4/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/envs/traveldbapi/lib/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() ==== ommitting some lines ==== connection = Database.connect(**conn_params) File "/var/envs/traveldbapi/lib/python3.4/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: fe_sendauth: no password supplied I confirmed that the relevant DATABASE setting required for django are present: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': DATABASE_NAME, 'USER': DATABASE_USER, 'password': DATABASE_PASSWORD } } I am not sure why this error is happening because this is the same setup I use on my local machine and it works. To confirm that there aren't any issues with my pg_hba.conf I started … -
TypeError while returning Response from django view
I've been trying to create a view for the url pattern Urls.py url(r'^task/', include('app.urls')), Urls.py inside app.urls url(r'^(?P<task_id>[0-9]+)/$', views.task, name='task'), Which can be accessed by /task/:task_id. My corresponding view for task is def task(request, task_id): obj = Task.objects.get(pk=task_id) return HttpRequest("You're looking at a %s Task." % obj.type) The corresponding model for Task is this. class Task(models.Model): image = models.ImageField(upload_to='tasks') description = models.CharField(max_length=500) language = models.CharField(max_length=7, default='en', choices=LANGUAGES) type = models.CharField(max_length=20, default='Transliteration', choices=TASK_TYPES) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.language + ' ' + self.description I am successfully able to debug the task_id and obj values which exist but my webpage returns the following error. TypeError at /task/1/ __init__() takes exactly 1 argument (2 given) How can such an error be fixed? -
How to save two forms in one view with a foreignkey relationship?
I have the following models with foreignkey relation. class UserProfile(models.Model): profile_id = models.CharField( ('Profile id'), max_length=30, default='', blank=True) first_name = models.CharField( ('first name'), max_length=30, default='', blank=True) last_name = models.CharField( ('last name'), default='', max_length=30, blank=True) Profile Image model has a foreignkey relation to UserProfile model: class UserProfileImage(models.Model): userprofile = models.ForeignKey(UserProfile) image = models.ImageField(upload_to='profile_pic/images',blank=True,null=True) def __unicode__(self): return self.userprofile.profile_id I want to save both forms in one view and for edit also it should pass both form instances.How will I save both forms in one view? -
range(1,1) is not processed by loop
I was trying to loop product's quantity: {% for the_number in one_product.product_stock_range %} {% if the_number == one_product.quantity %} <option value="{{ the_number }}" selected="selected">{{ the_number }}</option> {% else %} <option value="{{ the_number }}">{{ the_number }}</option> {% endif %} {% endfor %} now i am using 'product_stock_range' : range(1, product_stock), but sometimes, some product's stock is only 1. The loop will not run, how to i solve this issue? how do i force the loop to run even when it's only one-time loop? -
Django UpdateView and code trimming
While asking questions to build a view that would allow me to edit a users profile I was numerously recommended to use Django's UpdateView, however I have been unsuccessful in converting what I have now into a working UpdateView. # urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^profile/(?P<username>\w+)/$', views.profile, name='profile'), url(r'^profile/(?P<username>\w+)/edit/$', views.EditProfileFormView.as_view(), name='edit-profile'), ] # views.py class EditProfileFormView(View): form_class = EditProfileForm model = Profile template_name = 'forums/edit-profile.html' def get(self, request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404('The User "' + username + '" could not be found.') if (not request.user.is_authenticated): return HttpResponseForbidden() elif (user.id is not request.user.id): return HttpResponseForbidden() form = self.form_class(instance=user.profile) return render(request, self.template_name, {'form': form}) def post(self, request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404('The User "' + username + '" could not be found.') if (not request.user.is_authenticated): return HttpResponseForbidden() elif (user.id is not request.user.id): return HttpResponseForbidden() form = self.form_class(request.POST) if (form.is_valid()): # This needs to update the changed form profile = form.save(commit=False) # clean (normalized) data profile.save() if (user.is_active): return redirect('/profile/' + user.username) return render(request, self.template_name, {'form': form}) Also under the get and post methods I have the same code twice to validate the user who is editing the profile. Is there any … -
Django-admin is not working Django 1.11 Python 3.6
I tried to research on all related topics here and googled it but the django-admin command is not doing anything whenever I type it in CMD (win 7). It only opens my pycharm and shows codes inside the django-admin.py. I already added it to environment variables and tried these syntax but didn't work (I was able to create and run virtual environment): version1: django-admin startproject mysite version2: django-admin.py startproject mysite version3: path-to-django-admin\django-admin.py startproject mysite I even tried to copy the django-admin.py on my project folder but didn't do any good. -
What the page number with user
In the frontend I have map with pins (all profiles) and list of profiles (with pagination). Idea is to get the needed page (and then render it) with user, which had been chosen from the map pin. So I think it will be great, if anyone knows how can get the link with page with this user from Django Rest Framework. Can it be some filtering stuff? -
Trigger receiver signal on Proxy model
I'm using a proxy model, so that I can use Elastic search on the same model using two different serialisers. However, the new_index_elastic function never runs (ie I never see the print, and my NewModel never gets indexed). How would I do this? class Item(EsIndexable, models.Model): title = models.CharField( blank=True) tag = models.ManyToManyField('Tag', blank=True) class Elasticsearch(EsIndexable.Elasticsearch): serializer_class = ItemEsSerializer fields = ['title', 'tag'] @receiver(post_save, sender= Item) def index_elastic(instance, **kwargs): instance.es.do_index() class Newmodel(Item): class Meta: proxy = True class Elasticsearch(EsIndexable.Elasticsearch): serializer_class = NewModelEsSerializer fields = ['title', 'tag'] @receiver(post_save, sender= Newmodel) def new_index_elastic(instance, **kwargs): print('Index proxy') instance.es.do_index() -
Django saving updated database values from form
I am trying to allow a user to edit their profile. In the post method I want to save the new data over the old data in the same row. # Post method of class view in views.py def post(self, request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404('The User "' + username + '" could not be found.') if (not request.user.is_authenticated): return HttpResponseForbidden() elif (user.id is not request.user.id): return HttpResponseForbidden() form = self.form_class(request.POST) if (form.is_valid()): # creates a new user object, does not save to the database yet profile = form.save(commit=False) # clean (normalized) data # ... profile.save() if (user.is_active): return redirect('/profile/' + user.username) return render(request, self.template_name, {'form': form, 'error_message': 'Oops, something went wrong'}) This code I believe is creating a new database row when the post method is called. How do I get it to update the existing row in a clean looking solution? -
pass data from Django view to react
I have a django view that returns a variable in order to be rendered in template return render_to_response('index.html', { 'courses': courses}) I'm using ReactJS to render the index.html file, but I'm not sure whether i have to point to index.html in my view or the ReactJS file. If I have to point to index.html how can I use the courses variable with React ? -
I can't update the Model instance while Testing
I'm testing a CBV on Update and each time the model instance can't seems to update. console output > self.assertEqual(product.showoff, data['showoff']) E AssertionError: 'uMsvXoRJbwFeieMvoCmR' != 'showoff 33333' E - uMsvXoRJbwFeieMvoCmR E + showoff 33333 views.py class ProductUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Product form_class = ProductForm template_name = "mainapp/product_update.html" success_message = 'Successfully Updated a Product entry' def dispatch(self, *args, **kwargs): return super(self.__class__, self).dispatch(self.request, *args, **kwargs) def form_valid(self, form): self.object = form.save(commit=False) #migh need to remove that line #self.object.author = self.request.user return super(self.__class__, self).form_valid(form) product_update = login_required(ProductUpdateView.as_view()) tests.py def test_ProductUpdateView_should_update_the_product_content(self): #Delete all Products Product.objects.all().delete() #Create user (fixture) user = mixer.blend('auth.User', is_superuser=True) #create a Product (fixture) product = mixer.blend('mainapp.Product') #Fields to update data = dict( showoff='showoff 33333', ) #Preparing to post to the Update url url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk}) request = RequestFactory().post(url, data=data) #assign a user request.user = user #Post to Update URL response = views.ProductUpdateView.as_view()(request, pk=product.pk) #Assertion: status code self.assertEqual(response.status_code, 200) #Refresh the db and Get the latest Product product.refresh_from_db() product = Product.objects.get(pk=product.pk) #pytest.set_trace() #Assertion self.assertEqual(product.showoff, data['showoff']) -
Django TypeError in render() call once uploaded to server
I have a website I'm updating to the latest Django, a point release at a time. Right now I'm on Django 1.9.13 and Python 2.7.5, and I have code that works fine with manage.py runserver on my local dev machine, but when I run it to my web host (WebFaction), it fails with this error: TypeError at / init() takes exactly 3 arguments (2 given) Here's the traceback: File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bobtiki/webapps/optical_green/cinedex/theoptical/views.py" in frontpage 38. return render(request, 'theoptical/frontpage.html', context) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/shortcuts.py" in render 67. template_name, context, request=request, using=using) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 96. template = get_template(template_name, using=using) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/loader.py" in get_template 32. return engine.get_template(template_name, dirs) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/backends/django.py" in get_template 40. return Template(self.engine.get_template(template_name, dirs), self) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/engine.py" in get_template 190. template, origin = self.find_template(template_name, dirs) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/engine.py" in find_template 153. for loader in self.template_loaders: File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 33. res = instance.__dict__[self.name] = self.func(instance) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/engine.py" in template_loaders 118. return self.get_template_loaders(self.loaders) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/engine.py" in get_template_loaders 123. loader = self.find_template_loader(template_loader) File "/home/bobtiki/.virtualenvs/optical_green/lib/python2.7/site-packages/django/template/engine.py" in find_template_loader 146. return loader_class(*args) Exception Type: TypeError at / Exception Value: __init__() takes exactly 3 arguments (2 given) Here's cinedex/theoptical/views.py in frontpage: … -
Call view function with empty request object
I am trying to call a view function to test something in my application like so: >>> from ingest.views import search_site >>> request={'search_string':'billy','search_type':'title'} >>> search_site(request) AttributeError: 'dict' object has no attribute 'GET' How do I create an empty request objcect, such as the above that I can test a view function with? -
Django Channels no errors in runserver but no page on localhost
I am trying to set up Django channels in an existing Django project, having never used them before. I am following this guide if that helps. You can see below what I get when I runserver, however going to 127.0.0.1:8000 just gives me a message corrupt, page couldn't be loaded error. Because I am new to the concept of channels there is a good chance I have missed something in the setup. pi@raspberrypi:~/o2ta_swdev_pie/o2ta_web $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). May 11, 2017 - 23:30:18 Django version 1.10.4, using settings 'o2ta_web.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgiref.inmemory.ChannelLayer) Quit the server with CONTROL-C. 2017-05-11 23:30:18,744 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-05-11 23:30:18,748 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-05-11 23:30:18,750 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-05-11 23:30:18,753 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.receive 2017-05-11 23:30:18,796 - INFO - server - Using busy-loop synchronous mode on channel layer I have installed dependencies according to this requirements.txt: # requirements.txt asgi-redis==1.0.0 channels==0.17.3 daphne==0.15.0 Django==1.10.4 And have added consumers.py, routing.py and altered …