Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return model objects with JSON field
Lets say I want to get all the objects from a Model where one of it's field is JSON stored as string So the object will look something like this after serializated from the model: [{ "model": "Book", "pk": 1, "fields" :{ "title": 'Book 1', "content": "{ "content1": "abc", "content2": "def" }" }, "model": "Book", "pk": 2, "fields" :{ "title": 'Book 2', "content": "{ "content1": "123", "content2": "456" }" }, }] objList = serializers.serialize('json', Books.objects.all() context = { 'objList': objList } return render(request, template, context) Are there any way to make sure the content field to be returned as JSON? Tried use {{objList|safe}} but that doesn't makes the content field to be JSON. The content field returned as string when I use it in the javascript. -
object of type 'NoneType' has no len() :
def send_ivr_calls(sp_orders, base_url, api_key, extra_data): for contact in sp_orders: if len(contact) == 10: contact = '0'+contact File "views.py", line 43, in calls if len(contact) == 10: TypeError: object of type 'NoneType' has no len() object of type 'NoneType' has no len() How can I check whether the sp_orders list does not contain any Nones? -
How to get the challenger using DjangoSimpleCaptcha
I'm trying to use Ajax to check the correctness of input captcha code, CaptchaStore.generate_key() to generate a key and an image: hashkey = CaptchaStore.generate_key() image_url = captcha_image_url(hashkey) return render(request, 'registe.html', { 'hashkey':hashkey, 'image_url':image_url, }) And in my template, I use a text field to test the correctness by Ajax: <div class="input_contain"> <label class="input_label">Captcha</label> <input class="text_input" type="text" onchange="captcha(this.value, {{ csrf_token }})"> <img id="image_url" src="{{ image_url }}" class="captcha"> <input id="hashkey" type="hidden" value="{{ hashkey }}"> <input id="csrf" type="hidden" value="{{ csrf_token }}"> <span id="result"></span> </div> I want to use Ajax to pass the input value and test in views, but I don't know how to get the captcha's challenger, so, how? -
How backward relation works with Django query set
I have below models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class IndustryCat1(models.Model): name = models.CharField(max_length=256) class Meta: managed = False db_table = 'industry_cat_1' class IndustryCat2(models.Model): name = models.CharField(max_length=256) num = models.CharField(max_length=10) label = models.CharField(max_length=200) industry_cat_1_id = models.ForeignKey('IndustryCat1') class Meta: managed = False db_table = 'industry_cat_2' class IndustryCat3(models.Model): name = models.CharField(max_length=256) num = models.CharField(max_length=10) label = models.CharField(max_length=200) industry_cat_2_id = models.ForeignKey('IndustryCat2', blank=True, null=True, related_name='industry_cat_2_id') class Meta: managed = False db_table = 'Industry_cat_3' class IndustryCat4(models.Model): name = models.CharField(max_length=256) num = models.CharField(max_length=10) label = models.CharField(max_length=200) industry_cat_3_id = models.ForeignKey('IndustryCat3', blank=True, null=True, related_name='industry_cat_3_id') class Meta: managed = False db_table = 'Industry_cat_4' This is the file where I am writing queries: industries.py: from demo.models import IndustryCat1, IndustryCat2 import datetime from django.db.models import Q class Industries: @staticmethod def getIndustries(indId): try: b = IndustryCat1.objects.filter() return b.industrycat2_set.all() # Returns all Entry objects related to Blog. except IndustryCat1.DoesNotExist: return None This is the file where I need to get results returned from query which is implemented in industries.py: views.py: # -*- coding: utf-8 -*- from django.http import HttpResponse from models import IndustryCat1 from demo.core.persistence.Industries import * from django.shortcuts import get_object_or_404, render, render_to_response from django.core import serializers import json def … -
Django - get 404 on live, works on local enviroment
I have an application in django 1.6 and a problem with /admin/ address on live. When I go to this address on the live gets a 404 error. Nginx log says that I have no file or directory: /path_to_project/live/admin/index.html "not found (2: No such file or directory) Locally, everything works and the project does not have the index.html file in the admin directory. Please for help. My urls: from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^', include('presentationtool.urls')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings: from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['*'] TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) # Application definition DEFAULT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) THIRD_PARTY_APPS = ( 'south', 'easy_thumbnails', ) ADMIN_APPS = ( 'suit', 'adminsortable', ) LOCAL_APPS = ( 'myapp', ) INSTALLED_APPS = ADMIN_APPS + DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'www.urls' WSGI_APPLICATION … -
Can you optimize this code? (Django, python)
I'm adding 'added' field to check which categories User's Post(Outfit) is added to. It sounds horrible, so let's dive in to the code. I want to optimize get_categories(self, obj) function. class OutfitDetailSerializer(serializers.ModelSerializer): def get_categories(self, obj): user = self.context['request'].user categories = Category.objects.filter(owner=user) added = categories.extra(select={'added': '1'}).filter(outfits__pk=obj.pk) added = list(added.values('added', 'name', 'id')) added_f = categories.extra(select={'added': '0'}).exclude(outfits__pk=obj.pk) added_f = list(added_f.values('added', 'name', 'id')) categories = added + added_f return CategorySerializer(categories, many=True).data Output is below! "categories": [ { "id": 1, "name": "Gym", "added": true }, { "id": 2, "name": "School", "added": false }, { "id": 3, "name": "hollymo", "added": true }, { "id": 4, "name": "Normal", "added": false }, { "id": 6, "name": "New Category", "added": false } ] This question is an extension of a question: 'filter multiple objects and returns 'new field' in Serializer' Detail about Outfit and Category model is explained in the question. -
DRF: "detail": "Method \"GET\" not allowed."
I am trying to create a register and sign in API(TokenAuthentication) using DRF. This is my views.py from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny from django.http import HttpResponse from .serializers import AccountSerializer from .models import Account class AuthRegister(APIView): """ Register a new user. """ serializer_class = AccountSerializer permission_classes = (AllowAny,) def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class AuthLogin(APIView): ''' Manual implementation of login method ''' def post(self, request, format=None): data = request.data email = data.get('email', None) password = data.get('password', None) account = authenticate(email=email, password=password) # Generate token and add it to the response object if account is not None: login(request, account) print("logged in") return Response({ 'status': 'Successful', 'message': 'You have successfully been logged into your account.' }, status=status.HTTP_200_OK) return Response({ 'status': 'Unauthorized', 'message': 'Username/password combination invalid.' }, status=status.HTTP_401_UNAUTHORIZED) This is urls.py from django.conf.urls import url from .views import AuthRegister from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token urlpatterns = [ url(r'^login/', obtain_jwt_token), url(r'^token-refresh/', refresh_jwt_token), url(r'^token-verify/', verify_jwt_token), url(r'^register/$', AuthRegister.as_view()), ] When I run the server i get the following error. Not able to figure out the error. Please anyone help! -
How to store an object that references several other objects in a specific order?
I am developing a Django project with three main classes : class A, class B and class C. Objects from the C class are composed of objects from A and B classes in a specific order. All of them are stored in a MySQL database. Currently I have : class A(models.Model): name = models.CharField(max_length=250) class B(models.Model): name = models.CharField(max_length=250) class C(models.Model): name = models.CharField(max_length=250) composed_of = PickledObjectField(blank=True) Therefore, to create C objects I do the following : c1 = C() c1.composed_of = [a1, b4, a1, b1, a2, b2, b3, b4, a2, a5] c1.save() with a1..a5 being instances of A and b1..b5 instances of B. This works but is not good at all for two reasons : 1. It is awful when I need to query this field ; 2. If instances of A or B are updated or deleted from the database, the change is not done in the C instances. Thus my question : how can I make a class with instances referencing instances from other classes, in a specific order ? I'm using Django 1.8 with Python 2.7. -
modal doesn't show up but grey background appears on click of button
I have a dynamically created table and on click of view button present in every row it shows up a grey screen but modal doesn't open ..I tried a lot but not understanding where the problem is involved.I took help of https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html his code as reference.please help me... m_manage.html---Here i declared modal and included the page <div class="panel-body"> <table class="table table-hover" id="table"> <tbody> {% include 'm_manage/partial_m_manage.html' %} </tbody> </table> </div> <div class="modal fade" id="modal-leave"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> partial_m_manage.html : It contains the the columns in table {% for pl in pending_leaves %} <tr> <td><button type="button" class="btn btn-default btn-sm view" data-url="{% url 'm_manage:leave_view' pl.id %}" data-target="#{{pl.id}}_3"><i class="fa fa-eye" aria-hidden="true" style="color:black"></i></button> </td> </tr> js----call to on click of button $("#table").on('click', '.view', function (e) { var btn = $(this); console.log(btn); var url= btn.attr("data-url"); console.log(url); $.ajax({ // url: '/m_manage/leave_view/', url: btn.attr("data-url"), dataType: 'json', type: 'get', beforeSend: function () { $("#modal-leave").modal("show"); }, success: function (data) { console.log('You Did it!!!!'); $("#modal-leave .modal-content").html(data.html_form); } }); }); views.py-- def leave_view(request,pk): Leave = get_object_or_404(leave, pk=pk); data=dict() if request.method == 'POST': data['html_form']= render_to_string('m_manage/view_modal.html',{'Leave':Leave}, request=request) return JsonResponse(data) view_modal.html---I am rendering a new page ie modal <form method="post" action="{% url 'm_manage:leave_view' Leave.id %}" class="js-leave-view-form"> {% csrf_token %} <div class="modal-header"> … -
Can't start django app with daphne
I was going through a tutorial on Django Channels until I came across the command that should start my app daphne apps.base.asgi:channel_layer -p 8000.What could be the reason my django app doesn't start when running it in terminal. It doesn't show any errors, when I press Enter it just goes to new line without running the command. -
Django: Caching differs on Accept-Language request HTTP header
I'm caching some APIs functions in a Django projects. My code basically looks like this: @cache_control(max_age=1200) @cache_page(60 * 60 * 24) def data_as_json(request, argument_1, argument_2): #code return JsonResponse(rst) and in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', 'OPTIONS': { 'MAX_ENTRIES': 1000 } } } I noticed when I look in the cache table that the visitor's Accept-Language request HTTP header seems to be part of the cache key. Here is an example: :1:views.decorators.cache.cache_page..GET.3181615aba0959bd5afd815d19aedc92.d41d8cd98f00b204e9800998ecf8427e.en.Europe/Berlin I'm assuming this means that this cache object will only be used for users with the same Accept-Language request HTTP header? My website has few visitors and serve the same content to all visitors so I do not want the caching to depend on the visitor's location and language. Is there a way to change this? I'm using Django 1.11 and Python 3.6. -
django haystack search using elasticsearch
I tried to follow the instructions on Haystack Docs but i think their missing codes in it. For example it tells me to add 'SearchView' into app/urls.py and then include the app in the project/url.py. I am trying to implement a table search on the same page as my tables data. this is my urls.py urlpatterns = [ url(r'^$', views.table_base, name='tables'), url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='id-details'), url(r'^(?P<table_id>\d+)/details$', views.addview, name='details'),] this is my dynamic table models.py @python_2_unicode_compatible class AllTables(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) depth = models.IntegerField(db_column='Depth') redirectstatus = models.IntegerField(db_column='RedirectStatus') created_at = models.DateTimeField(db_column='Created_at') class Meta: managed = False def __str__(self): return self.url and this is part of tables/views.py def addview(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name tbl_detail = AllTables.objects.raw(tbl_details) paginator = Paginator(list(tbl_detail), 100) page = request.GET.get('page') try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) return render(request, 'tables/table_list.html', {'tbl_name': table_name, 'details': tbl_detail, 'detail_page': details}) I did follow the steps in the haystack docs...i created a .txt file inside my template/tables/.txt, I created my search.py file class AllTablesIndex(indexes.SearchIndex, indexes.Indexable): title = indexes.CharField(document=True, use_template=True) url = indexes.CharField(model_attr='url') description = indexes.CharField(model_attr='description') redirectstatus = … -
Django-Haystack using nested facets with Elastic Search
I want to create nested facets for my application. There are two categories, Prim_Cat and Alt_Cat with a 1:M relationship in my Django models.py. search_index.py prim_cat = indexes.CharField(model_attr='primary_category', faceted=True) alt_cat = indexes.CharField(model_attr='alternative_category', faceted=True) I want to the alt_cat results to be nested within the related prim_cat. Any thoughts on how to acheive this? Thank you. -
Get the ChildObject from the BaseObject
So i want to get the Secondobject It's One to One from First. model.py(First) <pre> class Firstobject(models.Model): (...) def save(self,*args,**kwargs): super().save(*args,**kwargs) Second.objects.get_or_create(first=self) </pre> model.py(Second) <pre> class Votes(models.Model): (...) first = models.OneToOneField(First) def save(self,*args,**kwargs): self.value2 = self.value - self.value2 super().save(*args,**kwargs) def __str__(self): return "%s name" % self.first </pre> View.py <pre> def function(request, pk): pk = request.GET.get('pk') obj = models.First.objects.get(pk=pk) votes = obj.Second votes.value = votes.value + 1 votes.save() data = {'val1':votes.value, 'val2':votes.value2} return JsonResponse(data) </pre> index.html ----------------- <button data-url="{% url 'first:link' pk=first.pk %}" data-pk="{{first.pk}}"></button> foo.js ----------------- <pre> $('button').click(function() { var pk = $(this).attr("data-pk"); var urla = $(this).attr("data-url"); // $.ajax({ url : urla, data : {'pk' : pk}, success : function(data) { $('#ID1' + pk).text(data.val1) $('#ID2' + pk).text(data.val2)} }); }); </pre> So my Error is: AttributeError at /link/5/ 'First' object has no attribute 'Second' I know whats the error is, but i cant figure out how to fix it. I hope you Guys can help me -
How to test get request in django with a data?
I am now writing tests for my web application in django. I have a url 127.0.0.1/home/device/(?P<item>[^/]+). I was testing invalid url path. Here item is a device name in the database. Consider an invalidedevice and while testing i have given the following code. response=self.client.get("health/errorfiles",{'item':'invaliddevice'}) This give me 404 response. The same thing i have tried with response=self.client.get("health/errorfiles/invaliddevice") But this time,test runner execute my view function and give TypeError since it is not an invalid device. In both of the method, which one is correct usage for a get request. Please help me ? I am stuck here, please help me to solve this. -
How to add prefix in URL-name in Django?
Here's first url-file: from blog import urls as blog_urls urlpatterns += [ url(r'^blog/', include(blog_urls, app_name='blog', namespace='blog')) ] And the second url-file (blog/urls.py): urlpatterns = [ url(r'^$', blog, name='main'), url(r'post/(?P<slug>[\w\-]+)/$', post, name='post'), url(r'category/(?P<category>[\w\-]+)/$', blog, name='category'), ] As a result, my url-adresses are: blog.mysite.com/category || blog.mysite.com/post But what I actually want is this: mysite.com/blog/category || mysite.com/blog/post Cant you please help me accomplish this ? -
How to split ModelAdmins from one app to more block
I have single Django app and it contain 2 models Store and Account. I registered them in admin.py and I get them in the admin in one block "EXAMPLE APP" Now I`d like to split it into two blocks to better UI: "EXAMPLE APP" will contain only Account "ANOTHER BLOCK WITH CUSTOM NAME" that will have Store model. this looks like the current state # admin.py class FooAdminSite(AdminSite): site_title = "Foo Admin" site_header = 'Foo administration' class AccountAdmin(admin.ModelAdmin): pass class StoreAdmin(admin.ModelAdmin): pass admin_site = FooAdminSite(name='admin') admin_site.register(Account, AccountAdmin) admin_site.register(Store, StoreAdmin) # urls.py from foo.admin import admin_site urlpatterns = [ url(r'^admin/', admin_site.urls), ] How I can achieve this to looks like on this screenshot I don't want add another app - just want use single app and customize admin. I tried add another AppConfig in apps.py but it didn`t help. -
show count and top_categories in the homepage
I want to show top_categories in the homepage. I have written top_categories function to list the categories that has most number of products. But I have written this function in Product Model. I am confused on where should I write this. Here is my code class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) categories = models.ManyToManyField(Category, related_name='products') def top_categories(self): product = Product.objects.values('id').annotate( categories_count=models.Count('categories')).order_by('-categories_count') return product def home(request): categories = Category.objects.all() companies = Company.objects.all()[:12] context = { 'categories': categories, 'companies': companies } return render(request, 'company/home.html', context) Now there is a confusion, Do I have to implement top_categories function in Category modal or the way I am doing is fine? Because the job of showing the content in homepage is the role of home view. -
How to handle thousands of ajax requests in the web server
I have a web application that makes a lot ajax requests to get the data from the server and I want the server to handle those requests. The total number requests that I am getting on the server is around 4500 requests/second. Currently I am using Apache->mod_WSGI->Django to serve the requests and the server is not able to handle those requests and timing out. I need 45-250 millisecond to process the data in the back-end and respond. So is there any way that I can make the server more efficient and respond much fast? -
Django factory boy OneToOne field UNIQUE constrained failed error
I have a test case created containing 2 objects calling the same factory My intention was to create 2 instances of them for my tests. My tests.py class BoatTestCase(TestCase): def setUp(self): self.current_boat = BoatFactory() self.bogus_boat = BoatFactory() My factories.py: class UserFactory(DjangoModelFactory): class Meta: model = get_user_model() email = factory.Sequence(lambda n: 'email_{}@example.com'.format(n)) class BoatFactory(DjangoModelFactory): class Meta: model = models.Boat user = factory.SubFactory(UserFactory) Running the test with this setup raises an exception: django.db.utils.IntegrityError: duplicate key value violates unique constraint "boat_user_id_key" DETAIL: Key (user_id)=(1) already exists. my Boat model does not have a field named user_id. only a OneToOne with User class Boat(models.Model): user = models.OneToOneField(User, related_name='boat') I suspect that the factory is creating another instance of user just like the first one it created (because I was invoking the BoatFactory twice). I got completely lost on this problem for over an hour, and just flipped the table and tried random stuff just to get it working. My solution was to add a kwarg to the BoatFactory upon invocation. Like this: BoatFactory(user_id=2). I figured I should specify the field user_id because it's the one being called out in the error. Somehow it does not raise the error anymore. My current code looks like … -
Search by date range in Django Admin
After trying to include two input fields (for date range) into the search form in Django Admin for days and with no avail, I finally have done so by appending the form itself using jQuery, resulting in this: When the submit button is hit without filling out those two fields, the form returns an ?e=1 error, which is a problem number one. When dates are properly filled out the form works as expected: But then when I submit the form with different dates (or empty dates as shown in the example below), the URL parameters are doubled, and the original input is always there rendering the usage of the form useless, which is a problem number two: How can I fix both of those problems, one: be able to send an empty form, expecting that all entries will be returned in the search results, two: get rid of the orginal set of url parameters when the form is re-submitted? Can I have little nudge in the right direction? -
Django 1.6 Logging : Custom name logger propagating to root when set to False
Below is my settings.py import logging custom_logger = logging.getLogger('custom') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'django.utils.log.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file_log': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/tmp/web_logs.log', 'maxBytes': 1024 * 1024 * 200, 'backupCount': 1, }, 'filtered_log': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/debug_info.log', }, }, 'loggers': { 'django.request': { 'handlers': ['null'], 'level': 'ERROR', 'propagate': False, }, '': { 'handlers': ['console', 'file_log'], 'level': 'DEBUG', 'propogate': True, }, 'custom': { 'handlers': ['filtered_log'], 'propogate': False, }, }, } But every custom_logger.debug('Message') is sent to both custom logger and '' logger. For every logging level the same happens i.e. it is sent to both the loggers despite Propogate flag is set to False. Any suggestions to rectify it. Please ignore the indentation errors and Django version is 1.6. -
Should I get ID the user ID using websockets or REST in Django?
I use in my project REST for registration and user authentication. When the user logs in he can send message to backend using websockets. I save his all messages to my database. At the moment in my database I have columns id and message. I would like to add also id of the user which send message to backend. My model looks in this way: class Message(models.Model): message = models.CharField(max_length=200) I want to achieve this: from django.contrib.auth.models import User class Message(models.Model): user = models.ForeignKey('auth.User') message = models.CharField(max_length=200) My question is how should I add the user ID to my database with his message. ID of this user should be sended using websockets or for instance header in REST? -
Nginx gateway timeout without much load on server
I am using NGINX and UWSGI to power the python/Django based API backend with load balancer attached to AWS auto scale groups, my servers works fine in routine, but sometimes start getting 504 or 502 from server once in a month or two constantly for a day or more. Load on my server is less than routine, memory usage is fine, but still get 502 or 504 Using ubuntu 14.0.4 Here is how my nginx configuration looks user www-data; worker_processes 2; pid /run/nginx.pid; events { worker_connections 2048; multi_accept on; use epoll; } worker_rlimit_nofile 40000; http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 50s; keepalive_requests 1024; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; client_body_timeout 12; client_header_timeout 12; send_timeout 10; limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 20; open_file_cache max=5000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## log_format json '{"method": "$request_method", "uri": "$request_uri", "status": $status, "request_time": $request_time, "upstream_response_time": $upstream_response_time, "body_bytes_sent": $body_bytes_sent, "http_user_agent": "$http_user_agent", "remote": "$remote_addr", "upstream": "$upstream_addr", "proxy": "$proxy_host"}'; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 9; #gzip_buffers 16 8k; #gzip_http_version 1.1; #gzip_types text/plain … -
I want to create a reusable function in Django
I am new to django and have been working on a project where i need to send regular mails to my clients from different modules in my django project. I wanted to know if there is any provision in django using which i can create a reusable component which can be used globally in my project. The purpose is to create a mail sending function using a third party api and to call it from anywhere in my application just by passing the required parameters.