Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error retrieving access token: b'{\n "error": "redirect_uri_mismatch",\n "error_description": "Bad Request"\n}'
Trying to authenticate from Nuxt App using Django rest + allauth + dj-rest-auth First Error allauth.socialaccount.models.SocialApp.DoesNotExist: SocialApp matching query does not exist. resolved this by changing SITE_ID = 1 TO 2 Second I am getting This error Traceback (most recent call last): File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 48, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 138, in post self.serializer.is_valid(raise_exception=True) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation value = self.validate(value) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\registration\serializers.py", line 117, in validate token = client.get_access_token(code) File "C:\Users\xyz\django-env\lib\site-packages\allauth\socialaccount\providers\oauth2\client.py", line 91, in get_access_token raise OAuth2Error("Error retrieving access token: … -
change django view context based on template
I'm wondering if there is a way to change django view context based on template (I've no idea if it's possible) I'm building a chat application where I loop through all the thread messages and I'm looping through all images that if the image message id equals to message id to show the message related image. It's something like this .. {% for message in chatmessages %} <p>{{ message.message }}</p> {% for img in images %} {% if img.message.id == message.id %} <img src="{{ img.image.url }}"> {% endif %} {% endfor %} {% endfor %} and the same for attachments. I'm sending these context from my view context = { "me": me, "threads": threads, "other_user": other_user, "chatmessages": ChatMessage.objects.filter(thread=thread.id), "images": MultipleImage.objects.all(), "attachments": MultipleAttchment.objects.all(), } Any better way to reduce my looping in template for a better functionality. here is my models.py ... class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True) class MultipleImage(models.Model): message = models.ForeignKey('ChatMessage', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_img_dir, blank=True, null=True) class MultipleAttchment(models.Model): message = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) attachment = models.FileField(upload_to=upload_att_dir, blank=True, null=True) ... looking for a better way :( -
how to change innerHTML using classname inside loop
here my code i just wanna change the innerHTML of btn by grabbing classname which is inside for loop {% for pbyid in productbyid %} <div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'> <div> <div> <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a> <span class="top-left">{{pbyid.discountpercentage}}% off</span> </div> <div class="card-body"> <h5 class="card-title cardtitle">{{pbyid.title}}</h5> <div><p class="carddesccrip">{{pbyid.desc}} </p></div> <div class='pricce_card'> <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span> <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span> </div> </div> <div class="card-body"> {% comment %} /viewpage/{{pbyid.id}} {% endcomment %} <p href="" id='' class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction({{pbyid.id}})" > Add to cart <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></p> </div> </div> </div> {% endfor %} js how can i change html of btn from class , when i try it doesn't wok with classname but it work with id , but for id is specific so we have to use classname but i'm not exactly getting how to solve can anyone have idea to solve it function myFunction(id) { var x = document.getElementsByClassName("caddtocart"); x.innerHTML = "added"; console.log(id); } </script> -
Mac filtering on Django?
Is there a package or how to?, on Django that allows to whitelist a mac address that stored on a model. class mac_address(models.Model): mac_address = models.CharField(max_length=17) That only listed mac addresses are only able to access the webapp, since IP whitelisting is kinda complicated because it's changes from time to time. -
Django - Annotate with first filtered related object
Having models: class Book(models.Model): name = models.CharField(max_length=255) class Page(models.Model): text = models.TextField() page_number = models.PositiveSmallIntegerField() book = models.ForeignKey(Book, on_delete=models.CASCADE) I want to annotate books with selected_page based on changing page number, books that doesn't have required page number will have book.selected_page = None: page_number = get_page_number() books = Book.objects.annotate(???) # smthing like: Book.objects.annotate(selected_page=Page.objects.filter(page_number=page_number)) for book in books: if book.selected_page: print(book.selected_page.text) -
Cannot use 'in' operator to search for 'length' in 'id_cliente'
I am trying to add the sale of products to the database but it turns out that when I try to do it I get the following error: jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 'id_cliente' I had to add some lines to the ajax code because otherwise another error would appear I hope you can help me JS $('form').on('submit', function (e) { e.preventDefault(); ventas.items.id_cliente = $('input[name="id_cliente"]').val(); ventas.items.fecha_venta = $('input[name="fecha_venta"]').val(); ventas.items.forma_pago = $('input[name="forma_pago"]').val(); ventas.items.precio_total = $('input[name="precio_total"]').val(); var parametros = new FormData(); parametros.append('action', $('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); submit(window.location.pathname, parametros, function () { location.href = 'crear_venta'; }); Views def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter( nombre__icontains=request.POST['term'])[0:10] for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) elif action == 'add': #vents = request.POST['ventas'] ventas = json.loads(request.POST['ventas']) print(ventas) venta = Venta() venta.id_cliente = int(ventas['id_cliente']) venta.id_empleado = int(ventas['id_empleado']) venta.fecha_venta = ventas['fecha_venta'] venta.forma_pago = ventas['forma_pago'] venta.precio_total = float(ventas['precio_total']) venta.save() for i in ventas['productos']: detalle_venta = Detalle_Venta() detalle_venta.id_detalle_venta = venta.id_venta detalle_venta.id_producto = int(i['id_producto']) detalle_venta.cantidad = int(i['cantidad']) detalle_venta.subtotal = float(i['subtotal']) detalle_venta.save() else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) … -
How to correctly represent a "warehouse" in django - n+1 problems
I'm learning Django. I am trying to make an app for managin a warehouse that's composed by simple elements: Involved models are transaction, items, warehouses and homes. models.py: class Home(Model): name = models.CharField(max_length=255, verbose_name=_('name'),blank=False) class Warehouse(Model): name = models.CharField(max_length=255, verbose_name=_('name'),blank=False) class Item(Model): name = models.CharField(max_length=255, verbose_name=_('name'), whouse = models.ForeignKey('Warehouse', blank=True,null=True,on_delete=models.CASCADE, related_name='all_items') quantity = models.PositiveSmallIntegerField(verbose_name=_('Quantity'), default=1, blank=False) @cached_property def count_remaining(self): remaining = self.quantity qs = self.transactions.all() if qs: out = qs.aggregate(Sum('quantity'))['quantity__sum'] if out: remaining -= out return remaining class Transaction(Model): item_field = models.ForeignKey('Item', blank=True,null=True,on_delete=models.CASCADE, related_name='all_transactions') home_field = models.ForeignKey('Home', blank=True,null=True,on_delete=models.CASCADE, related_name='all_transactions') quantity = models.PositiveSmallIntegerField(verbose_name=_('Quantity'), default=1, blank=False) item_list.html (for the generic ListView, with qs=Item.objects.all()): ... <table> <thead> <tr> <td>name</td> <td>quantity</td> <td>remaining items</td> <td>whouse</td> </tr> </thead> <tbody> {% for item in item_list %} <td>{{ item.name }}</td> <td>{{ item.quantity }}</td> <td>{{ item.count_remaining }}</td> <td>{{ item.whouse }}</td> {% endfor %} </tbody> </table> ... Now my problem is that my count_remaining method is being called one time for each object in the queryset, obviously resulting in an exponential number of database hits when there are many items in item_list. How can I make this arithmetical operation without hitting the db so much, provided that I must have a page that displays in the template the remaining items … -
Why I am getting Error 404 at Admin /Django
How can I fix this error: Page not found (404) You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It's my urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('pages.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django, How to filter this case?
class SomeConnect(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='sc_user') some = models.ForeignKey(Some, on_delete=models.CASCADE, null=True, blank=True, related_name='sc_some') class UserFollow(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='c_user1') user2 = models.ForeignKey(Some, on_delete=models.CASCADE, null=True, blank=True, related_name='c_user2') I want to find User Queryset on condition: User.objects.filter(someconnect's some is some1, someconnect's user=user_connect's user1 and user1 is followed by user2 has priority) example) In this case, UserFollow's user2 is kippling someconnect1 -> (user is jessica1, some is food) userfollow -> (user1 is jessica1, user2 is kippling) someconnect2 -> (user is jessica2, some is food) userfollow -> (user1 is jessica2, user2 is no_kippling) #Here is different someconnect3 -> (user is jessica3, some is food) userfollow -> (user1 is jessica3, user2 is kippling) so that I want to get queryset like(jessica1, jessica3, jessica2) Because jessica is not followed by kippling but no_kippling. How to filter it? -
Frequency of Django settings loading and initialization in a uSWGI + Django setup
I have a Django app running with uWSGI and wanted to understand how Django settings are loaded and re-initialized. uWSGI config has the following settings: ... max-requests = 5000 workers = 8 enable-threads = true ... So in terms Django settings (and the whole app for that matter), do the settings get initialized once every 5000 requests when a worker is being recreated ? -
Is it good practice to add .git folder to Github?
After i entered git init I have directory D:myproject\.git Is it good to add .git folder it in Github or should i add it in .gitignore? -
Interlinking records in a many-to-many field doesn't appear toaccept multiple records
I have this model for a tune: class MsTune(models.Model): name = models.CharField(max_length=255) ms = models.ForeignKey(Manuscript, on_delete=models.CASCADE, related_name="mstunes") concordances = models.ManyToManyField("self", blank=True) I have many manuscripts (ms), and the same tune might appear in more than one manuscript. What I want to do, with that concordances field, is link all the similar tunes. This works, in part. The Django administration back-end allows me to select many tunes to be linked to the current one I'm editing: The problem is that I'd like to see ALL the tunes I've linked in each of the tune. For instance, in the example above, Mary Scott... should list all three tunes (Courante, Almain, Hopetounsetc...); Courante should list the other three (Mary Scott, Almain, Hopetoun's). Right now they only show one. What am I missing? Do I have to create a new concordances model? -
How to limit calls to external API in django
I have an app that displays all the posts of a YouTube-Channel. For that, I use the youtube-API v3 which I call in my views.py. I then save all the data in my database which I pass as context to my render-function: return render(request, "blog/home.html", context) I was wondering if it's possible to only call the API if the last API-call was 5 minutes ago and just use the data in the database otherwise. One idea I have is to save the current datetime to a file whenever an API-call is made, and whenever the views-function is called, compare the current datetime with the one in the file. However, this seems inefficient and I was wondering if there was a better way. -
Visual tree representation After filtering
I'm working on a Django app, I want to make some kind of tree of nodes and leafs like this example. How I can implement that using html-css-javascript ? Is there any library or framework that helps ? -
Calling a DRF API via javascript: properties may not be accessed on strict mode functions
I have a very simple model which I call via javascript unsuccessfully: model: class Product(models.Model): name = models.CharField("name", max_length = 32, unique = True) file = models.ImageField(upload_to = "images") view: class ProductDataViewSet(viewsets.ViewSet): def list(self, request): query = Product.objects.all() results = PSerializer(data = query, many = True) results.is_valid() return Response(data = results.data) Serializer: class PSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["pk", "name", "file"] api call: var testing = async function() { const data2 = await $.ajax({url: "api/pds/"}); console.log(data2) } This returns me: django restframework "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them but ONLY when I call it via await. If I just go to 127.0.0.1:8000/api/pds i get a correct output: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "pk": 2, "name": "cafe pic", "file": "/media/images/cafe_2020.bmp" }, { "pk": 3, "name": "test pic", "file": "/media/images/test.bmp" } ] I have no idea what goes wrong why. I have a multiple similar API endpoints within the same app that work just fine, as long as I do not choose this model. The only difference is the models.ImageField(upload_to = "images") - I know when … -
ckeditor mardown bar showing in admin page but not in htm template
im trying to include ckeditor ,which work in the admin page perfectly but not showing the mardown bar at all in a regular template with a form <form method="post"> {{ form.as_p|safe}} {{ form.media }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> the markdown from my admin page on the same form is workin as expexted. seems like this line {{ form.media }} isn't working , any idea why ?? -
Unable to display image in django when the url is correct
I'm new to Django. In my app, I'm working on an image uploading and displaying function. I have tried setting up the MEDIA_URL and Media_ROOT. I also add the static path to the urls.py file and make sure that in HTML template object.image.url is used. However, the image is not displayed. Any help is greatly appreciated! My code is as followed: urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class ListingForm(ModelForm): def __init__(self, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) class Meta: model = Listing fields = ['title', 'description', 'current_price', 'image', 'category'] def index(request): return render(request, "auctions/index.html", { "active_listings" : Listing.objects.all() }) def createListing(request): if request.method == "POST": listing_data = ListingForm(request.POST, request.FILES) if listing_data.is_valid(): title = listing_data['title'] description = listing_data.cleaned_data['description'] current_price = listing_data.cleaned_data['current_price'] if listing_data.cleaned_data['image']: image = listing_data.cleaned_data['image'] else: image = None category = listing_data.cleaned_data['category'] listing = Listing(title=title, description=description, current_price=current_price, image=image, category=category) listing.save() return HttpResponseRedirect(reverse("index")) return render(request, "auctions/createListing.html", { "listingForm" : ListingForm() }) models.py class Listing(models.Model): class Category(models.TextChoices): FASHION = 'FA', _('Fashion') TOYS = 'TO', _('Toys') ELECTRONICS = 'EL', _('Electronics') HOME = … -
assign task no to the current user in viewflow
I have been using viewflow for a while, and I managed to create my process without any problem. But now I need someone to review the work from someone else. I don't want to create roles for that simple task, because I want everybody to be able to review somebody's work at any time. In other words, there is one task (task1) that can be executed for everybody, but it cannot be executed for the same person that finished the previous task. task1 = ( flow.View( UpdateProcessView, fields=["quality_check", "quality_check_comments"], task_description="writte comments" ).Permission( auto_create=True ).Next(this.task2) ) task2 = ( flow.View( UpdateProcessView, fields=["quality_check_completed"], task_description="Perform a quality control on the work instructions" ).Permission( auto_create=True ).Next(this.check_qa_manual) ) From Django-viewflow how to get the current user? I understand that I can assign the task to the user that created the task or the owner of a previous task, but I want the contrary. Is there a way to say .Assign(this.start.(not)owner) or .Assign(this.start.(not)created_by) ? -
django: user activation during email confirmation
Unfortunately. user is not going to be activate views.py: code = random.randint(1000, 9999) def register_view(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] password1 = request.POST['password1'] email = request.POST['email'] global user user = User(email=email, username=username) user.set_password(password) else: ... again views.py another def def email_activation(request): if request.method == "POST": global code email_activation = request.POST['email_activation'] if str(email_activation) == str(code): user.is_active = True return redirect('account') else: ... please help me -
"Django" Add friend request error (No User matches the given query)
I am trying to add a button to send a friend request to another user, but I keep getting the error (No User matches the given query). I have a 'Add Friend' button on the profile.html page of the user which works fine, I can't figure out what is going wrong, but on the users_list.html, the button comes back with this error. I'm still new to Django and learning, so would appreciate any help. error : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/users/friend-request/send/2/ Raised by: users.views.send_friend_request No User matches the given query views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Profile from feed.models import Post from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.conf import settings from django.http import HttpResponseRedirect from .models import Profile, FriendRequest from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm import random from django.core.mail import send_mail @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user in users: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends+=friend my_friends = request.user.profile.friends.all() for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = … -
Django is appending unwanted characters to Imagefield name attribute
I am writing a test for my Imagefield model that checks its relative path name, but it is not passing because the __str__ method returns the file path + some unwanted characters. For example, a file created as test_image.png is returned as test_image_ak0LKei.png, despite the fact that I am explicitly defining the file name. Every time a new file is created the appended part changes, it can return test_image_HqOXJc4.png, for example. This only happens when I am creating a dummy image file for the tests. When I upload a real image in Django's admin, it just returns the file path without any modifications. I am using Sqlite for tests and Postgres for the development, as the development database is in Heroku and it does not allow table creation I tried to change how I create the dummy file, like using a bytes object, using b64decode() with SimpleUploadedFile() from django, but the results are the same. My models: class Image(models.Model): image = models.ImageField(upload_to='post_images/') alt_tag = models.CharField(max_length=125, blank=True) def __str__(self): return self.image.name My test. The last thing I tried is using the static method below: class ImageTestCase(TestCase): @staticmethod def get_image_file(name='test_image.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = PIL_IMAGE.new("RGBA", … -
Django: Add subquery to a nested model
I have the following models in my project. An SRV contains many projects, and each project contains several tasks. I am detailing each SRV in a template and showing a list of all associated projects. class Srv(models.Model): srv_year = models.CharField(max_length=4) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null=True, blank=True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, blank=True) state = models.BooleanField(blank=True, null=True, default=False) in views.py I want to get the completed tasks associated with each project, but I always get all the tasks associated with all projects from the SRV (main model) queryset = Srv.objects.annotate( todo_done=Round(Count('project__todo', filter=Q(project__todo__state=True)) * 100.0 / Count('project__todo')), ) How can I send a new data to the project list contained in an SRV? -
Invalid block tag on line 10: 'static'/css/all.css''. Did you forget to register or load this tag?
am getting Invalid block tag on line 10: 'static'/css/all.css''. Did you forget to register or load this tag? when i run my django app. here is my code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static'/css/all.css'%}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static'/css/bootstrap.css'%}"> <!-- Custom --> <link rel="stylesheet" href="{% static'/css/style.css'%}"> <title>BT Real Estate</title> </head> here is my static settings STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [`enter code here` os.path.join(BASE_DIR, 'btre/static') ] -
how to pass django view data in js to get product id accordingly
the problems is i have passing data from view to product template , when i click add to cart i have to get product id accordingly using js how can i do this inside templates it work but when i apply inside script it doesn't work is there any method to access / get data my views.py def product(request): productbyid = None categories = ProductCategory.get_all_categories() products = TopList.get_all_products() categoryID = request.GET.get('category') if categoryID: productbyid =TopList.objects.filter(category=categoryID) else: productbyid = TopList.get_all_products() data = {} data['categories']:categories data['productbyid'] =productbyid data['products'] = products data['categories'] =categories return render(request,'product.html',data) my product.html % for pbyid in productbyid %} <div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'> <div> <div> <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a> <span class="top-left">{{pbyid.discountpercentage}}% off</span> </div> <div class="card-body"> <h5 class="card-title cardtitle">{{pbyid.title}}</h5> <div><p class="carddesccrip">{{pbyid.desc}} </p></div> <div class='pricce_card'> <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span> <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span> </div> </div> <div class="card-body"> {% comment %} /viewpage/{{pbyid.id}} {% endcomment %} <button href="" class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction()" > Add to cart {{pbyid.id}} <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></button> </div> </div> </div> {% endfor %} js , my try here i when i click caddtocart btn i have to get product id accordingly … -
Django: Access custom login page along with AD authentication
I am writing a Django application for a company and they have requested me to integrate AD authentication as they already have groups in their Active Directory for all their tasks. I have found a potential solution here: Automatic Login in a Django Application Using External Authentication (It is not yet tested for production) Now, the problem that I am facing is that I can't access the custom/Django's default login system. I need the custom page in case someone outside the AD group wants to access the application (approved by the company). How can I access the login page, in case there is no AD group member logged in?