Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to rediect to redirect url in Django, Python, Keycloak
@method_decorator(login_required, name='dispatch') class ResetCredential(RedirectView): url = '/oidc/logout' def get(self, request): return redirect('https://docs.djangoproject.com/') I want to call first this < url = '/oidc/logout' > because I want to logout first and then https://docs.djangoproject.com/ -
Correct Practice - Change whole web application to REST API or create a REST API section
I currently have an existing Django based web application, but I am now planning to create an Android app. I need authentication and data from the server so I will be using Django Rest Framework. Just wondering, is it better to change the whole application to REST API or just create a .../api section? -
Get selected text from ckeditor in django python
Are there any good ways to get the selected text from a ckeditor RichTextField as a python string in django? Apologies if this question has been asked before but I could not find any results when it came to ckeditor and django. -
pythonanywhere django deployment Error running WSGI application
Hi this is the error i get when attempting to load my site on pythonanywhere, i am also using aws S3 to load my static files and Postgresql fr my db but i am yet to do any sort of configuration for this on pythonanywhere in case that helps with the solution Please any help would be greatly apprciated, thank you 2021-08-04 12:53:54,120: Error running WSGI application 2021-08-04 12:53:54,128: ModuleNotFoundError: No module named 'django_sass' 2021-08-04 12:53:54,128: File "/var/www/fulodev_pythonanywhere_com_wsgi.py", line 38, in 2021-08-04 12:53:54,128: application = get_wsgi_application() 2021-08-04 12:53:54,128: 2021-08-04 12:53:54,128: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-08-04 12:53:54,128: django.setup(set_prefix=False) 2021-08-04 12:53:54,129: 2021-08-04 12:53:54,129: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/init.py", line 24, in setup 2021-08-04 12:53:54,129: apps.populate(settings.INSTALLED_APPS) 2021-08-04 12:53:54,129: 2021-08-04 12:53:54,129: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate 2021-08-04 12:53:54,129: app_config = AppConfig.create(entry) 2021-08-04 12:53:54,130: 2021-08-04 12:53:54,130: File "/home/fulodev/.virtualenvs/myenv/lib/python3.9/site-packages/django/apps/config.py", line 224, in create 2021-08-04 12:53:54,130: import_module(entry) and this is my wsgi file import os from django.core.wsgi import get_wsgi_application import sys from dotenv import load_dotenv project = os.path.expanduser('/home/fulodev/portfolio_project/project') load_dotenv(os.path.join(project, '.env')) path = '/home/fulodev/portfolio_project/project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' application = get_wsgi_application() settings file ALLOWED_HOSTS = ["fulodev.pythonanywhere.com"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "portfolio_project.apps.PortfolioProjectConfig", 'django_sass', 'ckeditor', 'crispy_forms', 'ckeditor_uploader', 'storages' ] … -
I keep getting attribute Error in python anytime I try to install a python package
C:\Users\OMONIYI\Documents\Vico\django\To-do app\todo_app>pip install gunicorn Traceback (most recent call last): File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\OMONIYI\AppData\Local\Programs\Python\Python36\Scripts\pip.exe\__main__.py", line 4, in <module> File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\main.py", line 9, in <module> from pip._internal.cli.autocompletion import autocomplete File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\autocompletion.py", line 10, in <module> from pip._internal.cli.main_parser import create_main_parser File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\main_parser.py", line 8, in <module> from pip._internal.cli import cmdoptions File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\cmdoptions.py", line 23, in <module> from pip._internal.cli.parser import ConfigOptionParser File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\cli\parser.py", line 12, in <module> from pip._internal.configuration import Configuration, ConfigurationError File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\configuration.py", line 27, in <module> from pip._internal.utils.misc import ensure_dir, enum File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_internal\utils\misc.py", line 38, in <module> from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 186, in <module> class RetryError(Exception): File "c:\users\omoniyi\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\tenacity\__init__.py", line 193, in RetryError def reraise(self) -> t.NoReturn: AttributeError: module 'typing' has no attribute 'NoReturn' Please, I need help with this. I just finished my first django project, and I'm trying to install some python packages so I can host it on heroku. But anytime I try to, it keeps giving me this error. Python version is 3.6, django version is 3.1.5 -
Get Post Value in Django
I would like to achieve getting a value from a post. I have the following in my views.py: def foo(request): number = request.POST.get('number') print(number) return HttpResponseRedirect(reverse('index')) The HTML is as follows: {% for i in model %} <a class="btn btn-warning" href="{% url 'ms_app:foo' %}" method="POST" name="number" value="{{ i.number }}"">RESTART</a> {% endfor %} The output is none: [05/Aug/2021 12:14:23] "GET /ms_app/customers/1 HTTP/1.1" 200 11714 None [05/Aug/2021 12:14:24] "GET /ms_app/esp_rsrt/ HTTP/1.1" 302 0 [05/Aug/2021 12:14:24] "GET / HTTP/1.1" 200 2650 I feel like this is a simple thing that I am doing wrong. I am very new to Django and new to asking questions here, so if I have done something wrong, please let me know so I can correct it. -
Get real time data to django models from a external webpage
I have a Django app and some of the models I want to get data in real-time from external sources. class Register(models.Model): student_id=models.IntegerField() temperature=models.TextField(max_length=300) The data I want this model to hold can only be accessed in another URL. I have tried to create a web scrapy to get real-time data but it is not efficient. If there is an efficient way to handle this let me. -
How to use django cors with vue (axios)?
I just using vue and with axios going to get data from django, but it gives CORS error, how i can fix it? Console Error My settings.py file: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False # Application definition INSTALLED_APPS = [ ...... 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ ..... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' ...... ] -
Is it possible to show loading message in django admin when deleting objects?
I have added some code in the pre_delete signal that deletes the images from aws s3 bucket. Because of this, delete is taking more time which would obviously happen. But I want to show some loading message till the object deletes and redirect to the model tabular view again. How can I add that loading message ? -
Can't reopen Django File as rb
Why does reopening a django.core.files File as binary not work? from django.core.files import File f = open('/home/user/test.zip') test_file = File(f) test_file.open(mode="rb") test_file.read() This gives me the error 'utf-8' codec can't decode byte 0x82 in position 14: invalid start byte so opening in 'rb' obviously didn't work. The reason I need this is because I want to open a FileField as binary -
How do you join nested queries in Django
I am trying to frame a Django query for a normal sql that looks like this: SELECT d.id, sum(d.assess), sum(d.view) from (SELECT id, name, group_concat(status) as group, CASE WHEN(GROUP_CONCAT(status) = 4 THEN 1 ELSE NULL) as assess, CASE WHEN(GROUP_CONCAT(status) = 5 THEN 1 ELSE NULL) as view FROM <tables> Group by id,name) d join <table> e on e.id = d.related_id GROUP BY 1; The inner query (the one that does the GROUP_CONCAT) can be formed using a Django Queryset but Im not able to use that output as a Nested Query so that I can join with the main table. Since GROUP_CONCAT is already an aggregate function(which is implemented in Django using annotate functions), I am not able to do another annotate on those fields. This would avoid doing the outer query but understand why its not possible as you cannot do a GROUPING on a GROUP. I wanted to find out if there is a way to do the above, basically running a queryset as a JOIN Table so it can be used as in the setup above. I have tried: a) Subquery: Dint work as my inner query returns multiple rows (one Group_concat for each grouping) so it … -
How do I integrate specific attribute in Django
If I used this line in the PowerShell: Get-AzureADUser -ObjectId "elton.tan@straitsconstruction.com").ExtensionProperty["employeeId"] I will get the employee id How do I integrate this into Django? **This is my graph helper.py** graph_url = 'https://graph.microsoft.com/v1.0/' def get_user(token): # Send GET to /me user = requests.get( '{0}/me'.format(graph_url), headers={ 'Authorization': 'Bearer {0}'.format(token) }, params={ '$select': 'displayName,mail,mailboxSettings,userPrincipalName,department, employeeId' }) return user.json() **This is my HTML** <p>{{user.employeeId}} </p> -
handle group by in mongo engine without raw query
I want to group my documents by month of field date(documents have field createdAt that type is date) and counted them with the mongo engine in Django! I can do it using pipeline and raw query but I want to know is there any way to handle it without raw query like annotate in Django ORM -
buffer size in Django using uWSGI and Nginx
i have a test project which made using: Django 3.2.6 uWSGI 2.0.19.1 nginx/1.18.0 (Ubuntu) i was trying to implement SSE 'Server Sent Events' ,to push the some data to a user, i was able to make send the data, but i face a problem with the buffer size. in other words, the data i was trying to send was small data like this below: def sse_test_data(request): def event_stream(): while True: sleep(.2) yield f"data: {datetime.time(datetime.now())}\n\n" return StreamingHttpResponse(event_stream(), content_type='text/event-stream') and i had to wait the buffer size to reach a specific size 'limit' in order to send 'flush' the data. when i was trying to inspect the buffer size should be reached to be sent i found that it was 6000/characters so any data its size below that size it waits another data in the buffer till the whole data size reach 6000/characters and then it is sent as a block i am really new with SSE and buffering as all, i tried to read about , in order to get around this issue but i couldn't have something to solve this issue so my question is, How to control the buffer size 'make it less or more' ? How to force … -
Accessing a ManyToManyField's contents for a Django template
I'm making a low-spec e-bay clone, I'm trying to implement a watchlist function but the problem is I can't access the ManyToManyField in the Watchlist model so I can use the contents of the field in the template I'm using. To display each user's watchlist to them, so far I only get this result: but I need to get a result like so: Code I'm using: watchlist.html {% extends "auctions/layout.html" %} {% load static %} {% block title %} {{name}}'s Watchlist {% endblock %} {% block body %} <h2>{{name}}'s Watchlist</h2> {% for listing in watchlist %} <div class='listing'> <h3>{{ listing.list_title}}</h3> {% if listing.img_url == "" %} <a href='#'><img src="{% static 'auctions/img404.png' %}" class='img-fluid'></a> {% else %} <a href='#'><img src="{{ listing.img_url }}" class="img-fluid" alt='image of {{ listing.list_title }}'></a> {% endif %} <p> {{ listing.desc }} </p> <p> Current Bid: ${{ listing.start_bid }} </p> {% if listing.category == "" %} <p>Category: No Category Listed</p> {% else %} <p>Category: {{ listing.category }}</p> {% endif %} <a href='#' class='btn btn-primary' id='go'>Go To Listing</a> </div> {% endfor %} {% endblock %} views.py def render_listing(request, title): if request.method == "POST": form = BidForm(request.POST) bid = int(request.POST['new_bid']) listing = Auction_Listing.objects.get(list_title=title) comments = Auction_Comments.objects.all().filter(auction_id=listing) if bid < listing.start_bid: … -
how to add lastmod field in index sitemap django
I need to add lastmod attribute to sitemap index. And it looks like django.contrib.sitemaps.views.index doesn't include lastmode though Here is my sitemap.xml: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" <sitemap> <loc>localhost:8000/sitemap-pages.xml</loc> </sitemap> </sitemapindex> my urls.py sitemaps_pages = { 'pages': sitemaps.PageViewSitemap, 'life': sitemaps.LifeViewSitemap, 'lifes': sitemaps.LifesSitemap, 'novosti': sitemaps.NewsViewSitemap, 'novost': sitemaps.NewsSitemap, 'catalog': sitemaps.CatalogViewSitemap, 'categories': sitemaps.CategorySitemap, 'regions': sitemaps.RegionSitemap, 'times': sitemaps.TimeSitemap, 'material': sitemaps.MaterialSitemap, 'products': sitemaps.ProductsSitemap, } path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), path('sitemap.xml', index, {'sitemaps': sitemaps_pages}, name='django.contrib.sitemaps.views.sitemap'), sitemaps.py class ProductsSitemap(sitemaps.Sitemap): protocol = 'https' try: priority_filter = strip_tags(Info.objects.get(name='priority_filter').value) frequency_filter = strip_tags(Info.objects.get(name='frequency_filter').value) except Exception: priority_filter = '0.5' frequency_filter = 'daily' priority = priority_filter changefreq = frequency_filter limit = 1000 def items(self): return Product.objects.all() def location(self, item): return str(item.url) def lastmod(self, item): if item.url == '/': return Product.objects.latest('updated_at').updated_at else: return item.updated_at How do i solve the problem? -
Django Rest Framework: How to randomize Queryset while keeping the pagination and search functionality?
Premise: Imagine I have 100 items in the database and each time the user opens the application I want to display 10 random items, and as the user scrolls down more items get added. I started by creating a "ListAPIView" using a "PageNumberPagination" class: class ItemListView(generics.ListAPIView): queryset = Item.objects.all() serializer_class = ItemListSerializer pagination_class = ItemListPagination class ItemListPagination(PageNumberPagination): page_size = 20 This will give me always the same 10 items, so to randomize it I overwrote the "get_queryset" method and used a seed to randomize the queryset. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination def get_queryset(self): objects = list(Item.objects.all()) seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset seed return objects This works as expected but as soon as I introduce the SearchFilter backend, it errors out because is expecting a QuerySet and not a list. class ItemListView(generics.ListAPIView): serializer_class = ItemListSerializer pagination_class = ItemListPagination filter_backends = [SearchFilter] search_fields = ['name'] def get_queryset(self): objects = list(Item.objects.all()) # Get queryset and convert it to list seed = self.request.GET.get('seed') # get the seed from the request query params random.seed(seed) # set seed random.shuffle(objects) # randomize objects random.seed() # reset … -
Django Form validation(Not showing submitted Data)
As you see I can try to show only odd numbers on the screen. But after submission, the data not showing on the screen. Here the HTML code {% if form_submited %} <p>Field: {{ field }}</p> {% endif %} Here form.py file from django import forms from django.core import validators def even_or_not(value): if value%2==1: raise forms.ValidationError("Please Insert an Even Number!") class user_form(forms.Form): number_field=forms.IntegerField(validators=[even_or_not]) **Here views.py file ** from django.shortcuts import render,HttpResponse from home.models import Musician, Album from home import forms # Create your views here. def index(request): musician_list = Musician.objects.order_by('first_name') diction={'text_1':'This is a list of Musicians', 'musician':musician_list} return render(request,'index.html',context=diction) # return HttpResponse("this is homepage") def form(request): new_form=forms.user_form() diction={'test_form': new_form, 'heading_1': "This form is created using django library "} if request.method == "POST": new_form = forms.user_form(request.POST) diction.update({'test_form':new_form}) if new_form.is_valid(): diction.update({'field': new_form.cleaned_data['number_field']}) diction.update({'form_submited':"Yes"}) diction={'test_form': new_form,'heading_1':"This form is created using django librery "} return render(request, 'form.html',context=diction) -
how call a function with in the class in djagno shell
class Test: def m1(): pass def m2(): pass I have this class in the test.py(Django-Project) file how to call the m2 function in Django. shell. how to call this function in Django shell. I am trying like this: >> python manage.py shell >> from appname.filename import <class_name|function_name> But it thrown an error like this: ImportError: cannot import name <class_name|function_name>. anyone help me out with this. Thanks in advance. -
How my django model field can take value from a function defined in default
Having this model: class Settings(models.Model): INT = "int" FLOAT = "float" STRING = "string" JSON = "json" BOOLEAN = "boolean" VALUE_TYPES = ( (INT , "int"), (FLOAT , "float"), (STRING , "string"), (JSON , "json"), (BOOLEAN , "boolean"), ) def casted_value(self): if self.value_type == Settings.INT: return int(self.value) elif self.value_type == Settings.FLOAT: return float(self.value) elif self.value_type == Settings.STRING: return str(self.value) elif self.value_type == Settings.BOOLEAN: return bool(self.value) elif self.value_type == Settings.JSON: return json.dumps(self.value_type) key = models.CharField(max_length=100, null=True, blank=True) value = models.CharField(max_length=250, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) value_type = models.CharField(max_length=30, choices=VALUE_TYPES, default=casted_value) I am trying to give to my value_type field value based on the function casted_value. The concept is to return the value based on the type. When I am trying to migrate I come up with the error : TypeError: casted_value() missing 1 required positional argument: 'self' How is the right way to define my casted_value function in order the value_type field to take the value from this function? -
Django Download folder From Media
Django Download folder From Media In django Which method is user for Download complete directory to Client Machine from /media/ -
How do I fix the circular import in django
I am trying to simply put a 'Hello World' text on the server. And it brings an error. Project Urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] App Urls.py from django.urls import path from . import views urlpattern = [ path('', views.index,name = 'index') ] Views.py from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('<h1>Hello World</h1>') The Error it tells me: The included URLconf in myapp/urls.py does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
post() missing 3 required positional arguments: 'user', 'user_obj', and 'code'
class CodeAPIView(APIView): def post(self,request,user,user_obj,code): code2 = request.data['code'] if code2 == code: AuthAPIView.login(self,request,user,user_obj) else: return Response("the code is wrong!") this is my view, and I get an error. How can I fix it? -
For loop in django retrieving all users instead of one and M2M field data output
I have 2 Issues in Django: Below are my codes, whenever I am using For loop in my Template, it is retrieving not one user data, but all users/profile data. but when I use request.user.profile.first_name only then it works, but I am in a situation where i need to retreive data from many-to-many field and I have to use For loop, which brings me to my 2nd question I need to use For loop in many-to-many field to retreive the data, but it is fetching for all users, please can you correct me where I am doing wrong? or is there any alternate method to retreieve data without using for loop (one user/profile only post logging-in) models.py class Department(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) departments = models.ManyToManyField(Department) views.py def profilepage(request): profiles = Profile.objects.all() departments = Department.objects.all() context = { 'profiles': profiles, 'departments': departments } return render(request, 'profile.html', context) profile.html {% for profile in profiles %} First Name: {{profile.first_name}} {% for department in departments %} Department: {{department.name}} {% endfor %} {% endfor %} -
Zappa Django one lambda per app in a monorepo
My Django REST API is composed of multiples apps, one app per resource like that: ├── core │ ├── settings.py │ ├── urls.py ├── customers │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py ├── orders │ ├── models.py │ ├── serializers.py │ ├── urls.py │ └── views.py The settings of the app are all in core/settings.py. How can I tell zappa to deploy each app in a different lambda function and configure API Gateway to handle the routing for each app?