Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i import single object from django to a html template
i am creating a website with django and i have 2 models in it,1:Gifi(contains .gif images) and 2:categorite! When i click one of the .gif images i want to be sent to another html template where that image shows and information about it.I have done some coding and when i click the image i get to the html page but the problem is that no data from django gets imported to that html page,except the id on the url.I know the problem is so simple but i am new to this and i dont know the code. This is the models: from django.db import models class categorite(models.Model): name = models.CharField(max_length=100) id = models.AutoField(primary_key=True) class Gifi(models.Model): foto = models.ImageField(upload_to='website/static/') emri = models.CharField(max_length=100) Source = models.CharField(max_length=100) Kodet = models.CharField(max_length=12) categoryId = models.ForeignKey(categorite, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) This is views.py: from django.shortcuts import render,get_object_or_404 from .models import Gifi,categorite # Create your views here. def home(request): return render(request, 'website/home.html') def categories(request): content = { 'view': categorite.objects.all() } return render(request, 'website/categories.html',content) def PostaCode(request): return render(request, 'website/PostaCode.html') def Contact(request): return render(request, 'website/Contact.html') def category(request,id): content = { 'view': Gifi.objects.filter(categoryId_id=id), } return render(request, 'website/category.html',content) def code(request,id): content = { 'view': get_object_or_404(Gifi,pk=id) } return render(request, 'website/code.html',content) This is … -
How to filter ManyToManyField in django rest framework
I have a model Offlinecheckout and CartItem model. I want to add a filter queryset of the cart field in the offline checkout model. As It is showing the cart of all users. I want to filter queryset by request.user.So that cart filed will show in the cart request.user only not other users. How I can add a filter in that field. Models.py class OfflineCheckOut(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE) cart = models.ManyToManyField('cart.CartItem') time_slot = models.ForeignKey('category.TimeSlot', on_delete=models.CASCADE) state = models.CharField(max_length=254) city = models.CharField(max_length=254) address = models.CharField(max_length=254) landmark = models.CharField(max_length=254, blank=True) # order_id = models.ForeignKey('cart.CartModel', on_delete=models.CASCADE) date = models.DateField() tsn_amount = models.IntegerField() def __str__(self): return self.user.username serializers.py from rest_framework import serializers from .models import Address, Date, OfflineCheckOut class OfflineSerializer(serializers.ModelSerializer): class Meta: model = OfflineCheckOut fields = "__all__" views.py class offlineViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return OfflineCheckOut.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() serializer_class = OfflineSerializer -
Django : user online / offline - error 'bool' object is not callable
I'm trying to know if my user are online or offline. I got different apps. I'm using user app for all my users. user/models.py class UserProfile(models.Model): ... def last_seen(self): return cache.get('last_seen_%s' % self.user.username) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > (self.last_seen() + datetime.timedelta(seconds=settings.USER_ONLINE_TIMEOUT)): return False else: return True else: return False then I've created a new file: user/middleware.py import datetime from django.core.cache import cache from django.conf import settings from django.utils.deprecation import MiddlewareMixin class ActiveUserMiddleware(MiddlewareMixin): def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.datetime.now() cache.set('seen_%s' % (current_user.username), now, settings.USER_LASTSEEN_TIMEOUT) In my settings.py (monsite folder): I added this to MIDDLEWARE 'user.middleware.ActiveUserMiddleware' Also at the bottom of my settings.py file I've added that: (and I don't really with what I've to replace LOCATION value) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } # Number of seconds of inactivity before a user is marked offline USER_ONLINE_TIMEOUT = 300 # Number of seconds that we will keep track of inactive users for before # their last seen is removed from the cache USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7 I got this issue: 'bool' object is not callable /home/dulo0814/monProjetDjango/user/middleware.py in process_request, line 10 -
Updating DataTable Row from pop up using Django
I managed to list all the elements of my DataTable and put it in one page, I added in each row an update button, onclick , it shows a pop up with all information about that specific row. Now I want to add elements to that row from the modal pop up and then on submit, it updates that dataTable row. I have problem sending the new data to that specific dataTable row id. -
How To Show Category in Drop-down and Hide if Not Available in Django?
I am working with drop-down in Django, and I have done this. But main issue is this if a category doesn't have subcategory then drop-down should be hide, Please let me know how I can do it. here is my html code when I am displaying category, subcategory and subchildcategory.. {% for i in cat %} <li class="mega" id="hover-cls"><a href="javascript:void()" class="has-submenu" id="sm-15980957729343015-21" aria-haspopup="true" aria-controls="sm-15980957729343015-22" aria-expanded="false">{{i.cat_name}} <span class="sub-arrow"></span></a> <ul class="mega-menu full-mega-menu" id="sm-15980957729343015-22" role="group" aria-hidden="true" aria-labelledby="sm-15980957729343015-21" aria-expanded="false"> <li> <div class="container"> <div class="row"> {% for j in i.subcategoryies.all|slice:"0:10" %} <div class="col mega-box"> <div class="link-section"> <div class="menu-title"> <h5>{{j.subcat_name}}<span class="according-menu"></span></h5> </div> <div class="menu-content" style="display: none;"> <ul> {% for k in j.SubChildRelated.all %} <li><a href="/subcategory/{{k.slug}}">{{k.name}}</a></li> {% endfor %} </ul> </div> </div> </div> {% endfor %} </div> </div> </li> </ul> </li> {% endfor %} here {% for j in i.subcategoryies.all|slice:"0:10" %} subcategory will display, but if {{i.cat_name}} doesn't have subcategory then it should not be display as a dropdown in main menu, so please let me know how I can hide the dropwown if a category doesn't have subcategory. -
How to DJANGO Web Token and Save Procces (POST)?
I am trying to add data on views.py, I send username and password parameters on JSON body with POST method from POSTMAN . Normally The function work succesfully like below: json_str=((request.body).decode('utf-8')) json_data = json.loads(json_str) new_device = Device(id=json_data["id"], status=json_data["status"]) try: new_device.save() resp_data = { 'code': 200, "success": True } return JsonResponse(resp_data) except Exception as e: error_data = { "success": False, "error": str(e) } return JsonResponse(error_data) After enable djangorestframework_simplejwt package on my project and run it successfully I changed urls.py link like: path('add/', add_device) to path('add/', add_device.as_view()) On views.py: class add_device(APIView): permission_classes = (IsAuthenticated,) def get(self,request): json_str=((request.body).decode('utf-8')) json_data = json.loads(json_str) new_device = Device(id=json_data["id"], status=json_data["status"]) try: new_device.save() resp_data = { 'code': 200, "success": True } return JsonResponse(resp_data) except Exception as e: error_data = { "success": False, "error": str(e) } return JsonResponse(error_data) But now, always a json error message returns to me: { "detail": "Method \"POST\" not allowed." } How do I fix it ? Thank for all helps.. -
uwsgi with django Permission denied on folder
I'm relatively new with Unix like systems and I'm trying to configure a Django application with nginx as web server using the uwsgi protocol. I'm using Ubuntu 20.4 LTS I followed this guide: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 But when I start the uwsgi process it gives me this error: Aug 31 09:23:07 fucur-vm systemd[2255]: uwsgi.service: Failed to execute command: Permission denied Aug 31 09:23:07 fucur-vm systemd[2255]: uwsgi.service: Failed at step EXEC spawning /usr/local/bin/uwsgi: Permission denied Aug 31 09:23:07 fucur-vm systemd[1]: uwsgi.service: Main process exited, code=exited, status=203/EXEC Aug 31 09:23:07 fucur-vm systemd[1]: uwsgi.service: Failed with result 'exit-code'. If I run the command namei -nom /run/uwsgi the system tell me the following permissions: f: /run/uwsgi drwxr-xr-x root root / drwxr-xr-x root root run drwxr-xr-x bryan www-data uwsgi These are my configuration files: /etc/uwsgi/sites/example.ini [uwsgi] project = django-example uid = bryan base = /home/%(uid) chdir = %(base)/%(project)/provadjango home = %(base)/%(project)/venv module = example.wsgi:application master = true processes = 5 socket = /run/uwsgi/example.sock chown-socket = %(uid):www-data chmod-socket = 666 vacuum = true /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown bryan:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target Could someone exaplain to me what is my problem? Thanks in advance -
Hybrid Django Application - REST API Authentication
I am new to Django and have built a basic application (Django 3.1) which uses session authentication and a simple login page (username + password) to login a django user. It works fine. I would like to use javascript (vue.js) on pages accessible to the logged in user to call Django REST APIs, hosted on the same Django application. Despite lots of googling, no one seems to give a clear authentication example of a hybrid Django app, augmented with APIs. I have used lots of APIs before so am familiar with the authentication options. My issue is how to get credentials to the javascript loaded by django templates in a secure manner. IDEALLY I would like: User logs in with username/password django redirects to PAGE B, AUTOMAGICALLY SOMEHOW inserting user's token into a cookie/sessionStorage A javascript function on PAGE B gets credentials from cookie/sessionStorage and calls API (using all the various options supported by django-rest-framework) My Questions: Question 1 ==> in my do_login view function (below), after successful authentication with Djangos inbuilt login method, do I need to create a cookie in HttpResponse (e.g. token=XXXXXXX), so javascript can access it? Is this secure? def do_login(request): .... login(request, user) ... #create … -
Percent encoding in url
Suppose I have the code: params = {'a': '('} url = 'example.com/some-url?' + urlencode( {k: encode_param(v) for k, v in params.items()}).replace('&', '&amp;')' This gives example.com/some-url?a=%28 But when I access this url, it is not decoded to (. It remains %28. What is the function to properly encode query params? -
Django how to use validate_image_file_extension
hello how to pass a validator on model field ? from django.core.validators import validate_image_file_extension class Photo(models.Model): image = models.ImageField('Image', upload_to=image_upload_path, validators=?????) -
No module names 'notifications.signals'; 'notifications' is not a package
Hello I have a problem with a Django project. When I ran in Pycharm the celery I got this error : No module named 'notifications.signals'; 'notifications' is not a package Althought when I type in Python Console this : from notifications.signals import notify Could you help me please ? Thank you very much -
Django Type Eroor at add
I want to create a function that returns the list of last points per vehicle that have sent navigation data in the last 48 hours. I create a view it works and it displays name correctly but when I want to add new Vehicle from Django Admin panel it shows an error. TypeError at /admin/navigation/navigationrecord/add/ str returned non-string (type int) How can I fixed it? And is there a more afformative and efficient way to list data over the past 48 hours? models.py class Vehicle(models.Model): id = models.IntegerField(primary_key=True) plate = models.CharField(max_length=30) def __str__(self): return str(self.plate) class NavigationRecord(models.Model): id = models.IntegerField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) datetime = models.DateField(default=timezone.now) latitude = models.FloatField() longitude = models.FloatField() def __str__(self): return self.vehicle views.py def get_48_hours(request): time_48 = datetime.now() - timedelta(hours=48) results = NavigationRecord.objects.filter(datetime__gte=time_48) context = { 'results': results, } return render(request, 'navigation.html', context) navigation.html <table class="table table-hover"> <thead> <tr> <th>ID</th> <th>Vehicle</th> </tr> </thead> <tbody> {% for result in results %} <tr> <td>{{result.id}}</td> <td>{{result.vehicle}}</td> <td>{{result.datetime}}</td> </tr> {% endfor %} </tbody> </table> admin.py models = [Vehicle, NavigationRecord] admin.site.register(models) traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/navigation/navigationrecord/add/ Django Version: 2.2.13 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'navigation'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
how to redirect different login page to different type of users in django admin after login?
i created user - user 1 assigned group A user 2 assigned group B now i created login page and after login as user1 i want to redirect to page1.html and if logged in as user2 then redirect to page2.html for this i wrote def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: auth.login(request,user) if user.usergroup=='A': return redirect('pages/page1.html') else: return redirect('pages/page2.html') else: messages.error(request,'Invalid credentials') return redirect('login') # User is authenticate else: return render(request,'pages/login.html') with this i logged in as user1 ,got the error AttributeError at / 'User' object has no attribute 'usergroup' kindly help -
Django Model Tree
I need to create next logic, but i stack in modeling. i think: user1 give invite code to user2, user2 give invite code 3 and etc.. when user give invate for every next user we are increment invation counter for example to user2 and etc. task: The user can generate his own invitation code. Each user has his current points. The scoring scheme is as follows: The prize fund for the successful use of the invitation code is N points, where N is the current number of registered users of the owner of the code + 1. The prize fund is distributed according to the scheme: the owner of the code 1 point, the one who attracted the owner 1 point, and so on, until one of the conditions is reached: a) N == 0 b) the top of the tree is reached In case b and if N> 0, the user at the top gets the entire value of N User can watch other those who attracted him and the list of people he attracted. I created some models and know what do next :( class User(AbstractUser): invation_code = models.CharField(max_length=128, blank=True) points = models.PositiveIntegerField(default=0) class Invation(MPTTModel): invation_from = models.ForeignKey(User, … -
Do I need foreign key reference when using separate schemas for tenants?
I am doing research for database design for a SaaS application. I studied this article where 3 approaches are discussed. Separate database for each tenant, Shared database but separate schemas and Shared database and schema with foreign key reference to the tenant table. The first approach is out of the question for me. From the 2nd and 3rd, 2nd approach suits best my situation. I have Django on top of PostgreSQL. I, ll create a separate schema for each tenant. For serving every (web) request, I'll identify the current user's schema and set it using SET SCHEMA before querying the database. 3rd option is to add tenant id in every database table and query accordingly. My question is how secure is 2nd approach considering Django running as web application on top of the database? Are there any chances of data leakage considering there can exist cross schema foreign key references? Should I also add a foreign key in tables as an extra layer of security and query accordingly? -
Django static files css,fonts,img
I've received static files from a friend who've working on front-end stuff I'm trying to implement them in django project. I've learned I can approach django static files through {% static '' %} at html file But I have no idea to approach fonts and pictures at CSS file. fonts are designated in this format at CSS file @font-face { Src: url('../fonts/SansBold.otf');} and images are designated in this format at CSS file .hero-header { background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('../images/img2.jpg');} So How can I approach the static file and use them at css file? -
How do I solve failed to find attribute `application` in `folder.myproject`
How do I solve this error, I keep on getting it for deployment to heroku The web server I use is gunicorn Failed to find attribute 'application' in 'src.website_viewer'. -
Add Django elements locally to ManyToMany fields without saving them in the database, comparable to the setattr function, only for M2M fields
I was looking to see if there was a way to add local items to a ManyToMany field without storing them in the database. I want to be able to do the same with a ManyToMany field as I would with a ForeignKeyField or other fields of a Django model. There is a function setattr (obj, field.name, <newValue>) for these fields. These changes are not saved in the database, but I can access them in templates, for example. I would be very happy if someone could give me a hint whether there is something similar for ManyToMany Fields. I've struggled with this problem for quite a while and haven't found anything about it. Thanks in advance :) -
Transform function to class based view (recall same site)
Very similar to these questions I want to transform my view. The difference is that I want to return to the same page and I have problems adjusting my urls.py (I think): So on the product_all.html I press a button and end up on the same page after the product was deleted: def delete_product(request, pk): Product.objects.filter(id=pk).delete() context = {'Product': Product.objects.all()} return render(request, 'gbkiosk/product_all.html', context) urls.py: path("product_delete/<int:pk>", views.delete_product, name='product-delete'), I wanted to recreate that using a TemplateView: class DeleteProduct(TemplateView): template_name = "gbkiosk/device_all.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Product.objects.filter(id=kwargs["product_id"]).delete() context["products"] = Product.objects.all() return context but what would the corresponding urls.py entry be?: path("product_delete/<int:product_id>", views.DeleteProduct.as_view(), name="product-delete") This will not return me to product_all.html after clicking? -
Is it possible to change the definition of model field using a proxy model?
With a proxy model, it is possible to extend and overwrite the functionality of the base model's methods. But is it also possible to manipulate the base model's fields? from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class MyPerson(Person): class Meta: proxy = True # Somehow extend first_name to have max_length of 50. # Add an integer field called `points` -
Object of type MxCreateSerializer is not JSON serializable
I am working on a django project and I have a django model Message: class Message(models.Model): content = models.TextField(_('Content')) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sent_dm', verbose_name=_("Sender"),on_delete=models.CASCADE) recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='received_dm', verbose_name=_("Recipient"),on_delete=models.CASCADE) sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) views.py class MessageCreateView(APIView): queryset = Message.objects.all() serializer_class = MxCreateSerializer def get(self, request, format=None): serializer = MxCreateSerializer() return Response({'serializer':serializer}) def post(self, request): sent_data = request.data #print(sent_data) data_ = [elem for elem in sent_data.values()] sender = data_[0] content = data_[1] recipient = data_[2] csrf = data_[3] sender = get_object_or_404(User,username=sender).username recipient = get_object_or_404(User,username=recipient).username new_resp = {'sender':sender,'content':content,'recipient':recipient, 'csrfmiddlewaretoken':csrf} qdict = QueryDict('', mutable=True) qdict.update(new_resp) #print(qdict) serializer = MxCreateSerializer(data=qdict) if not serializer.is_valid(): return Response({'message':'no'}) serializer.save() return Response({'message':'yes'}) serializers.py class MxCreateSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ['sender','content','recipient'] def create(self, validated_data): message = Message.objects.create(**validated_data) print(message) return message I get this error: Traceback (most recent call last): ... File "/.../site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/.../site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/.../site-packages/rest_framework/renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "/.../site-packages/rest_framework/renderers.py", line 680, in get_context 'content': self.get_content(renderer, data, accepted_media_type, renderer_context), File "/.../site-packages/rest_framework/renderers.py", line 413, in get_content content = renderer.render(data, accepted_media_type, renderer_context) File "/.../site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/.../site-packages/rest_framework/utils/json.py", … -
Looping Initial Data for Formset Django
I want to set initial data at formset for TimeField's field every 1 hour as much 24. So the desired output: 00:00, 01:00, 02:00, 03:00,..., 22:00, 23:00 like below image: I tried following code but no result: profiles = UserProfile.objects.filter(username=username) initial_formset = [{ 'user': item.name, 'time': datetime.datetime.now(). + datetime.timedelta(hours=1), } for item in profiles] MyFormset = formset_factory(MyForm, extra=24) formset = MyFormset(initial=initial_formset) Any help will be appreciated. -
can't multiply sequence by non-int of type 'QuerySet' in Django 2.2.4
I have this logic in my views.py that will multiply the quantity and unitprice in the same models. I am using aggregate, and i encountered this error, can't multiply sequence by non-int of type 'QuerySet' def updatecart(request): itemID = request.GET.get("itemID") cart = CustomerPurchaseOrderDetail.objects.filter(id = itemID) per_item_amount = CustomerPurchaseOrderDetail.objects.filter(id = itemID).aggregate(total=Sum('unitprice' * cart.values_list('quantity'))) print(per_item_amount) return render(request, 'customAdmin/add2cart.html', {"cart": cart}) this is my models.py class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer,on_delete=models.SET_NULL, null=True, blank=True,verbose_name="Client Account") customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer Purchase Order") products = models.ForeignKey(Product,on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") quantity = models.IntegerField(null=True, blank=True, default=1) unitprice = models.FloatField(max_length=500, null=True, blank=True) def __str__(self): suser = '{0.id}' return suser.format(self) How do i configure this out? this is my traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in updatecart 981. per_item_amount = CustomerPurchaseOrderDetail.objects.filter(id = itemID).aggregate(total=Sum('unitprice' * cart.values_list('quantity'))) Exception Type: TypeError at /updatecart/ Exception Value: can't multiply sequence by non-int of type 'QuerySet' -
End of script output before headers: ezstage.wsgi
I am getting to only specific requests from django admin page which has big data wsgi.conf file <VirtualHost *:8080> WSGIPassAuthorization On #Header set Access-Control-Allow-Origin "*" WSGIScriptAlias / /home/ubuntu/ezstage.wsgi WSGIDaemonProcess localhost processes=4 threads=30 display-name=%{GROUP} WSGIProcessGroup localhost WSGIApplicationGroup %{GLOBAL} # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn LogLevel debug ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/criterioncloudez/static/ #Alias /static/admin /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/ <Directory /home/ubuntu> AllowOverride All Require all granted </Directory> <Location "/static/"> Options -Indexes </Location> ezstaze.wsgi file import os import sys import site prev_sys_path = list(sys.path) site.addsitedir('/usr/local/lib/python2.7/site-packages') sys.path.append('/home/ubuntu/criterioncloudez'); os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' sys.path.extend([ '/usr/local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages/django/contrib/admindocs', ]) new_sys_path = [p for p in sys.path if p not in prev_sys_path] for item in new_sys_path: sys.path.remove(item) sys.path[:0] = new_sys_path from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ''' error: [Mon Aug 31 05:23:47.955596 2020] [authz_core:debug] [pid 31414] mod_authz_core.c(802): [client 117.216.179.95:15666] AH01626: authorization result of Require all granted: granted [Mon Aug 31 05:23:47.955647 2020] [authz_core:debug] [pid 31414] mod_authz_core.c(802): [client 117.216.179.95:15666] AH01626: authorization result of : granted [Mon Aug 31 05:23:47.962028 2020] [authz_core:debug] [pid 31414] mod_authz_core.c(802): [client 117.216.179.95:15666] AH01626: authorization result of Require all granted: granted [Mon … -
Create flask modules and dividing application
I'm building a small flask application and I want to have a modular structure in my project. In Django I could just write two separate folders with their own urls.py, register them in my settings.py and create routes to them in base urls.py. How to achieve this kind of modularity in flask? Preferably with as little code as possible. Bonus points if all this can be easily done without extensions.