Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium in django
How can we implement the selenium in django we want to implement in the views part that is logic part we want to write the selenium code but its happening that selenium code open the browser and backend render the webpage we getting the conflict part How can we solve it -
How to get the checked items(with jquery) in django view?
Here I have a list of checked items in the <ul id ='user-list'> section with the help of jquery. However I am not being able to get these checked items in my django view. template <ul class="approval approval_scrolltab mt-3" id="search_users_results"> {% include 'user_groups/ajax_user_search_results.html' %} </ul> <div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1"> <ul id="user-list" class="approval approval_scrolltab mt-3"> # here I have the checked items from jquery </ul> </div> ajax_user_search_results {% for user in users %} <div class="form-group"> <div class="checkbox"> <input data-name="{{user.first_name}" class="checkbox1" name="users" type="checkbox" value="{{user.pk}}" id="search-user{{user.pk}}"/> <label for="search-user{{user.pk}}"></label> </div> </div> views.py def create_user_group(request): users = get_user_model().objects.filter(is_active=True)[:10] form = CreateUserGroupForm() if request.method == 'POST': form = CreateUserGroupForm(request.POST) if form.is_valid(): group = form.save() users = form.cleaned_data.get('users') for user in users: user.groups.add(group) .... Script to display the checked users <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $('input[class="checkbox1"]').on('change', function() { var image_url = $(this).closest( '.approval--member' ).find( 'img' ).attr('src'); var name = $(this).closest( '.approval--member' ).find( '.approval--name ~ p' ).text(); if($(this).prop('checked')) { $('ul#user-list').append( '<li id="' + name + '">' + '<div class="approval--member">' + '<img src="' + image_url + '" class="user--image" />' + '<div class="w-100">' + '<h6 class="approval--name"></h6>' + '<p>' + name + '</p>' + '</div>' + '<span class="ic-close"></span>' + '</div>' + '</li>'); } else { $('ul#user-list #' + name).remove(); } How can … -
Django and javascript - how to use the value of dropdown box to access the static image stored on server using the static tag
{% load static %} line 1 <html> line 2 <head> line 3 <meta charset="UTF-8"> line 4 </head> <body> <select id="ddlViewBy"> <option value="Pranamasana.jpg">Pranamasana</option> </select> <img id='cat' crossorigin="anonymous" height = "620" width = "620"/> <button onclick = "myfun()">button</button> <script> function myfun() { var e = document.getElementById("ddlViewBy"); var strUser = e.options[e.selectedIndex].value; document.getElementById("cat").src = "{% static 'Pranamasana.jpg' %}"; line 16 } </script> </body> </html> Even though I have a drop down box I am hard coding the name of the image to be accessed in line 16. I want to know the way if I can use the string 'struser' so that the image selected by user can be displayed without hard coding. Any help would be appreciated and thanks in advance. I am using django and this is a html page in my project -
Django chicken and egg situation loading an app that references django modules
I have upgraded a Django app from 1.x to 2.2 but appear to be faced with a chicken and egg situation when trying to incorporate the django-permissions module [ https://pypi.org/project/django-permissions/ ] WHat seems to happen is that in attempting to load this app, Django tries to run its init.py code. But this contains imports of Django modules, which in turn calls the populate() method within Django, which (not unreasonably) complains that this method is not reentrant. Any ideas how to resolve this? I would like to take a fork of django-permissions and adapt it as nencessary to work with Django 2.2 (Rolling back to 1.x is not an option) Thanks in anticipation -
Which Type of Views I should use in Django?
There Are Three Types Of Views as far as I know. 1.Function-Based Views. 2.Class-Based Views. 3.Django Generic Views. Which Views Should I Use and Why Should I use. Thanks Good People. -
Django __in lookup doesn't look of None values
Consider I have a model called Subject, and I want to filter the values based on the list of values. Consider the below list. ["John", "Brad", None] When I try to filter out the result using __in lookup it doesn't look for None values. For example Subject.objects.filter(user__in=["John", "Brad", None]) This will provide the queryset for John and Brad but not None. What I'm missing here? Can anyone please help me -
Can I use the same directory for development and production in django docker?
I am developing a Django project. I am new to Docker and other related things to it. I was wondering if it is okay to use the same working directory for development and production in docker container. Thanks for your time and consideration. -
Display form if its value exists in db
views.py @login_required() def Info_anlegen(request, id=None): item = get_object_or_404(Kunden, id=id) kontaktform_form = InfoForm(request.POST or None, instance=item) if WindowsHome.objects.filter(KN=item.KN).exists(): item1 = WindowsHome.objects.get(KN=item.KN) winform_form = InfoWinForm(request.POST or None, instance=item1) if kontaktform_form.is_valid(): return redirect('/Verwaltung/KontaktAnlegen') else: form = acroniform(instance=item) return render(request, 'blog/infokontakt.html', {'kontaktform_form': kontaktform_form, 'winform_form': winform_form}) infokontakt.html {% extends 'blog/base.html' %} {% load bootstrap4 %} {% block supertitle %} InfoPage {% endblock %} {% block Content %} {% load static %} <html> <div class="p-2 mb-1 bg-white text-black"> <head> <div class="d-flex justify-content-center align-items-center container "> <img src="{% static 'blog/Gubler.jpeg' %}" alt="Gubler" height="300" width="700"> </div> </head> <br> <body> <form class="form-row" action="" method="post"> <div style="margin-left: 2.5em;"> <font color="black"> <div class="col-sm-10 col-form-label"> {% csrf_token %} {% bootstrap_form kontaktform_form %} </div> </font> </div> </form> <form class="form-row" action="" method="post"> <div style="margin-left: 2.5em;"> <font color="black"> <div class="col-sm-10 col-form-label"> {% csrf_token %} {% bootstrap_form winform_form %} </div> </font> </div> </form> My Problem is: if WindowsHome.KN exists it gets displayed but if it does not exist i get the error UnboundLocalError at /Verwaltung/InfoKontakt/6 local variable 'winform_form' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/Verwaltung/InfoKontakt/6 Django Version: 3.0.1 Exception Type: UnboundLocalError Exception Value: local variable 'winform_form' referenced before assignment How do i say that if the db entry does not exist it should not … -
How to include shingle elasticsearch filter in analyzer with Python elasticsearch_dsl
I am using elastic search for full text search in a Django application. I am using the elastic_dsl library from pypi to interface with the cluster. I am trying to implement a shingle filter in the analyzer. I believe I have gotten it to work with default values: from elasticsearch_dsl import analyzer, tokenizer main_analyzer = analyzer( 'main_analyzer', tokenizer="standard", filter=[ "lowercase", "stop", "porter_stem", "shingle" ] ) I would like to change the defaults. Eg, set max_shingle_size to 5 instead of the default 2. I cannot find the syntax for doing this. I have read the documentation, the examples in the Git repository, and some of the source code. -
Django ORM join on single table
I have SQL/ORM related question, there is one model NewsArticle with ~500k objects - querying on it causes some performance issues. Model more or less looks like this: Class NewsArticle(models.Model): date_published = models.DateTimeField() duplicates_group_id = models.UUIDField(blank=False, null=True) duplicates = models.ManyToManyField('self', blank=True) topic = models.ForeignKey('NewsTopic', on_delete=models.SET_NULL, null=True) online = models.BooleanField(default=True) ... What I need is to group by duplicates_group_id and iterate only on articles with lowest id from every matching duplcates_group. In SQL following query is quite fast(uses proper db indexes): SELECT l.`*` # fields dont matter now FROM `summarizer_newsarticle` l INNER JOIN (SELECT MIN(id) AS first_article_id FROM `summarizer_newsarticle` WHERE date_published >= '2019-12-02 00:00:00' GROUP BY duplicates_group_id) r ON l.id = r.first_article_id WHERE l.`online` = 1 AND l.`topic_id` = 5 In View for displaying those articles in get_queryset method I struggle to prepare proper query. Also raw SQL didnt solve the issue because get_queryset expects returning queryset object. Without sufficient SQL queries performance is really bad Do you maybe have an idea if its even possible to reproduce such query or to do it different way? Thank you -
How to use Token keyword instead of default Bearer in token authentication OpenApi 3.0 swagger?
I am writing documentation for an API developed on Django+DRF, that uses token authentication. And in header uses this patter Authorization: Token <token> but in OpenApi 3.0 there is only Bearer keyword to use with token. I couldn't find answer in documentation. Is there any way to specify keyword for header? Note: I know that I can change keyword in DRF authentication method but I cannot do that because the project is on the production and frontend depends on it. -
Custom validator breaks password change form
We are attempting to add a custom validator to our password reset page. Below is a simplified version of what we have implemented. However, there seems to be an unusual side effect in the form that renders the password reset page. I am expecting 3 fields, old_password, new_password1 and new_password2, but new_password1 is not rendered on the page. We are using almost all of the default Django password change functionality, as can be seen in views.py below. If the validator is removed from settings, the form works as expected. Why is the validator breaking the form? myvalidator.py import re from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ class MyValidator(object): message = _("Password is not complex enough (%s)") code = "complexity" def __init__(self, complexities=None): self.complexities = complexities def validate(self, password, user=None): errors = [] if password == '12345678': errors.append(_("Password must be 12345678")) if errors: raise ValidationError(self.message % (_(u'must contain ') + u', '.join(errors),), code=self.code) def get_help_text(self): return _( "Your password must contain 12345678" ) views.py class PasswordChangeView(views.PasswordChangeView): template_name = 'accounts/password_change.html' settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
How to send data to view from values table in django table
I am developing django app. I need to send data in my table below to the view. I used data from db to table and now i want to submit these data with remark. And i have to update some other db tables using this values too. <form method="POST">{% csrf_token %} <th scope="col">Cheque No</th> <th scope="col">Date Created</th> <th scope="col">Name</th> <th scope="col">Amount</th> <th scope="col">Remark</th> <th scope="col">Action</th> </tr> </thead> <tbody id="myTable"> {% for instance in queryset%} <tr> <td>{{instance.cheque_no}}<input type='hidden' name='cheque_no' id="cheque_no{{instance.cheque_no}}" value='{{instance.cheque_no}}'><input type='hidden' name='id' value='{{instance.id}}'></td> <td>{{instance.date_created}}<input type='hidden' name='date' value='{{instance.date_created}}'></td> <td>{{instance.contributor_id}}<input type='hidden' name='contributor_id' value='{{instance.contributor_id_id}}'></td> <td>{{instance.total_amount}}<input type='hidden' name='total_amount' value='{{instance.total_amount}}'></td> <td><input type="text" name="remark" class="vTextField form-control" maxlength="20" id="id_remark" ></td> <td> <div class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <input type="submit" class="btn btn-primary btn-sm " style="height: 1.8rem; font-size: .85rem;" role="button" value="Cancel" name='cancel'> <input type="submit" class="btn btn-primary btn-sm " style="margin-left:10px; height: 1.8rem; font-size: .85rem;" value=" View Payment Details" role="button" href='#'> <!-- <a class="form-control btn btn-primary btn-sm" role="button" href='/{{instance.lot_seq_no}}/deleteChequelot/'>Delete</a> --> </div></div> </td> </tr> {%endfor%} </tbody> </table> <input type="text" name="remark_all" placeholder="Remark"> <input type="submit" value="Cancel All" name="cancel_all" class='btn btn-primary'> </form> -
Django: Check if object is last linked one to another
I'm writing a delete function in django (python). I need to delete a Site. A Site can be linked to multiple Groups. Before the Site can be deleted, I have to check if the Site is the last Site from a Group. I'm thinking of how to do this the most efficiently. Should I query for all the Sites for all the groups to which the site is linked, before I delete the site and check if the site is the only linked one? site = get_object_or_404(Site, pk=site_pk) group = Group.objects.prefetch_related("user_site").filter( user_site__site_id=site_pk ) site.delete() -
Nginix configuration for django nuxt app with docker hosted on ec2
I have a dockerized app that works fine in development mode on my host machine. I'm trying to figure out how I can host my app on ec2 using the default ip address created when I launch my instance. My folder structure is as follows. backend |---projectname |---Dockerfile |---requirements.txt |---wait-for-it.sh config/nginx |---app.conf frontend |---nuxt folders |---Dockerfile This is my current docker compose file I'm using docker-compose.yml version: '3.4' services: db: restart: always image: postgres volumes: - pgdata:/var/lib/postgresql/data env_file: .env ports: - "5432:5432" expose: - 5432 redis: restart: always image: redis volumes: - redisdata:/data django: build: context: ./backend env_file: .env command: > sh -c "./wait-for-it.sh db:5432 && cd autobets && python manage.py collectstatic --noinput && gunicorn --workers=2 --bind=0.0.0.0:8000 autobets.wsgi:application" ports: - "8000:8000" volumes: - ./backend:/app depends_on: - db restart: on-failure nuxt: build: context: ./frontend environment: - API_URI=http://django:8000/api command: bash -c "npm install && npm run dev" volumes: - ./frontend:/app ports: - "3000:3000" depends_on: - django - redis volumes: pgdata: redisdata: config/nginx/app.config upstream django { ip_hash; server django:8000; } upstream nuxt { ip_hash; server nuxt:3000; } server { location ~ /(api|admin|static)/ { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location / { proxy_pass http://nuxt; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; … -
How do i display all users profile pictures in template
I have been able to add an image field in Profile, and also i created users and attached an image to all my users profile. Now, how do i display all users profile pictures in template. I try this: profile_img = Profile.objects.filter(user=request.user.id) but it display the current login user profile picture in all users profile picture. I want to display all profile pictures for each user in template. class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', blank=True) def home(request): profile_img = Profile.objects.filter(user=request.user.id) print(profile_img) {% for profile in profile_img %} {% if profile.profile_pic %} <img src="{{ profile.profile_pic.url }}" class="rounded-circle avatar-img z-depth-1-half mb-3 mt-1" height="55" width="55" style="border:none;padding:0px;"> {% endif %} {% endfor %} -
CUSTOM USER MODEL IN DJANGO REST FRAME WORK
i had create a custom user model in django the issue is that i am not able to login in admin panel i don't understand what is the issue i had create a serialzer class Class Custom(serial.ModelSerial): all field, class Meta: all field but when i going to login it will not recognise my id and password and giving error that wrong id and password i had created is_staff,is_admin,first_name,last_name all the method is created in my model -
How to use Pyrebase Stream handler with django
I want to use Pyrebase stream handler, to get realtime changes in my firebase using django server. Below is a code which is running on Jupyter notebook firebase_config = { "apiKey": "####", "authDomain": "####", "databaseURL": "####", "storageBucket": "####", } def stream_handler(response): print(response) firebase = pyrebase.initialize_app(firebase_config) db = firebase.database() my_stream =db.stream(stream_handler) while True: pass But when i put the code in django app.views (excluding while statement), it doesn't capture anything. How to reslove it? -
Nginx without static files (Django + Gunicorn)
I launch the site on VM (localnetwork, Ubuntu 18 LTS). But the admin panel works without static files. Settings Django: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = "/home/portal/static/" After command 'manage.py collectstatic' static files created here: There is also a static folder in the project root, but it is empty. File contents new_portal: server { listen 80; server_name 10.0.0.18; location = /favicon.ico {access_log off;log_not_found off;} location /static { alias /home/portal/static; expires max; } location /media/ { root /home/portal/my_django_app/new_portal; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}} gunicorn.conf: bind = '10.0.0.18:8000' workers = 3 user = "nobody" Tell me where is the error? Is there something wrong with Gunicorn? If something else is required (code or screen) - I will attach it upon request. -
How to create a product successfully using woo commerce api with python
I am trying to create / update products from my django app to my website. The problem I am facing with is that i can not create the product from my django to the website using the woo commerce api. The update procedure works. Here is my code: def create_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id): data = { "name": name, "sku": fetched_sku, "images": [ { "src": fetched_url }, ], "short_description": short_description, "description": description, "categories": [ { "id": woo_commerce_category_id } ], } #post data to the woocommerce API wcapi_yachtcharterapp.post("products",data).json() print(" 3A STEP - WOO PRODUCT CREATED IN THE SITE") def update_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id,post_id): data = { "name": name, "sku": fetched_sku, "images": [ { "src": fetched_url }, ], "short_description": short_description, "description": description, "categories": [ { "id": woo_commerce_category_id } ], } #put data to the woocommerce API wcapi_yachtcharterapp.put("products/"+str(post_id),data).json() print(" 3B STEP - WOO PRODUCT UPDATED IN THE SITE") Here is the part of code, calling the above functions based on the response: r=wcapi_yachtcharterapp.get("products/?sku="+fetched_sku).json() if len(r) > 0: #if it exists in the website , take the post id post_id=r[0]['id'] if len(r) == 0: #call the create create_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id) product.is_stored_to_website = True product.save() print("Stored : {} \n".format(product.is_stored_to_website)) else: #call the update update_woocommerce_product_individually(wcapi_yachtcharterapp,name,fetched_sku,fetched_url,short_description,description,woo_commerce_category_id,post_id) product.is_stored_to_website = True product.save() print("Stored : {} \n".format(product.is_stored_to_website)) I read … -
NoReverseMatch at / Error during template rendering
when i opens http://127.0.0.1:8000/ which is home.html, Iam getting NoReverseMatch at / and *Reverse for 'exam-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['exam/(?P[^/]+)$'] Iam thinking the error is due to in urls.py. The following is urls.py file from . import views from .views import ExamListView, ExamDetailView app_name='map' urlpatterns = [ path("", ExamListView.as_view(), name='map-home'), path("exam/<str:pk>", ExamDetailView.as_view(), name="exam-detail"), path("login_student/", views.login_student, name='map-login'), path("register_student", views.register_student, name='map-register'), path('add_student/', views.add_student, name='add_student'), path('front/', views.front, name="front"), ] models.py file subject = models.TextField(primary_key = True, unique = True) def __str__(self): return self.subject home.html {% extends "map/base.html" %} {% block content %} <p>WELCOME HOME</p> {% for exam in exams %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'map:exam-detail' exam.subject %}">{{ exam }} </a> </div> </div> </article> {% endfor %} {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'map/main.css' %}"> {% if title %} <title>{{ title }}</title> {% else %} <title> MAP PAGE </title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">Project M.A.P</a> … -
How to Add custom urls to oscar API documentation page(API root)
I have a Django oscar application and I use django-oscarapi for my custom APIs. I have created an app(api), and in that app, I have included the oscarapi.url, which is showing me the URLs for oscarapi. However, I have added a custom, viewset for registration that I call 'users', I also want to display that users in the same list as of oscarapi's. i.e I want to add some more URLs to the same list....how can I add it to get displayed as other API hyperlink on the API ROOT page e.g http://127.0.0.1:8000/api/users/ i am able to access the users URL, but it is not getting displayed in the list of all APIs. How can I do it? https://prnt.sc/r792or api/urls.py router = routers.DefaultRouter() router.register(r'users', UserCreateAPIView) urlpatterns = [ #oscarapi default urls path(r'', include("oscarapi.urls")), #custom url path(r'', include(router.urls)), ] -
Python, return html file generated by business logic in django rest framework
I'm trying to create a Rest API that can receive data from a user, run some business logic on it and return as a response an HTML File that is generated based on the data passed in. # models.py from django.db import models from django.utils import timezone from django import forms # Create your models here. areas = [ ('210', '210'), ('769', '769'), ('300', '300') ] class LocationInfo(models.Model): latitude = models.FloatField(name="GDT1Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) longitude = models.FloatField(name="GDT1Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=1) gdt2_lat = models.FloatField(name="GDT2Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) gdt2_lon = models.FloatField(name="GDT2Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lat = models.FloatField(name="UavLatitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_lon = models.FloatField(name="UavLongitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) uav_elevation = models.FloatField(name="UavElevation", max_length=100, default=1, blank=False, help_text="Enter the above ~Sea Level~ planned uav Elevation. " ) area = models.CharField( max_length=8, choices=areas, ) date_added = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'date_added' … -
Multiple forms on one page Django
How can I add several forms per page? My code currently only displays one form, how do I add another form to my code? class OrderUpdateView(UpdateView): model = Order template_name = 'order_update.html' #in this expample only one form form_class = OrderEditForm def get_success_url(self): return reverse('update_order', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) instance = self.object qs_p = Product.objects.filter(active=True)[:12] products = ProductTable(qs_p) order_items = OrderItemTable(instance.order_items.all()) RequestConfig(self.request).configure(products) RequestConfig(self.request).configure(order_items) context.update(locals()) return context -
The view course.views.coursehome didn't return an HttpResponse object. It returned None instead
Unable redirect the "return redirect(reverse('detail', kwargs={"id": instance.id}))" page. enter image description here @login_required(login_url="/login/") def coursehome(request,courseid): courseid=get_object_or_404(CourseId,courseid=courseid) instance=get_object_or_404(CourseDetails,courseid=courseid) scorm_type=get_object_or_404(scormcontent,courseid=courseid) cohome=CourseDetails.objects.filter(courseid=courseid) scormcourse=scormcontent.objects.filter(courseid=courseid) course_enroll=Enrollment.objects.filter(courseid=courseid) student_data=course_enroll.filter(student_id=request.user.id) user_id=str(request.user.id) if request.user.is_authenticated: for student in course_enroll: if user_id in student.student_id: home={ 'courseid':courseid, 'cohome':cohome, 'scormcourse':scormcourse, 'student_data':student_data, "scorm":scorm_type, } return render(request,'course_home.html',home) else: return redirect(reverse('detail', kwargs={"id": instance.id})) else: return redirect('/login')