Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: context must be a dict rather than JsonResponse
I am trying to use ajax in class based Listview for pagination but it's not working.I saw many tutorial of ajax pagination but all of them is with function based views. #views.py class HomePage(ListView): model = Video template_name = 'index.html' def get_context_data(self, **kwargs): context = super(HomePage, self).get_context_data(**kwargs) videos = Video.objects.filter(category='sub') paginator = Paginator(videos, 5) page = self.request.GET.get('page2') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) context['videos'] = videos if self.request.is_ajax(): html = render_to_string('video/index2.html', context, request=self.request) return JsonResponse({'form' : html }) else: return context The error I getting using this views is:- TypeError: context must be a dict rather than JsonResponse. If you have any different ways to achieve this ajax pagination .Please mention that.Thank you in advance. -
django_filter on filtered Model
When i try to filter a model that i have queryed like this: products_model = Product.objects.filter(sub_category__name__iexact=sub) supplier_filter = SupplierFilter(request.GET, queryset=products_model ) products_model = supplier_filter.qs I get this error 'list' object has no attribute 'model' Does anyone know a way around it? Or am i just doing it wrong. I had an idea where i would get all objects then create a for loop and use the objects.get(id=pk) method for every product. But didnt get that to work. Thanks for help in advance! -
How can I get Django-Html dynamic loop on 2 table?
I have 2 tables Models.py class Spiders(models.Model): bot = models.ForeignKey(Bots,on_delete=models.CASCADE) spider_class = models.CharField(max_length=50,verbose_name="Örümcek Sınıfı") spider_name = models.CharField(max_length=200,verbose_name="Örümcek Adı",null=True) spider_url = models.CharField(max_length=200,verbose_name="Örümcek Adresi",null=True) spider_frequency = models.CharField(max_length=200,verbose_name="Spider Sıklığı", null=True) class Urls(models.Model): spider = models.ForeignKey(Spiders,on_delete=models.CASCADE) url_tag = models.CharField(max_length=200,verbose_name="URL Uzantısı") View.py def listMarkets(request): spiders = Spiders.objects.all() urls = Urls.objects.all() context={ 'spiders': spiders, 'urls': urls, } return render(request, 'index.html', context) index.html {% for spide in spiders%} <div class="card"> <div class="card-header row" id="heading{{spide.id}}"> <div class="col-2" style="padding-top:13px"> <h5 class="mb-0"><a href="#!" data-toggle="collapse" data-target="#collapse{{spide.id}}" aria-expanded="false" aria-controls="collapse{{spide.id}}">{{spide.spider_name}}</a></h5> </div> <div class="col-6"> <table class="table"> <tbody> <tr> <td>{{spide.spider_url}}</td> <td>{{spide.spider_frequency}}</td> {% endfor %} </tr> </tbody> </table> </div> <div class="col"> <tr> <td><button type="button" class="btn btn-info" style="margin-bottom: unset;" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Linkleri gir</button></td> <td><a href="#" class="btn btn-info" style="margin-bottom: unset;">Güncelle</a></td> <td><a href="#" class="btn btn-info" style="margin-bottom: unset;">Getir</a> </td> <!--<td><a href="#" class = "btn btn-danger" style="margin-bottom: unset;">Sil</a> </td>--> </tr> </div> </div> <div id="collapse{{spide.id}}" class=" card-body collapse" aria-labelledby="heading{{spide.id}}" data-parent="#accordionExample"> <table class="table table-striped"> <thead> </thead> <tbody> <tr> {% for spider in spiders %} <td>{{spider.id.url_tag (or something like this)}}</td> //I want to write url_tag depend on spider_id (foreign key) <td>{{spider.id}}</td> <td>{{spider.spider_name}}</td> <td>{{spider.spider_url}}</td> <td>{{spider.spider_frequency}}</td> {% endfor %} </tr> </tbody> </table> </div> </div> {% endfor %} I want to write url_tag depend on spider_id because every spider has more than 1 url_tag and I want … -
why webpage shows empty after running python manage.py runserver
why webpage shows empty after running python manage.py runserver python manage.py runserver shows black page. why html templates are not loading. block content is not fetching data from templates in base.html if i put all login.html in base.html it load template but after use of block and extends it shows empty. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('account.urls')), ] urls.py (account) from django.urls import path, include from account import views urlpatterns = [ path('', views.account, name='account'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def account(request): return render(request, 'account/base.html') base.html <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <title>Account</title> </head> <body> {% block content %} {% endblock content %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </body> </html> login.html {% extends 'account/base.html' %} {% block content %} <!-- Login Form --> <div class="row justify-content-center" style="margin-top:250px;"> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" … -
Python Django, Pandas: ForeignKey, his attributes and calculation
Good day, is there any solution to access the attributes of a ForeignKey inside my models.py and also to calculate inside a dataframe? class Object(models.Model): name = models.Charfield(max_length=100, null=False, blank=False) price = models.Integerfield(default=0) class Amounts(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE) amount = models.Integerfield(default=0) Let's say the existing objects are looking something like this: id | name | price 1 | name_a | 2 2 | name_b | 4 3 | name_c | 8 Now I got a dataframe that looks something like this: id | object | amount 1 | name_a | 12 2 | name_b | 7 3 | name_c | 19 Is it possible to get the other attributes of the (via foreignkey) connected data and also to calculate inside the dataframe(in this case: price x amount)? Possible result: id | object | amount | price | calc 1 | name_a | 12 | 2 | 24 2 | name_b | 7 | 4 | 28 3 | name_c | 19 | 8 | 152 Thanks for all your help! -
couldn't import django:importError
I am working on a Django project and at the beginning everything was going well . But for say 2 days i'm not more able to run my project using the Python run manage.py it gives me this error Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment ? I use Anaconda as virtual environment . During my debugging process I checked the installed packages in the environment , and this is the output. I also use python 3.8 as interpreter but outside the virtual environment. -
How to split a string in django QuerySet object
In the view.py I am trying split an attribute value which is a long string. In a normal query: someposts = Posts.object.all()[3:5] should return: <QuerySet [object<first post>, object<second post>]> So then I query posts as follows as I need to split an attribute value (after this change I get the error): someposts = Posts.object.all().values('id', 'title', 'tags')[3:5] so it returns something like: <QuerySet [{'id': 2, 'title': 'first post', 'tags': ' X1, X2, X3,.., X10'}, {'id': 4, 'title': 'second post', 'tags': ' S1, S2, S3,.., S8'}] But I expect to receive tags as a list of stings, so what I did: splited_tags = [v['tags'].split(',') for v in someposts] for n, i in enumerate(someposts): someposts[n]['tags'] = splited_tags[n] and as the result <QuerySet [{'id': 2, 'title': 'first post', 'tags': [' X1', 'X2', 'X3',.., X10']}, {'id': 4, 'title': 'second post', 'tags': [' S1', 'S2', 'S3,.., 'S8']}] since I am passing someposts to my template: context = { 'someposts':someposts, } return render(request, 'app/home.html', context) and in home.html: {%for post in someposts %} <a class="avator" href="{% url 'user-post' post.author.username %}"></a> { % endfor %} I recieve this error: Reverse for 'user-post' with arguments '('',)' not found I think the problem is post.author.username since post is a string, … -
Django elasticsearch data synchronization
I want to use elasticsearch to index a model in django, this model is an map of database view. I want to know if django elasticsearch synchronized data after the storage of data in the other tables, or before that ?? -
Django timesince function is wrong
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 I want to show that How long has it been since the data was sent. I use timesince but it shows wrong. It adds 13 hours and prints same hours for all data. I think it is related to my models because I cannot do anything about hours, minutes. like this How can I fix it? navigation.html <td>{{ result.datetime|timesince }}</td> 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 str(self.vehicle) views.py def get_48_hours(request): time_48 = datetime.now() - timedelta(hours=48) results = NavigationRecord.objects.filter(datetime__gte=time_48).order_by('-datetime') context = { 'results': results, } return render(request, 'navigation.html', context) Note: Any advice is accepted for improving my code. -
Django: Pagination wont centre on page 1
I have added in a template pagination I found and it works fine but wont centre on page 1 even with "text-centre" and "justify-content-center" as recommended by other answers. It looks fine on page 2 and 3... as can be seen below {% block pagination %} {% if is_paginated %} <div class="text-center"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} {% endblock %} This is the code i used and this is what it looks like on page 1 and its pulling to the right. I currently don't have any CSS code for the pagination, though I have tried different options with no luck. If I remove the "text-centre" then page 1 is centred but pages 2/3 pull to the left, so I am a bit stumped. p.s this is my first django post so … -
How do I create a portable admin panel in Django
I need help I want to create a cms like wordpress using django I want to create a cms once and us it for all of my projects anyone can help me ? -
Read big PDF files django
I have a pdf file (500 MB) and it contains images . Now I have to tell when each image start and when it ends , like image 1 : start page 1 , end Page 2 . for that what I can do to read that much big files ? and which python lib can do this work of checking pages ? -
django.db.utils.OperationalError: no such table: polls_post
I'm looking at this problem for an hour but i cannot find what's wrong with this, when I run "python manage.py shell" and import like "from polls.models import Post " and call on the shell "Post.objects.all()" it shows an error like this "django.db.utils.OperationalError: no such table: polls_post" how can I solve this ? This is the polls.models.py ''' from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) ''' This is the 0001_initial.py ''' Generated by Django 3.1 on 2020-08-31 02:53 ''' from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.TextField()), ('date_posted', models.DateTimeField(default=django.utils.timezone.now)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] ''' -
Django __str__ return foreignkey title
Good day, I am currently experiencing an issue with my code. My goal is to have the most MostRevenueGeneratedForCurrentMonth attach to the Sales model with a Foreign Key and return the Foreign Key's Product Title but for some reason it keeps giving me an error saying 'Product' object has no attribute 'product_title' The sales Model class Sales(models.Model): """ This is the data Model for the sales data. This is where we will be saving products that have been sold so we can collect data for stats """ order_item_id = models.CharField(max_length=155) order_id = models.CharField(max_length=155) order_date = models.DateTimeField() sale_status = models.CharField(max_length=155) offer_id = models.CharField(max_length=155) tsin = models.CharField(max_length=155) sku = models.CharField(max_length=155) product_title = models.CharField(max_length=155) takealot_url_mobi = models.CharField(max_length=155) selling_price = models.CharField(max_length=155) quantity = models.IntegerField() warehouse = models.ForeignKey( Warehouse, on_delete=models.CASCADE, null=True) customer = models.CharField(max_length=155) takealot_url = models.CharField(max_length=155) shipment_id = models.CharField(max_length=155, null=True) po_number = models.CharField(max_length=155, null=True) shipment_state_id = models.CharField(max_length=155, null=True) shipment_name = models.CharField(max_length=155, null=True) promotion = models.CharField(max_length=155, null=True) def __str__(self): return self.product_title The MostRevenueGeneratedForCurrentMonth Model class MostRevenueGeneratedForCurrentMonth(models.Model): """ This is the data model for the most revenue generated products so we can easily keep track of it and sort through it to send to the API app to get serialized and sent to the frontend. """ … -
How to use multiprocess in django command?
I'm tring to use ProcessPoolExecutor in django command to get some results at same time. And I tried with below codes to get it # main codes import json import time import datetime from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from redis import Redis from django.conf import settings from django.core.management.base import BaseCommand from thrift.transport import TSocket, TTransport from thrift.protocol import TBinaryProtocol from utils.cache import pool from services.analysis.thrift.Analysis import Client, Dashparam from api.analysis.models import MDashBoard redis_con = Redis(connection_pool=pool) class AnalysisThriftService(object): def __init__(self): ... def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.transport.close() class Command(BaseCommand): help = 'python manage.py --settings "xxx"' def add_arguments(self, parser): parser.add_argument('--dashboard_id', type=int, help="ID") @staticmethod def _handle_with_thrift(dashboard_id): try: print(dashboard_id) with AnalysisThriftService() as thrift_server: dashboard_result = ... except: import traceback traceback.print_exc() def handle(self, *args, **options): dashboard_id = options["dashboard_id"] if dashboard_id is None: dashboard_tables = [dashboard.id for dashboard in MDashBoard.objects.all()] with ProcessPoolExecutor(max_workers=5) as executor: executor.map(Command._handle_with_thrift, dashboard_tables) else: ... But I always get error like Process Process-5: Process Process-2: Traceback (most recent call last): File "D:\python3\lib\multiprocessing\process.py", line 258, in _bootstrap self.run() File "D:\python3\lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "D:\python3\lib\concurrent\futures\process.py", line 169, in _process_worker call_item = call_queue.get(block=True) File "D:\python3\lib\multiprocessing\queues.py", line 113, in get return _ForkingPickler.loads(res) File "C:\Users\Domob\Desktop\dev\myapi\analysis\management\commands\dashboard_schedule_task.py", line 15, in <modu le> … -
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=?????)