Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dependent dropdown list using jquery in django
I am beginner i want dropdown list in django using jquery which get data from database evrything is working perfectly but the problem is its not picking the first data in dropdown it select the first after selecting another.So tell me how its possible first data in dropdown list got selected at first.Thank you. viwes.py from django.shortcuts import render from map.models import * import json as simplejson from django.http import HttpResponse # Create your views here. def index(request): countries = Country.objects.all() print(countries) return render(request, 'index.html', {'countries': countries}) def getdetails(request): #country_name = request.POST['country_name'] country_name = request.GET['cnt'] print("ajax " + str(country_name)) result_set = [] all_cities = [] answer = str(country_name[1:-1]) selected_country = Country.objects.get(name=answer) print("selected country name " + str(selected_country)) all_cities = selected_country.city_set.all() for city in all_cities: print("city name " + str(city.name)) result_set.append({'name': city.name}) return HttpResponse(simplejson.dumps(result_set), content_type='application/json') index.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; ajax('/getdetails',data,function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }); }); }); </script> </head> <body> <select name="selectcountries" id="selectcountries"> {% for item in countries … -
I passed the user information to get_queryset but No output from the template
I have a question. I passed user information to get_query_set like below. After searching for one user's information, I passed it to a template through get_query_set. However, nothing is printed in the template. I don't know why console : [25/Jun/2020 15:56:55] "GET /accounts/my_profile_information_view/ HTTP/1.1" 200 11946 my_profile_information_view excute!! user : nodebird profile_user : <QuerySet [<User: nodebird>]> view : class user_profile_information_view(LoginRequiredMixin,ListView): paginate_by = 10 # if 'q' in request.GET: # query = request.GET.get('q') # print("query : ", query) def get_template_names(self): if self.request.is_ajax(): print("user list ajax ") return ['accounts2/user_profile.html'] return ['accounts2/user_profile.html'] def get_queryset(self): print("my_profile_information_view excute!!") user = self.kwargs['user'].strip() print("user : ", user) profile_user = User.objects.filter(username=user.strip()); print("profile_user: ", profile_user) return profile_user templates: <table class="table table-bordered"> <tr> <td width="20%">user_name</td> <td>{{profile_user}}</td> </tr> <tr> <td>email</td> <td> <div class="input-group mb-1"> <input type="text" class="form-control" value="{{profile_user.profile.email}}" id="profile_email" aria-describedby="basic-addon2" ></input> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button">수정</button> </div> </div> </td> </tr> <tr> <td> public </td> <td> <div class="input-group mb-1"> <input type="text" class="form-control" value="{{profile_user.profile.public}}" aria-describedby="basic-addon2" id="profile_public"></input> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button">수정</button> </div> </div> </td> </tr> <tr> <td> github </td> <td> <input type="text" class="form-control" value="{{profile_user.profile.github}}" aria-describedby="basic-addon2" id="profile_github"></input> </td> </tr> </table> -
Django accessing multiple databases dynamically
I have a django project where I am trying to make a customer based grocery system. Here I have different databases for each customer. Each database consist of order history as well as all other details like contact details etc. I will get an url argument to identify customer through customer_id & I will able to get which database to use ie db name. Code - Model - class Company(models.Model): company_id = models.IntegerField(primary_key = True) name = models.CharField(max_length=256, blank=True, null=True) db_name = models.CharField(max_length=200, blank=True, null=True) db_uuid = models.CharField(max_length=100, blank=True, null=True) objects = DataFrameManager() def __str__(self): return self.name Views file - @api_view(['GET', 'POST']) def page(request, uuid): if request.method == 'GET': rtrn = Company.objects.filter(db_uuid=uuid).values('db_name') return Response(rtrn) Url file - urlpatterns = [ url(r'user/(?P<uuid>[a-zA-Z0-9-]+)/$', page, name="getfromurl"), ] Here I will return db name. But I am not able to understand and implement the change of database. Let me make you understand with an example - Lets suppose Customer name Gaurav has db 'gaurav_groceries'. By the code I get the name - gaurav_groceries. But in setting.py I have added default db as 'grocies', so how can I use this dynamic nature of db ie in this case we have 'gaurav_groceries', for further calculation and … -
Django rest status=status.HTTP_400_BAD_REQUEST not working, response not visible after API is called from postman
My code: Views: if serializer.is_valid(): user = serializer.save() user.set_password(password) user.save() # to save password try: newmap=UserClientMapping() newmap.user= HelloOpsUser.objects.get(username=data['username']) newmap.client = ClientMaster.objects.get(client_name=data['client']) newmap.save() dataResp = {} dataResp['res'] = 'User added' return Response(dataResp['res'], status=status.HTTP_200_OK) except Exception as ex: print(ex) return Response(ex, status=status.HTTP_500_INTERNAL_SERVER_ERROR) None of the responses are coming in output, when the user gets added, i get output in postman as: "User added" ; status codes status=status.HTTP_200_OK, status=status.HTTP_500_INTERNAL_SERVER_ERROR, are not working; i have imported all the modules: from rest_framework.response import Response, from rest_framework import viewsets, status, generics, from django.http import HttpResponse, JsonResponse -
In urlpatterns path works, but not re_path
Djanto 3.0.7 I had urplatterns with paths. Like this: path('polls/', include(('polls.urls', 'polls'), namespace="polls")), But I decided to refactor them using re_path: urlpatterns = [ re_path(r'^$', HomeView.as_view(), name='home'), re_path(r'^{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls, {'extra_context': {'raster_image_admin_divider': '10', 'number_of_raster_image_fields': 150}}), # Change admin url for security reasons. re_path(r'^polls/', include(('polls.urls', 'polls'), namespace="polls")), re_path(r'^applications/', include(('applications.urls', 'applications'), namespace="applications")), re_path(r'^draft/authors/', include(('authors.urls', 'authors'), namespace="draft_authors")), re_path(r'^authors/', include(('authors.urls', 'authors'), namespace="authors")), re_path(r'^email/', include(('email_subscribtions.urls', 'email_subscribtions'), namespace="email")), re_path(r'^facts/', include(('posts.urls.fact', "posts"), namespace="facts")), re_path(r'^draft/<slug:categories>/', include(('posts.urls.post', "posts"), namespace="draft_posts")), re_path(r'^<slug:categories>/', include(('posts.urls.post', "posts"), namespace="posts")), re_path(r'^tags/$', TagListView.as_view(), name="tags"), ] When I go to http://localhost:8000/draft/linux/install-os-ubuntu/, I get this: Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^admin/ ^polls/ ^applications/ ^draft/authors/ ^authors/ ^email/ ^facts/ ^draft/<slug:categories>/ ^<slug:categories>/ ^tags/$ [name='tags'] __debug__/ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, draft/linux/install-os-ubuntu/, didn't match any of these. Could you tell me why includes don't work and how to fix it. -
Django foreignkey coming in integer
my views : from django.shortcuts import render from django.http import JsonResponse, HttpResponse from .models import Post from django.views.generic import DetailView, ListView def returningJSONData(request): sharedData = list(Post.objects.select_related().values()) return JsonResponse(sharedData, safe=False) class postView(ListView): model = Post template_name="main/feeds.html" class postDetails(DetailView): model = Post my model : from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(blank=True, null=True, max_length=200) description = models.TextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateField(auto_now_add=True) my template : {% extends 'main/base.html' %} {% block content %} <div id="root-app"> <div style="height: 100vh !important; padding-bottom: 8%" class="row"> <div style="height: 100% !important; overflow-y: scroll;" class="col-sm-3 extraCol"></div> <div style="height: 100% !important; overflow-y: scroll;" class="col-sm mx-0 px-0"> <div style="width: 100%;" v-for="post in postObjects" class="ui card"> <div class="content"> <div class="right floated meta">[[post.date_posted]]</div> <img class="ui avatar image" src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg"> </div> <div class="image"> <img> </div> <div class="content"> <div class="header">[[post.title]]</div> <p class="description">[[post.description]]</p> <span class="right floated"> <i class="heart outline like icon"></i> 17 likes </span> <i class="comment icon"></i> 3 comments </div> <div class="extra content"> <div class="ui large transparent left icon input"> <i class="heart outline icon"></i> <input type="text" placeholder="Add Comment..."> </div> </div> </div> </div> <div style="overflow-y: hidden !important;" class="col-sm-4 extraCol"> <div style="width: 100%;" class="ui card"> <div class="content center aligned"> <img src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg" class="ui avatar image" alt=""> <p class="description">Username: {{request.user}}</p> <p … -
NoReverseMatch at /login/ (Reverse for 'index' not found. 'index' is not a valid view function or pattern name.)
I am starting with Django 3 and python 3.8, and I have had a problem, I am trying to start the session and when I press the Ingresar button I get this error: I have tried many things to try to solve it but I cannot, although I have found similar problems, the solutions they give have not worked for me. This is the code I have so far: principal urls.py urlpatterns = [ path('',include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('index/', views.index) ] app urls.py urlpatterns = [ path('/index', views.index, name='index'), path('/login', views.login, name='login'), ] views.py def index(request): return render(request, 'index.html') def login(request): return render(request, 'login.html') base_generic.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Read Praxis</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2"> {% block sidebar %} <ul class="sidebar-nav"> <li><a href="#">Home</a></li> <li><a href="">All books</a></li> <li><a href="">All authors</a></li> </ul> {% endblock %} </div> <div class="col-sm-10 "> {% block content %}{% endblock %} </div> </div> </div> </body> </html> login.html <!doctype html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> … -
Building Contest Platform using Django
Thanks for your attention.I am trying to create a contest platform, that is,users of my site can register for a contest in between a certain period of time.After closing,no one can join,but the ones who joined can post their materials.till now i have made a login-logout system and account registration successfully.but i am having no clue how to proceed next.could anyone help me? -
How to make a Django model enum available over API?
Say I have a model: class Student(models.Model): # Constants in Model class FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) Copied from here. Now, my frontend is in React. When I want someone to pick their "Year in school", they will ideally select from a dropdown with the choices in YEAR_IN_SCHOOL_CHOICES. My question is, how can I make these options available over REST API to the frontend? -
Django and Jquery submit multiple forms in a table using 1 submit button
I have two models that are currently set on a 1 html page. These models named "Products" and "Parts" where the products will have multiple parts. In this case, I want the user to create a "Product" by dynamically filling up a table that will consist of a part list of a product or "BOM". I think I successfully created an initial set up because I can save a "Product" but with no "Parts". My problem is how can I save the multiple parts of a product using jquery or ajax? I've read some questions and documentations but I still can't figure how to implement it. I saw some posts mentioning the use of formsets but I think it will only be effective if the second form only consists of 1 instance but in my case, I have many instances of "parts" I want to save for a "product". Any suggestions or coments on my code will be greatly appreciated! I initially planned on putting all the form data in a dictionary or array and send it to the view function via jquery or ajax. So I created the jquery script that would handle the submit request. However I don't … -
How to write queries to fetch queryset in Django
I want to get the count of likes for all the post written by particular author. I have tried something like below, Post.objects.filter(author=1).liked.count() but, it returns Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'liked' I'm able to fetch the like count for particular post by, Post.objects.filter(author=1).first().liked.count() How do I handle this logic in my views.py file? models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MinLengthValidator(200)]) liked = models.ManyToManyField(User, default=None, blank=True, related_name = 'liked') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'author') def __str__(self): return self.title @property def num_likes(self): return self.liked.all().count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices= LIKE_CHOICES,default='Like', max_length=10) def __str__(self): return str(self.post) -
Specifying which CSS file goes with a HTML template
The project I'm currently working on has 4-5 HTML template files, all of which use the same CSS file. I would like to change the CSS visual layout of one of the HTML files (let's call it engagement.html), and I figured that the easiest way to change that would be to create a new CSS file and have engagement.html refer that that new CSS file rather than the old CSS file . {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/new-css.css' %}"> </head> My new HTML page currently looks like this. I tried to change something simple, like the color of a paragraph. However, when I go to the browser and Chrome Developer tools, it looks like it's still getting its styles from the old-css.css file (the new paragraph color is crossed out). I've tried CTRL+SHIFT+R to refresh the cache and reloading everything, but no luck. -
How to trigger Django's pre_delete signal?
I have a User model and a UserImage model that contains a foreign key to a User. The foreign key is set to CASCADE delete. Here is what the receivers look like in my models.py: @receiver(pre_delete, sender=User) def deleteFile(sender, instance, **kwargs): print("User pre_delete triggered") instance.thumbnail.delete() @receiver(pre_delete, sender=UserImage) def deleteFile(sender, instance, **kwargs): print("UserImage pre_delete triggered") instance.image.delete() When I execute the following lines of code: >>> User.objects.last().delete() "UserImage pre_delete triggered" For some reason the associated UserImage signal is being received but the actual User model's signal is not. Am I missing something? -
Why does the number of .djcache files increase with MAX_ENTRIES when caching a serializer data attribute using cache.set in django REST?
I'm trying to use file based caching with django REST to cache a serializer.data object. the cache related settings look like so: CACHES = { "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "/var/tmp/django_cache", "OPTIONS": {"MAX_ENTRIES": 1}, } } I set the cache "manually" in the list method of a ViewSet: class SomeViewSet(viewsets.ViewSet): def list(self, request): cached_data = cache.get("some_key") if cached_data: return Response(cached_data, status=status.HTTP_200_OK) queryset = SomeModel.objects.all() serializer = SomeSerializer(queryset, many=True) cache.set("some_key", serializer.data, None) return Response(serializer.data, status=status.HTTP_200_OK) If the cache is completely cleared each time (I delete the files manually): calling this method once, will create 3 .djcache files with "OPTIONS": {"MAX_ENTRIES": 1}, calling this method once, will create 5 .djcache files with "OPTIONS": {"MAX_ENTRIES": 5}, calling this method once, will create 8 .djcache files with "OPTIONS": {"MAX_ENTRIES": 10}, calling this method once, will create 20 .djcache files with "OPTIONS": {"MAX_ENTRIES": 20}, I checked that the queryset is only executed if no cached file exist but I'm really confused about how this files are managed as I expected only one file would be created to store the serializer.data object Did I miss some settings? -
Show html / restricting views to groups
I'm trying to be able to restrict views to certain groups as well as display certain blocks of html to said groups. I also want to know how to reuse this code across all my apps in my project. Right now this code gives me NameError: name 'request' is not defined views.py from django import template register = template.Library() @register.filter('in_group') def in_group(user, group_name): return user.groups.filter(name=group_name).exists() @login_required @user_passes_test(in_group(request.user, 'Company Staff')) def some_view(request): return render(request=request, template_name='main/some-template.html') I also have this for checking in templates if a user is in a group main/templatetags/filters.py from django import template register = template.Library() @register.filter(name='group') def group(u, group_names): group_names = group_names.split(',') return u.groups.filter(name__in=group_names).exists() -
Django - Make parameter optional
In my urls file, I have specified the path to views - urlpatterns = [ path('users/userdetails', PersonalUserDetailView.as_view(), name='hello'), path('stores/<int:store_id>', StoreDetailView.as_view(), name='hello2'), ] Howvere, I want to make the store_id optional. How do I do it? -
Drill down in Line Chart Highcharts
I have a scenario as something similar to this. https://jsfiddle.net/31om2f6d/ Note that the data plotted in x-axis and data inside series is a list of 50 values (in this example, I have mentioned 6 values.) I need to drilldown into another three line charts which indicates the sum of the counts. For example, Point 50 in 2019.1 will be split into three points say(10,10,30) in the drilldown. Similarly the rest of the points as well.As a result, there should be 3 line charts when I drilldown from linechart of main page. Kindly help me out with this function. Note: I have been reading in forum like drilldown can be done only in point mapping and not when mapped in series. I am not sure if that is the exact behaivour. If so, kindly let me know how we can map a series of 50 dynamic data by points and drilldown from there. Any help is appreciated. Thanks in Advance. Highcharts.setOptions({ colors: [ '#470303', '#c40a0a', '#a34d4d', '#eda4a4' ] }); Highcharts.chart('container-trend', { chart: { type: 'line', }, title: { text: 'Trend' }, exporting: { tableCaption: false, enabled: false }, credits: { enabled: false }, xAxis: { categories: [2019.1, 2019.2, 2019.3, 2019.4, 2019.5, … -
Remove the key value pairs based on value
a:{ b:{cd:"abc", de:"rty" }, c:{cd:"abc", de:"uuy" }, d:{cd:"ap", de:"uy" } } I want to print values of cd and de from this dictionary and if the value of cd is same then I only want to print once. Expected output: b abc rty d ap uy How can I check if the value of cd is repeated or not ? -
django admin list filter nested related field as dropdown
I have the following model classes: class School(models.Model): ... school_name = models.CharField(max_length=255, null=True, blank=True) ... def __str__(self): return self.school_name class Class(models.Model): ... school = models.ForeignKey("backend.School", null=True, blank=True, related_name='class_school', on_delete=models.CASCADE) ... class Student(models.Model): ... class = models.ForeignKey("backend.Class", null=True, blank=True, related_name='student_class', on_delete=models.CASCADE) ... On the student admin listing page i'm trying to have the list filter of school_name in dropdown instead of list My searching lead to this answer I tried both method of using the django-admin-list-filter-dropdown and the filter.html template , both using the following related field class__school But in the admin it still render the school_name in list and not dropdown I tried with other fields and it work except for the nested related field Hope someone can help me -
Django filtering odd behavior with for loop
I am attempting to perform some filtering in Django, and trying to test how long it takes with different backend structures. The filtering is working, however, when I try to get the average time that filtering takes through running it n (set to 1000) amount of times, then dividing total time it takes by n, it is around 10x faster, then when n is set to 1. Is there a reason for this? (I am multiplying by 1000 to convert to ms) without average: temp = Response.objects.filter(id="Asde22dFee")[0].content end = time.time() return HttpResponse((end-start)*1000) with average: start = time.time() for i in range(1000): temp = Response.objects.filter(id="Asde22dFee")[0].content end = time.time() return HttpResponse((end-start)*1000 / 1000) -
Django complicated right-join queryset
I am trying to figure out how to solve this problem without using Raw SQL. I want to have a query set of all provinces categorized in age_range, filtered by the urban area (location_type), but assume zero for provinces whose population is 0. following qs omits provinces with zero population but I want to present 0 in the sum field. my models: #-------------------------------------------------------------------------------------# #---@desc Keeps a list of different cities #-------------------------------------------------------------------------------------# class Province(models.Model): code = models.CharField(max_length=3) title = models.CharField(max_length=100) def __str__(self): return "{}".format(self.title) #-------------------------------------------------------------------------------------# #---@desc Keeps list of differents cities #-------------------------------------------------------------------------------------# class City(models.Model): code = models.CharField(max_length=8) title = models.CharField(max_length=100) province = models.ForeignKey(Province, on_delete=models.CASCADE , related_name='cities') def __str__(self): return "{} - {}".format(self.province, self.title) #-------------------------------------------------------------------------------------# #---@desc Keeps information about population records of each city #-------------------------------------------------------------------------------------# class Population(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, related_name ='poeple') gender = models.CharField(max_length=1, choices=GENDER) number = models.IntegerField(null=False) location_type = models.CharField(max_length=1, choices=LOCATION_LIST) #rural or urban area age = models.IntegerField( null=False, validators=[ MinValueValidator(0), MaxValueValidator(100), ]) objects = PopulationQuerySet.as_manager() view: qs= Population.objects.select_related('city__province').\ annotate( age_group=Case( When(age__range=(0,9), then=Value('0-9')), When(age__range=(10,19), then=Value('10-19')), When(age__range=(20,29), then=Value('20-29')), When(age__range=(30,39), then=Value('30-39')), When(age__range=(40,49), then=Value('40-49')), When(age__range=(50,59), then=Value('50-59')), When(age__range=(60,69), then=Value('60-69')), When(age__range=(70,79), then=Value('70-79')), When(age__range=(80,89), then=Value('80-89')), When(age__range=(90,99), then=Value('90-99')), When(age=100, then=Value('100+')), default=Value('100+'), output_field=CharField(),)).\ filter(location_type = "U").\ values('city__province__title', 'gender', 'location_type','age_group').\ annotate(sum=Sum('number')) -
django-admin cannot find settings module
I'm trying to run django-admin runserver but I get this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'App' I am using pipenv so I made a .env file in the cwd and I have the DJANGO_SETTINGS_MODULE pointing atsrc.App.settings I haven't made any sort of modifications, I believe, except running the server once with ./src/manage.py runserver (it automatically created an sqlite3 db). Here is the file structure image I can run the server perfectly fine if I run it through manage.py though 🤔 -
View multiple pdf together (Django)
I have many pdf related and need to show them all in browser togheter. Also I need to download them all or a selected group. I use Django but didn´t found a library for that porpouse. I think maybe there is a js one. How can I solve that? -
Even after dispatching, CSRF token won't work
So I followed the instructions from the answers on this thread: @csrf_exempt does not work on generic view based class However, when I send POST requests via Postman, it still keeps throwing 403 error and I wonder what I am missing here. I tried the last answer(using braces.views and CsrfExemptMixin) as well and it still wouldn't work. Below is my code so far import json import jwt from psr.settings import SECRET_KEY from django.http import HttpResponse, JsonResponse from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.contrib.auth import views as auth_views from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from braces.views import CsrfExemptMixin from .models import User class LoginView(auth_views.LoginView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(LoginView, self).dispatch(request, *args, **kwargs) def post(self, request): form = AuthenticationForm(data = request.POST) if form.is_valid(): user = authenticate(email=request.POST['email'], password=request.POST['password']) if user is not None: messages.add_message(request, messages.SUCCESS, "Welcome back, {}".format(user)) login(request, user) token = jwt.encode({'id': user.id}, SECRET_KEY, algorithm='HS256').decode('utf-8') return JsonResponse({'token': token}, status=200) Am I missing something here? Thanks a lot in advance! -
Operations on django querysets
Say I have an image model with a many to one relationship to a product model as shown below: class Image(models.Model): product = ForeignKey(Product,on_delete=models.CASCADE, related_name='images' ) original = ImageField(ulpoad_to='img/') class Product(models.Model): title = CharField(max_length=120) def get_images(self): return self.images.all() def get_primary_image(self): #return the first uploaded image in the queryset images = self.get_images() return images[0] When trying to access {{product.get_primary_image.url}} on an image tag in a template it outputs an IndexError instead of the image, even after I add a couple more images to the database I still get the index error. Where could I be going wrong? Please help I'm still a newbie at this.