Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Supervisor reload as user
I installed Supervisor via... sudo apt-get install supervisor When I deploy my app with Capistrano, I need to run Supervisor as a none root user. If I run... /usr/bin/supervisorctl reload I get... Permission denied: file: /usr/lib/python2.7/socket.py If I run above command with sudo it works fine, but I need to run it without sudo. Is this possible? I tried changing the group and owner of Supervisor to the user running the command, but that didn't work. -
500 error when Debug=False with Heroku and Django
I am getting a funny 500 error when I switch to Debug=False in my Heroku app when I deploy. I have set Debug=True when I deploy just to try it out and it works perfectly - so the issue is only when Debug is set to False. I'm not sure where to start here. Some searching has led me to believe it's whitenoise causing the issue but it's not clear. The command: heroku logs --tail isn't giving me any useful information. method=GET path="/" host=penguiness.herokuapp.com request_id=c6cd8776-0c3f-40ac-9993-7a8c9fa1b491 fwd="86.185.175.116" dyno=web.1 connect=0ms service=2258ms status=500 bytes=234 protocol=http I have tried fixing as per this solution but to no avail; See below for my settings: import os import posixpath from os import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'A SECRET' DEBUG = True ALLOWED_HOSTS = ['*'] SITE_TITLE = "Penguiness" SITE_TAGLINE = "Amazing records for amazing species" # Application definition INSTALLED_APPS = [ 'app', # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'compressor', 'gunicorn' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', … -
Join more than 2 tables in Django
I am trying to create a new endpoint that would return a joined result of 3 tables (without having the model class) The 3 models that I am trying to join are: User, Institution and Site I have defined my own serializer as follows: class DashboardSerializer(serializers.Serializer): id = serializers.CharField(read_only=True) email = serializers.CharField() first_name = serializers.CharField() last_name = serializers.CharField() full_address = serializers.CharField() country = serializers.CharField() status = serializers.CharField() role = serializers.CharField() date_joined = serializers.DateTimeField() institution_id = serializers.CharField() site_id = serializers.CharField() site_name = serializers.CharField() def create(self, validated_data): pass def update(self, instance, validated_data): pass and the view set: class DashboardViewSet(viewsets.ModelViewSet): queryset = User.objects.all().select_related('institution_id').select_related('site_id') serializer_class = DashboardSerializer @api_view(['GET']) def get(self, request): if request.method == 'GET': users = User.objects.all().select_related('institution_id').select_related('site_id') serializer = DashboardSerializer(users, many=True) return JsonResponse(serializer.data, safe=False) The problem is that when hitting the endpoint I get: Invalid field name(s) given in select_related: 'institution_id', 'site_id'. Choices are: institution I am not sure if this is a problem with the query, serializer or even both. Any help would be greatly appreciated. -
How to log a user in by getting data from an API?
I am writing an API view where am accessing API to POST email and password to the address and fetch response.So i want if response is 200 or repose message is 'Success' then to login with available email and password datas, but i'm not able to do so. How to achieve such? class ApiLoginView(TemplateView): template_name = 'index.html' def post(self,request): email = request.POST.get('login-email') print(email) password = request.POST.get('login-password') print(password) API_KEY = '*********************' API_URL = 'http://devstudio.com/rest/storeLogin' parameter = { 'authToken':API_KEY, 'email':email, 'password':password, } r = session.post(url = API_URL, params=parameter) return HttpResponse(r) -
Wierd StaticCompilationError caused by django-static-precompiler
On project we use django-static-precompiler and scss. When I ran localy got this weird error that points to nothing literally. No info at internet or references at docs. I thought it connected to sass packecge but it already installed at my system. OR -
django.db.utils.ProgrammingError: (1146 table doesn't exist)
I have an problem with migrations in python django. When i try to execute python manage.py makemigrations or migrate there is this error.🤷♂️ django.db.utils.ProgrammingError: (1146, "Table 'rc2.eduuser_role' doesn't exist") Code: from django.db import models from django.utils.translation import gettext_lazy as _ from settings import base from eduuser.managers import EduUserManager from phonenumber_field.modelfields import PhoneNumberField # ** AUTH USER ** from django.contrib.auth.models import ( AbstractBaseUser,PermissionsMixin ) # ------------ # ROLE # ------------ class Role(models.Model): name = models.CharField( _("Role Name"), max_length=100, unique=True, ) def __str__(self): return self.name # ------------- # EduUser # ------------- class EduUser(AbstractBaseUser,PermissionsMixin): objects = EduUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] first_name = models.CharField( _("First Name"), default="", blank=False, max_length=255) last_name = models.CharField( _("Last Name"), default = "", blank=False, max_length=255) eduId = models.CharField( _("EduId"), blank=False, unique=True, db_index=True, error_messages={ 'unique': _("A user with that eduId already exists."), }, max_length=255) age = models.IntegerField( _("Age"), blank=True, null=True, ) GENDER_CHOICES = ( ('N', 'None'), ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField( _("Gender"), max_length=1, choices=GENDER_CHOICES) email = models.EmailField( _("Email"), max_length=255, unique=True, error_messages={ 'unique': _("A user with that email address already exists."), }, ) verify_key = models.IntegerField(blank=True, null=True) verify_key_expires = models.DateTimeField(blank=True, null=True) email_verify = models.BooleanField(default=False) password_forgot_key = models.CharField( _("Password_Forgot_Key"), blank=True, unique=True, max_length=255) password_forgot_key_expires = models.DateTimeField(blank=True, null=True) health_info … -
Trying to save image file from ajax to django rest framework but not working
I'm trying to figure out how to save an image file from ajax(jquery) to DRF with an ImageField. Right now I can save TextField only. I'm trying to build a product registration page with uploading an image. Is anybody here experiencing this also? I'm kinda learning django + django restframework and came up to create a challenge project to so that i can push my self and experience what future problems will i be dealing. Here is my script code calling ajax: <script> $(function(){ $('#registerButton').click(function() { console.log("CLICK"); var itemname = $('#input-itemname').val(); var barcode = $('#input-barcode').val(); var qty = $('#input-qty').val(); var desc = $('#input-desc').val(); var pricing = $('#input-pricing').val(); var thumbnail = $('#input-thumb').val(); var myFile = $('#input-file').prop('files')[0]; $.ajax({ url: "http://localhost:8000/apihelper/productitems/", method: "POST", data: { product_name: itemname, product_description:desc, product_barcode:barcode, product_qty:qty, product_srp: pricing, product_thumbnail:thumbnail, product_image : myFile, // csrfmiddlewaretoken: g_csrftoken } }).done(function(data) { console.log("DONE: ", data); }).fail(function(data) { console.log("FAIL", data); }); }); }); </script> My View.py @csrf_exempt def showmaterial(request): storage = StorageItems.objects.all() return render(request,'designs/material.html',{'listItem':storage}) Here is my apihelper views.py class StorageItemsViewSet(viewsets.ModelViewSet): serializer_class = serializers.StorageItemsSerializer # authentication_classes = (TokenAuthentication,) queryset = models.StorageItems.objects.all() # permission_classes = (permissions.PostOwnMessage,IsAuthenticated,) # permission_classes = (IsAuthenticated,) def perform_create(self,serializer): print ("HERE PERFORM_CREATE") # """Sets the alarm message to the logged in user""" … -
django dynamic form save data
thanks for reading this post and offering help to me. I am new to Django and I am working on a website for aboriginal regions to record their lives. Users can create a page and publish contents. Before they create a page, they need to specify the number of seasons that they want to record. The website will base on the number of seasons to dynamically create textfields. Currently, I can dynamically create textfields, but I have problems saving the data. I spent a long time trying to solve this issue but still stuck at here. The mistake I got is 'SeasonalTextForm' object has no attribute 'instance'. article that I am following when I implemented the dynamic form: 1 https://jacobian.org/writing/dynamic-form-generation/ [2] https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/ Here is the error message(the image can only attach as a link): Attribute Error: 'SeasonalTextForm' object has no attribute 'instance' Here is my model.py class PageComponent(models.Model): componentName=models.CharField(max_length=50,null=True, verbose_name="Name") type = models.ForeignKey(Type, on_delete=models.CASCADE) user = models.ForeignKey(AS_User, on_delete=models.CASCADE, editable=False) page = models.ForeignKey(CommunityPage, on_delete=models.CASCADE, editable=False) STATUS = ( ('a', 'Activated'), ('d', 'Deactivated'), ) componentStatus=models.CharField( max_length=1, choices=STATUS, blank=False, default='d', help_text='the current status of the page component', editable=False ) textContent=models.TextField(max_length=10000, help_text="Enter a description for your component", null=True, blank=True) photoContent=models.ImageField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Photo") # … -
collectstatic incorrectly creates multiple CSS files in S3
I have uploading files to S3 working fine with my Wagtail/django application (both static and uploads). Now I'm trying to use ManifestStaticFilesStorage to enable cache busting. The urls are correctly being generated by the application and files are being copied with hashes to S3. But each time I run collectstatic some files get copied twice to S3 - each with a different hash. So far the issue is ocurring for all CSS files. file.a.css is loaded by the application and is the file referenced in staticfiles.json - however it is a 20.0B file in S3 (should be 6.3KB). file.b.css has the correct contents in S3 - however it does NOT appear in the output generated by collectstatic. # custom_storages.py from django.conf import settings from django.contrib.staticfiles.storage import ManifestFilesMixin from storages.backends.s3boto import S3BotoStorage class CachedS3Storage(ManifestFilesMixin, S3BotoStorage): pass class StaticStorage(CachedS3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION file_overwrite = False Deps: "boto==2.47.0", "boto3==1.4.4", "django-storages==1.5.2" "Django==2.0.8" Any pointers on where to look to track down this issue would be appreciated! :) -
Django Serializer: How can I validate a modal object?
I'm pretty new to Django Serializers and still confused on how they work. I have a fairly general scenario wherein I'm calling my api which simply sets a field in my modal object and saves it (assume the record is already present and it is just being updated). However, I need to validate this modal object before saving it. api.py @detail_route(methods=['POST'], url_path='submit-draft') def submit_draft(self, request, *args, **kwargs): booking = self.get_object() // serializer with custom validations. serializer = self.get_serializer(booking) serializer.is_valid(raise_exception=True) booking.submit_draft(by=request.user) booking.save() data = serializers.BookingDetailSerializer(booking, context={'request': request}).data return response.Ok(data) serializers.py class BookingCreateUpdateSerializer(serializers.ModelSerializer): date = serializers.CharField() duration = serializers.IntegerField(required=True, ) created_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault(), ) modified_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault(), ) .... class Meta: model = models.Booking fields = [ 'title', 'date', 'duration', 'client', 'created_by', 'modified_by', .... ] However, I get this error: AssertionError: Cannot call '.is_valid()' as no 'data=' keyword argument was passed when instantiating the serializer instance. I understand that the serializer is expecting a dictionary rather than the actual modal object. But I can't figure out how to achieve what I want to ie. validate a modal object. Can anyone please suggest the right approach? -
Return response to client after asynchronous celery task finishes
I have a Django view that gets an AJAX request from the client and runs a long operation (30 - 60 seconds). This view calls a lambda functions several times asynchronously to process data given by the client in parallel. An example: import multiprocessing as mpi def myView(request): data = request.POST.get('data') processedData = [] pool = mpi.Pool() for chunk in data: processedData.append(pool.apply_async(call_AWSLambda,args=(chunk,))) pool.close() pool.join() # Blocking do_some_stuff(processedData) return HttpResponse({'success':True}, content_type='application/json') While this is taking place, the client sees a loading gif which blocks its GUI to further send more request. I like to have the client waiting so that he does not send a lot of requests. With this approach, while AWS lambda is computing, my server is waiting so it is taking some resources. I am wondering if there is a ways to run this task in parallel with celery to free up the server (e.g. something like apply_async) but keep the client waiting (so not returning the response {'success':True}) until the task finishes. On the other hand, since the heavy lifting is done by the lambda functions, the resources taken on the server while waiting for AWS to finish are minimal so I can have many users calling … -
Django; How to test views with django allauth
I'm trying to test views in Django project. Testing views doesn't work well because I'm using allauth. def test_add_entry(self): response = self.client.get(reverse('blog:add_entry')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/entry_form.html') Because the views set @login_required decorator, the client is redirected to other page. Also, login() doesn't work. How can I set user that logged in using allauth? -
Asynchronous HTTP call inside HTTP cycle of Django Rest Framework
I need to call external service on the get_queryset function of one of my viewsets on views.py, but I don't need to wait for the response of external function. How can I make the following requests.post line just triggered and passed to next line without waiting for the result? class SomeViewSet(viewsets.ModelViewSet): def get_queryset(self): .... requests.post(urlOfApi+token) ..... return Some.objects.all() -
Is This a Correct way of writing a project in django?
https://github.com/kvhnbasca/s This is the project. I have made a small project on ATM. 1)user can log in with his username and password.(users present in database) 2)A homepage will appear with *view balance *depoit money *withdraw money *mini statement *change pin 3)So all thse operations can be performed This project has been completed by me.I am a beginner in django and i want to know that is this the correct way of writing code in django or not.Some of my friends are saying that ur code is very simple and u have not used django at all in this project and used wrong way of writing django. Is this true?Please help me ,look at my code https://github.com/kvhnbasca/s And please give me suggestions for where to improve in my code.Thanks -
Solution to two problems
I need to check for a number of conditions and do a filter OR search if the conditions are specified. I am doing it as below: def or_q_if_truthfull(**kwargs): filtered = [Q(**{k: v}) for k, v in kwargs.items() if v] if filtered: return reduce(or_,filtered) else: return Q() def check(): if age.isdigit(): my_q = or_q_if_truthfull( name__lower__contains=name.lower(), age=age, mobile__contains=phone, email__lower__contains=email.lower(), address__lower__contains=address.lower(), city__lower__contains=city.lower(), ) else: my_q = or_q_if_truthfull( name__lower__contains=name.lower(), mobile__contains=phone, email__lower__contains=email.lower(), address__lower__contains=address.lower(), city__lower__contains=city.lower(), ) I tried to combine the if and else into one block: Problem 1: my_q = or_q_if_truthfull( name__lower__contains=name.lower(), age=age if age.isdigit(), mobile__contains=mobile, alternate__contains=alternate, email__lower__contains=email.lower() if email else email, address__lower__contains=address.lower(), city__lower__contains=city.lower(), ) but that's not working for age if Nonetype Then I tried this: Problem 2: from numbers import Number my_q = or_q_if_truthfull( cstid=HospitalID, name__lower__contains=name.lower() if name else name, age=age if isinstance(age, Number), mobile__contains=mobile, alternate__contains=alternate, email__lower__contains=email.lower() if email else email, address__lower__contains=address.lower(), city__lower__contains=city.lower(), ) File "/home/joel/myappointments/clinic/views.py", line 97 age=age if isinstance(age, Number), ^ SyntaxError: invalid syntax What's the issue in the two problems above? -
jQuery AJAX response Split
I have written an ajax call to call an API for post data and fetch after success response and show it in div tag of my respective form, but it gives me complete json {"code":200,"status":"OK","msg":"Login Success"}, But i just want to show 'msg' part. How can i achieve this? I am doing this on django template. i tried to do res['msg'](python key,value stuff) but its not working <script> $(document).ready(function(){ var myForm = $('.my-login-form') myForm.submit(function(e){ e.preventDefault() console.log('hi') var formData = $(this).serialize() $.ajax({ method: "POST", url: '/login', data: formData, success: function(res) { $('#login-data').html(res); }, }) }) }) </script> <form class="my-login-form" action="/login" method="post"> {% csrf_token %} <div id="login-data"></div> <div class="field-wrap"> <input type="email" name="login-email" required autocomplete="off" placeholder="Email Id"/> </div> <div class="field-wrap"> <input type="password" name="login-password" required autocomplete="off" placeholder="Password"> </div> <button class="button button-block"/>Login</button> <div class="forgot"><a class="user-form-toggle" href="#forgot">Forgot Password?</a></div> </form> -
How to integrate Tally ERP system with Django based backend?
I am trying to make an application, with Django as the backend. I would like to fetch data from Tally ERP system on my backend. 1. How can I do it? 2. Is there any documentation for their APIs? -
Django Countries storing unnecessary data when saved
I have the following model in my system that has CountryField(multiple=True) class Company(models.Model): name = models.CharField("Name", max_length=50) sites = CountryField(multiple=True, default='SG', blank_label='(Select Country)') uuid = models.CharField('fi_uuid', max_length=255, blank=True, null=True) def save(self, *args, **kwargs): if not self.id: self.uuid = shortuuid.uuid() super(Company, self).save(*args, **kwargs) In my views.py comp, created = Company.objects.get_or_create(name=company_cell) comp.save() When comp.save() is being executed, these are the weird data that is stored in the field 'sites'. [Country(code=u'[Country(code=u\'[Country(code=u"[Country(code=u\\\'SG\\\')]")]\')]')] I also tried putting this before comp.save(): comp.sites = 'SG' This is the data that comes out instead: [Country(code=u'SG')] And when I check my django admin in both cases, this is what I saw As you noticed in both cases, the option 'Singapore' is not being selected. So I have two questions to ask: Is there any reason why "sites" has data already being filled up even though there does not seem to be any code for that? How do I make sure "sites" by default already stores 'SG' instead of those weird data? Additional note: I am using django-countries==5.3.2 Thanks in advance. -
Django - login - redirect to specific url only when logged in from homepage
There are two scenarios of user log in: Log in from homepage Session expired, and user was logged out. User was forced to re-log in to stay in the current page (@login_required decorator is used) With the use of @login_required decorator, if I don't specify LOGIN_REDIRECT_URL in settings.py, if the user is logged off due to session expiration and logged back in, it will redirected back to its current page, like this: http://127.0.0.1:8000/?next=/my-current-url-page/ This is a very nice feature, and I would like to stick to it, but if I am in Scenario 1, it will be redirected to: http://127.0.0.1:8000/accounts/profile/ I want to specify redirect url only when the user is logging in from home page. How can I set an exception for in which the user is logging in from home page? urls.py # this renders the home page re_path('^$', auth_views.login, {'template_name': 'login.html'}, name='login'), # this renders the other pages path('well_list/', decorator_include(login_required, [ re_path(....), re_path(....), ])) FYI, decorator_include is a code snippet that allows you to apply decorator for url patterns with include(). -
How path is equivalent to url in django 2.0 in terms of wild card characters?
I am trying to learn Django. However, that tutorial is using url() function inside url.py rather than path. I was checking documentation about path() but I am a bit confused. Like, what is the equivalent of raw string search for url(r'^admin/$', 'views.about') in path like how ^ and $ wild card characters are mapped in the path() function. -
Django; template that render the response is template that is used for 404 error
I'm trying to test views in Django. The template that render the response always becomes the template that is used for 404 error. def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/index.html') This test was successful. But, def test_list_entry(self): response = self.client.get('/blog/list/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/list_entry.html') This test failed. The error says the template that render the response is 404.html. urlpatterns is like this urlpatterns = [ path('', views.index, name='index'), path('blog/', include([ path('list', views.list_entry, name='list_entry'), What am I wrong with this? -
DJango: how to get Dynamically created div id
I have created the div in a for loop on the basis of data. I want to make the div clickable ,So whenever I click any div it will show the detail of that content in another block.. {% for message in list_of_data %} {{ message.user.time }} {{ message.user.display_name }} {{ message.text|slice:":50"}} {% if message.source == "GooglePlus" %} https://plus.google.com/{{ message.user.user_id }}/posts/{{ message.status_id }} {% elif message.source == "Twitter" %} https://twitter.com/{{ message.user.display_name }}/status/{{ message.status_id }} {% endif %} {% endfor %} -
heroku application error becaouse of gevent
when I try to push to Heroku its deploys correctly but shows application error. no updates are possible , log of heroku is following 2018-09-13T04:54:13.237927+00:00 app[web.1]: import gevent 2018-09-13T04:54:13.237928+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gevent/init.py", line 41, in 2018-09-13T04:54:13.237930+00:00 app[web.1]: from gevent.hub import get_hub, iwait, wait 2018-09-13T04:54:13.237931+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gevent/hub.py", line 289 2018-09-13T04:54:13.237932+00:00 app[web.1]: except Exception, ex: 2018-09-13T04:54:13.237933+00:00 app[web.1]: ^ 2018-09-13T04:54:13.237934+00:00 app[web.1]: SyntaxError: invalid syntax 2018-09-13T04:54:13.237936+00:00 app[web.1]: ] 2018-09-13T04:54:13.237944+00:00 app[web.1]: -
Multifield Form that have the same script
I want to code the smart filter that can add more filter choice that can show/hide input relate on the select option value (like : http://lumen.codekerala.com/payments) I use the jQuery Multifield Plugin (https://github.com/maxkostinevich/jquery-multifield) It just clone the html but the script to use with it doesn't work , I think it cannot use together (Maybe It might create new script for the new field when I click "Add More Filter") I have no Idea to Fix it, Plz help T^T -
How to run Django Web app on port 443 and 80 linux - Ubuntu or Raspberry PI?
I am pretty new to Django. I think I cannot run django application as sudo since all pip related modules are installed for the user and not for the sudo user. So, it's a kind of basic question like how do I run django app that can listen for port 80 as well as port 443. So, far I have tried following option - i.e pre-routing - NAT I run my app using the following command - $python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 15 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. September 13, 2018 - 03:04:41 Django version 2.1.1, using settings 'WebBlogger.settings' Starting development server at http://127.0.0.1:8000/ Next, here is my iptables settings nothing worked for me though sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 $sudo iptables -t nat --line-numbers -n -L Chain PREROUTING (policy ACCEPT) num target prot opt source destination 1 DOCKER all -- 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL 2 REDIRECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 redir ports 8000 Chain INPUT …