Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to link Users to Usermodel
Hello I am pretty new to Django and don't get yet fundamental ideas of Users. I was able to create a registration page to create users which are shown on the admin page in the "Authentication and AUthorization -> Users". Now I want the users to logg in and create their profiles. They should add some additional information like name, bio, picture etc. Every user should be able to add and see its own profile. To do that I created a model: class Profile(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) bio = models.TextField() profile_pic = models.ImageField(upload_to="images/") def __str__(self): return self.firstname + ' | ' + self.lastname In my view and the html I am able to add these informations to the model. But HOW exactly can I relate this "Profile"-Model to the individual user? What do I miss here? -
how to pass the value of list indjango to method
I am trying to do something like this, I have a navigation bar with li items. **index.html** <ul class="submenu dropdown-menu"> <li><a class="dropdown-item" name="mis" href="{% url 'pdfNotes'%}">MIS</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">MA</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">UXD</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">OSS</a></li> </ul> here when I navigate to the first list '' i.e for MIS I have to redirect to pdfNotes.html with the name as 'mis' so that I can use this as a parameter in views.py to filter my data and display only 'MIS' details in pdf notes. same for all other li items. **pdfNotes.html** {% if pdfnote %} <table> <tr> <th># </th> <th>NAME</th> <th>DOWNLOAD FILE</th> </tr> {% with counter=1 %} {% for item in pdfnote %} {% with crs=item.course %} <tr> <td id="id">{{crs}}</td> <td id="id">{{pattn}}</td> <td id="id">{{sem}}</td> <td id="id">{{ forloop.counter}}</td> <td id="name">{{item.name}}</td> <td id="downloadBtn"> <a href="{{item.file.url}}" class="btn-outline-success" download >DOWNLOAD</a> </td> </tr> {% endwith %} {% endfor %} {% endwith %} </table> **model.pdf** class PDF_Notes(models.Model): name=models.CharField("File name",max_length=100) subject=models.CharField("Subject",max_length=50) course=models.CharField("Course",max_length=50) semester=models.CharField("Semister",max_length=50) year=models.CharField("Year",max_length=50) source=models.CharField("Source",max_length=100) file=models.FileField(upload_to="media/PdfNotes") def __str__(self): return self.name **view.py** def pdfNotes(request): pdfNotes_file=PDF_Notes.objects.all() #sub=request.GET[] if(request.GET['mis']): pdfNotes_file=PDF_Notes.objects.all().filter(subject="MIS") n=len(pdfNotes_file) print("hello",pdfNotes_file) params={'pdfnote':pdfNotes_file,'total_items':n} return render(request,'pdfNotes.html',params) how can I do that, please... Thanx!! -
AttributeError: module 'signal' has no attribute 'SIGHUP'
I am trying to deploy my Django app using the Apache2.4-Webserver. mod_wsgi has been installed in the project folder. When I try to run the command python manage.py runmodwsgi --reload-on-changes it returns the error: ***\mod_wsgi\server\management\commands\runmodwsgi.py", line 158, in handle signal.signal(signal.SIGHUP, handler) AttributeError: module 'signal' has no attribute 'SIGHUP'. How can I go about this? -
Django/HTML - HTML not showing complete string from the context, rather only part of it
I am working on a Django site. This site has a form with preview button. How I would like it to work: Text entered in the input field on HTML. Preview button pressed. Python script runs in background. Form to retain it's values. What I have done: So far I have managed to a create form, a preview button, run the script and return the values as context to HTML and show it on the form. However the problem is, if the string has spaces. Form only shows first section of the string rather than whole string. Example: If I enter name as "John Smith" and press preview button. Form only shows me "John". Same if I do "London, United Kingdom". It shows me "London," I have looked onto Google and stackoverflow but couldn't find a solution to this, hence thought to ask here. I would appreciate if someone can guide me on this. views.py ''' nname = request.POST['name'] django_run_script() context = {'name': nname} ''' index.html ''' <div class="form-group"> <label class="label" for="name">Full Name</label> <input type="text" class="form-control" name="name" id="name" placeholder="Name" required value={{ name|default:"" }}> </div> ''' Thank you, Kind regards, Shashank -
Django allauth and google recaptcha on login page - any good solutions?
I'm getting this error error Exception Value login() got an unexpected keyword argument 'redirect_url' Exception Location: \allauth\account\views.py, line 159, in form_valid I would have thought there were some good solutions out there, but none work for me, it seems outdated? I'm using django-allauth and django-recaptcha 2.0.6 The login page shows the google recaptcha, but I don't think it's working at all. When I type in an incorrect password it says that it's incorrect even when I don't check the box. I've tried putting {{ form.captcha }} in html and it doesn't show at all. When I do type in the correct password with or without checking the box I get the error above. There must be an easy solution? This is my code: forms.py from allauth.account.forms import LoginForm from captcha.fields import ReCaptchaField class MyCustomLoginForm(LoginForm): def login(self): captcha = ReCaptchaField() # You must return the original result. return super(MyCustomLoginForm, self).login(captcha) login.html <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="xxxx"></div> <button class="primaryAction" type="submit">{% trans "Sign … -
Django: Pass Model objects to context_processors
As a new developer to Django, I am running into an issue of trying to pass a model's object list to a global variable accessible on any template, within any app. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_ROOT, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'myapp.site_context.site_context_processor', ], }, }, ] site_context.py from .apps.events.models import Event def site_context_processor(request): ctx = {} ctx['current_year'] = time.strftime("%Y") ctx['events'] = Event.objects.active()[0] return ctx I am running into an issue of an app_label missing on the Events model, but when I add this, I get conflicting apps in the settings.py Model class myapp.apps.events.models.Event doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. when settings.py looks like INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'directory', 'events', 'utilities', 'filebrowser', ] but when I add the app via myapp.apps.Events I get RuntimeError: Conflicting 'event' models in application 'events': <class 'events.models.Event'> and <class 'myapp.apps.events.models.Event'>. Not sure where to go from here. Any help would be greatly apperciated. -
How could I translate static data coming from JSon files in Django?
I have a json file with a long list of geographic locations [ { "id": 1, "name": "Afghanistan", "iso3": "AFG", "iso2": "AF", "phone_code": "93", "capital": "Kabul", "currency": "AFN", "currency_symbol": "؋", "tld": ".af", "native": "افغانستان", "region": "Asia", "subregion": "Southern Asia", "timezones": [ { "zoneName": "Asia\/Kabul", "gmtOffset": 16200, "gmtOffsetName": "UTC+04:30", "abbreviation": "AFT", "tzName": "Afghanistan Time" } ], "latitude": "33.00000000", "longitude": "65.00000000", "emoji": "🇦🇫", "emojiU": "U+1F1E6 U+1F1EB", "states": [ { "id": 3901, "name": "Badakhshan", "state_code": "BDS", "cities": [ { "id": 52, "name": "Ashkāsham", "latitude": "36.68333000", "longitude": "71.53333000" }, ....... /* very long list */ This file is loaded in Django forms when country/state/city dropdown lists are needed. The problem is that I want to translate at least the country names to other languages. Even if I was allowed to use {% trans "Country_name" %} in my JSon file it wouldn't be very practical. Is there a faster way to do so? For example making this in forms.py doesn't work: from django.utils.translation import gettext_lazy as _ # ... def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], _(x['name'])) all_countries.append(y) return all_countries "--- Select a Country ---" will be translated but … -
Python Raw Recursive Query Convert
cursor.execute("WITH recursive subordinates AS (SELECT 1 as id FROM NODES WHERE node_id ='" + str(document_node_edit) + "' UNION ALL SELECT e.* FROM NODES e INNER JOIN subordinates s ON s.parent_node::text = e.node_id::text)SELECT s.short_code, s.node_type FROM subordinates s where s.location_id='" + str(location) + "' and s.node_type=1") -
How to create one to one field with Django for existing table?
We already have a model, let's say, Product. And we want to extend it into 'one to one relationship', let's say, ProductDetails. How do it in such way, that for each existing row of Product model row ProductDetails is created automatically? with some default vaules. Does Django provide such tool? The task seems pretty regular for me, but I can't find any native solution. -
How to customise message in send_mail in django
I'm trying to customise the message which I want to send to a gmail, like you may have seen some emails having nice layout, buttons and images. I want customise my message like that. But I'm not getting how to do it in django. Can anyone guide me how to do it? I'd appreciate some suggestions. Thank you. -
How do I fix AttributeError: type object 'Book' has no attribute 'published_objects' on django_3.2
I am trying to create a custom model manager by modifying an already existing queryset. After adding the custom manager to my models.py file, models.py from django.db import models from django.db.models.fields import DateField from django.utils import timezone, tree from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Book(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) author = models.CharField(max_length=100) slug = models.SlugField( max_length=250, unique_for_date='uploaded_on') uploaded_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='book_posts') body = models.TextField() publish = models.DateField() uploaded_on = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published_objects = PublishedManager() class Meta: ordering = ('-category', ) def __str__(self): return self.title``` If I use the python manage.py shell to test I was able to retrieve all books using Book.objects.all() >>> Book.objects.all() <QuerySet [<Book: 48 Laws of Power>, <Book: The China Card>, <Book: Rich Dad, Poor Dad>]>``` But when trying to retrieve using my custom model, the is my following result >>> Book.published_objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'Book' has no attribute 'published_objects'``` How do I fix this error please, since i was following the original Django Documentations? -
Does the sync_to_async decorator really make django requests faster?
asgiref module has sync_to_async and async_to_sync function and decorator. I want to know if using sync_to_async this decorator can really make django requests faster,code like this: @csrf_exempt @sync_to_async def get_data(request): user_obj_qs = User.objects.all() user_list = [{'name': user_obj.first_name} for user_obj in user_obj_qs] return JsonResponse(user_list, safe=False) -
How to implements DataTable in a Django Project?
I'm new in Django framework and I'm trying to implement datatable into my project. I read the documentation of Django and Datatables and implemented exactly as stated, but somehow the datatable does not showing in the template and I don't know why. home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Django Project</title> {% include 'headers.html' %} {% include 'scripts.html' %} </head> <body class="hold-transition sidebar-mini layout-fixed"> <div class="wrapper"> {% include 'header.html' %} {% include 'sidebar.html' %} <div class="content-wrapper"> <section class="content-header"></section> <section class="content"> {% block content %} {% endblock content %} </section> </div> {% block javascript %} {% endblock %} {% include 'footer.html' %} <aside class="control-sidebar control-sidebar-dark"></aside> </div> </body> </html> headers.html {% load static %} <!-- DataTables --> <link rel="stylesheet" href="{% static 'lib/bootstrap-5.1.1-dist/css/bootstrap.min.css' %}" /> <link href="{% static 'lib/datatables-1.11.2/css/jquery.dataTables.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/dataTables.bootstrap4.min.css' %}" /> <link rel="stylesheet" href="{% static 'lib/datatables-1.11.2/css/responsive.bootstrap4.min.css' %}" /> <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback" /> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/fontawesome-free/css/all.min.css' %}" /> <!-- overlayScrollbars --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/plugins/overlayScrollbars/css/OverlayScrollbars.min.css' %}" /> <!-- Theme style --> <link rel="stylesheet" href="{% static 'lib/adminlte-3.1.0/css/adminlte.min.css' %}" /> scripts.html {% load static %} <script src="{% static … -
Limit number of images user can upload
I have a blog feature on my site, users can upload a single main image and multiple supporting images. The issue I am facing is I want to be able to limit the number of images a user can upload. I understand that I could use a for loop on it but if the user goes back later and adds more it would make the for loop useless. So I figured the best way to do this would be to add a field to the model that would count the number of images uploaded and then I can use an if statement to check if more than a said number of images have been uploaded. How would i go about getting the number of images and adding them to the post while it is being created. Or should I go about this a different way view @login_required def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Setting up gdal/osgeo Python library on Heroku
On my Windows machine, I have set up GDAL by following these instructions: downloading a wheel from Chris Gohkle's website and installing it using pip. pip install "C:/Users/andre/Downloads/GDAL-3.3.2-cp39-cp39-win_amd64.whl" This then gives me access to gdal like so: from osgeo import gdal How can I now re-create this for my Django App on Heroku? I have already followed the official Heroku instructions on installing GDAL with a buildpack. Although this is successful, I don't know how to install the osgeo library (and its gdal sub-module) on the remote Heroku machine. -
JavaScript only works on index.html in a Django web app
I recently started to integrate JavaScript into my Django projects. However, I am facing an issue: Whenever I try to animate an element by clicking on a button it works fine in the index.html but not on other templates that extend the layout.html. I am new to JavaScript so I couldn't trace back the roots of the problem. Here is my code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Meine Website</title> </head> <body> <div id="ball"></div> <button id="btnwow">Animieren</button> </body> </html> layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Layout</title> </head> <body> {% block body %} {% endblock %} </body> </html> thoughts.html {% extends 'website/layout.html' %} {% load static %} {% block body %} <div id="ball"></div> <button id="btnwow">Animieren</button> {% endblock %} script.js (in the same folder with anime.min.js) function animateStart(){ anime({ targets: '#topbar', translateY: [-500, 0], easing: 'easeInOutCirc', opacity: [.1, 1], … -
Question about Django. Assistance for the implementation of registration for the tournament
at the moment there are such models. class Team(models.Model): name = models.CharField('Название', max_length=35, unique=True) tag = models.CharField('Тег', max_length=16, unique=True) about = models.TextField('О команду', max_length=500, null=True, blank=True) logo = models.ImageField('Лого', upload_to="teams_logo/", null=True) game = models.ForeignKey( Game, verbose_name='игра', on_delete=models.SET_NULL, null=True, blank=True ) tournament = models.ManyToManyField('Tournaments', verbose_name='Турниры', blank=True) slug = models.SlugField(unique=True, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("team_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Team, self).save(*args, **kwargs) class Meta: verbose_name = "Команда" verbose_name_plural = "Команды" class Tournaments(models.Model): name = models.CharField('Название турнира', max_length=50) description = models.TextField('Описание турнира') prize = models.TextField('Призовой') game = models.ForeignKey( Game, verbose_name='Дисциплина', on_delete=models.CASCADE ) author = models.ForeignKey( User, verbose_name='пользователь', on_delete=models.CASCADE, blank=True, null=True ) teams = models.ManyToManyField( Team, verbose_name='Команда', blank=True ) image = models.ImageField('Лого турнира') max_teams = models.PositiveSmallIntegerField('Максимальное количество команд', default=0) count_registration_teams = models.PositiveSmallIntegerField('Количество зарегестрированных команд', default=0) start_date = models.DateTimeField("Дата начала") start_registration_date = models.DateTimeField("Начало регистрации") end_registration_date = models.DateTimeField("Конец регистрации") slug = models.SlugField(unique=True, blank=True, null=True) status = models.BooleanField('Статус активности', default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("tournament_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(f'{self.name} - {self.game}') super(Tournaments, self).save(*args, **kwargs) def get_tournament(self): return self.tournamentregistration_set class Meta: verbose_name = "Турнир" verbose_name_plural = "Турниры" class TournamentRegistration(models.Model): tournaments = models.ForeignKey(Tournaments, on_delete=models.CASCADE) teams = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) user … -
How to implement a generalized uniqueness DB constraint (A,B) and (B,A) in Django?
I want to check the database before an object is created with fields one='a' and two='b', and not create (throw an exception) if the database already has rows with fields one='b' and two='a' (reverse order). That is, guarantee that only one of (one, two) and (two, one) exists. It's like a generalized uniqueness constraint. I'm using Django 3.2. I see CheckConstraint supports a boolean Expression, and one type of expression is an aggregate. So I can imagine testing that the number of rows with (one, two) and (two, one) is at most 1. However, that sounds expensive, and I also don't see examples of how to use a Count in the CheckConstraint. Alternatively, I could implement a pre_save signal that issues a query. This seems better, as I'll have the data in hand to form the query. However, I don't see how to prevent the save using the pre_save signal. Does it have a return value I can use? I don't see that in the docs. I'm open to other ideas as well. -
Using django-hitcount in function-based view
I am trying to implement the logic used HitCountDetailView of django-hitcount module. I've successfully implemented it. My problem now is how can I make it count hit because now it counts one hit for each IP. Example. If I hit an object 5 times, it only counts the first one but I want it to count all. What do I need to overwrite? Below is my function def stats(request, watched_object): object = get_object_or_404(My_model, pk=watched_object.pk) context = {} hit_count = get_hitcount_model().objects.get_for_object(object) hits = hit_count.hits hitcontext = context['hitcount'] = {'pk': hit_count.pk} hit_count_response = HitCountMixin.hit_count(request, hit_count) if hit_count_response.hit_counted: hits = hits + 1 hitcontext['hit_counted'] = hit_count_response.hit_counted hitcontext['hit_message'] = hit_count_response.hit_message hitcontext['total_hits'] = hits return context -
Django filtering over multiple pages
I'm still new to Django and web development, sorry if the question is stupid. I currently have a search bar and a drop down list for a category, which then sends the query set to the results template. The result template also has filters to further refine The search, like price range, condition and for sorting. I was wondering what would be the best way to implement these filters without losing the query set from the previous page. views.py class ProductListView(ListView): model = Product template_name = "products/index.html" context_object_name = 'products' paginate_by = 10 class ProductSearch(ListView): model = Product template_name = "products/ad-list-view.html" context_object_name = "products" def get_context_data(self, **kwargs): context = super(ProductSearch, self).get_context_data(**kwargs) Product_list = super().get_queryset() context.update({ 'filter': ProductFilter( self.request.GET, queryset=Product_list) }) return context def get_queryset(self): search_query = '' if self.request.GET.get('search_query') or self.request.GET.get('category'): search_query = self.request.GET.get('search_query') option = self.request.GET.get('category') category = Category.objects.filter(Name__icontains=option) ducts = Product.objects.distinct().filter( Q(Product_name__icontains=search_query), category__in=category,) return ducts return search_query index.py <div class="container"> <div class="row justify-content-center"> <div class="col-lg-12 col-md-12 align-content-center"> <form method="GET" action="{% url 'Product-search' %}"> <div class="form-row"> <div class="form-group col-md-4"> <input type="text" class="form-control my-2 my-lg-1" id="inputtext4" placeholder="What are you looking for" name="search_query" value="{{search_query}}"> </div> <div class="form-group col-md-3"> <select name="featured" value= "{{featured}}" class="w-100 form-control mt-lg-1 mt-md-2"> <option value= null>Category</option> {% for … -
Debugging Django with VS Code inside a Docker container shuts down the container
I'm following this guide for debugging Django inside a Docker container using VS Code. The only difference I've made was changing ports to 8000 and host to 0.0.0.0 because my docker-compose has it like that. I have no idea why the web container shuts down when I run Django with a breakpoint inside a view because I'm don't really know where the problem is coming from. My only guess is from the vscode/launch.json file that is set up by the following: { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/usr/src/app" } ], "port": 8000, "host": "0.0.0.0", } ] } Any ideas why this is not working or where the problem is coming from? -
Using django url scheme with Javascript fetch API
I want to use django url scheme when working with fetch API, but it's not understood and i end up with an escaped URL. I followed this tutorial (in french sorry) in which the author achieve it very easily. Demonstrated here Example code : let url = "{% url 'myapp:search_user' %}" const request = new Request(url, {method: 'POST', body: formData}); fetch(request) .then(response => response.json()) .then(result => { console.log(result) }) Which ends up with a console error : POST http://127.0.0.1:8000/myapp/actions/%7B%%20url%20'myapp:search_user'%20%%7D 404 (Not found) Of course my URL is declared in url.py and works well when used in templates. If I replace "url" with relative path it's work well, but that's not django friendly. What I am missing ? -
"We're Sorry, Client not found" FreeIPA, Keycloak setup
I am setting up FreeIPA and Keycloak for user authentication for a django webapp. I have set up the client id and client secret in the .bashrc file and have included my path properly in django (the website loads, just not properly). The error displayed is "We're sorry, Client not found." I figure this may have something to do with setup. What should I do to fix this and make the ipa/keycloak login show the login fields? -
How to get uploaded file size in django
I am uploading a zip file through my form. How I can get the file size i.e in KB / MB so I can display it in my template. -
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites '
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites'. Django Music web App: I have added "Add to Favourite" feature, But Can't add "Remove from Favourite" feature Favourite.html <form action="/music/favourites" method="POST">{% csrf_token %} <input type="hidden" name="video_id" value="{{song.song_id}}"> <button type="submit" class="btn btn-outline-danger">Add to Favourite</button> </form> <form method="post"> {% csrf_token %} <input type="submit" class="btn btn-outline-danger" value="Remove from Favourites" name={{song.id}} > </form> #models.py class Song(models.Model): song_id = models.AutoField(primary_key= True) name = models.CharField(max_length= 2000) singer = models.CharField(max_length= 2000) tags = models.CharField(max_length= 100) image = models.ImageField(upload_to = 'docs') song = models.FileField(upload_to= 'docs') movie = models.CharField(max_length = 150, default = "None") def __str__(self): return self.name class Favourites(models.Model): watch_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) video_id = models.CharField(max_length=10000000, default="") #Views.py def favourites(request): if request.method == "POST": user = request.user video_id = request.POST['video_id'] fav = Favourites.objects.filter(user=user) for i in fav: if video_id == i.video_id: message = "Your Video is Already Added" break else: favourites = Favourites(user=user, video_id=video_id) favourites.save() message = "Your Video is Succesfully Added" song = Song.objects.filter(song_id=video_id).first() return render(request, f"music/songpost.html", {'song': song, "message": message}) wl = Favourites.objects.filter(user=request.user) ids = [] for i in wl: ids.append(i.video_id) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)]) song = Song.objects.filter(song_id__in=ids).order_by(preserved) return render(request, "music/favourite.html", {'song': song}) This function is …