Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install mysql-python fails with missing config-win.h
The python command is pip install mysql-python The full error is _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory Can someone please tell me how to fix this error? What exactly is mysql-python and how is it different from regular mysql? Another stack overflow post suggested installing it with a setup executable, where can I find this? I installed something called mysql python connector from here: https://downloads.mysql.com/archives/c-c/ It installed into C:\Program Files\MySQL\MySQL Connector C 6.1 However, I cannotfind mysqld executable anywhere in this folder -
Django 3.0.5 connection trouble to sql server 2012
I am trying to connect Django 3.0.5 to SQL server 2012 and I went through lots of posts on various websites. they mostly said that use "django-pyodbc-azure" but when I go to download that i found out it supports only django 2.1 so is there any other tool or something i am missing or i need to actually do my work only in django 2.1? -
Cannot navigate in django url smoothly
I am making a web app in django ,i have set the url path in "urls" file of the app and also set views but the problem is that when i click the menu items once it works , now when i am on that page when i click it some other button or even reclick the same menu option it gives an error , it seems like its not routing properly . i have to go back to home and then go to some other url... when first time i click menu item ( http://localhost:3000/chest/ ) route sets like this. when i click menu item in the new page it appends to the route like this ( http://localhost:3000/chest/bicep ) instead of this ( http://localhost:3000/bicep/ ). Code: urls.py from django.contrib import admin from django.urls import path from . import views # from django.conf.urls import url urlpatterns = [ path("", views.home, name = "HOME"), path("blog_detail/<int:id>", views.blog_detail, name = "blog"), # path("about/", views.about, name="about"), # path("contact/", views.contact, name="contact"), path("back/", views.back1, name="back"), # re_path(r'^back/$', views.back1, name="back"), path("chest/", views.chest, name="chest"), path("shoulder/",views.shoulder, name="shoulder"), path("abs/", views.abs, name="abs"), path("bicep/", views.bicep, name="bicep"), path("tricep/", views.tricep, name= "tricep"), path("forearm/", views.forearm, name="forearm"), path("legs/", views.legs, name="legs"), path("fullbody/", views.fullbody, name="fullbody"), path("search/", views.search, name="search"), … -
Matplotlib shift plot graph to left
I'm wondering if it is possible to shift the graph only to the left for the following plot graph. import matplotlib import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() fig.savefig("test.png") plt.show() I want to leave the x ticks the same but want to shift the graph so that the starting point of the graph is on y-axis. Any suggestions? Thank you in advance. -
Too many values to unpack in MultipleChoicefield choices, though the choices element is an iterable list
I have this form, with a multiplechoicefield. The choices, I need to first split the values I get from the queryset, and then have them seperated before I can use them. class SsReportOndemandForm(forms.Form): recipient_email = forms.MultipleChoiceField(required=False,choices=email_choices) I tried this, and I got a simple list. email_choices = [] for emails in SsReportType.objects.all().values_list('email', flat=True): email_choices.append(str(emails).split(",")) print(email_choices) I printed out the list email_choices and got smth like this [[u'sumassing@sa.com ', u'shidwvargh@ss.com ', u'seweatigund@ff.com'], [u'sumaswqeing@gg.com', u'sumasing@hh.com ', u'shivdargh@aa.com ', u'satqweigweund@gg.com']] Which is fine, but when I render the form, it shows me error : ValueError at /ssreport/on_demand_ssreport too many values to unpack Request Method: GET Request URL: http://127.0.0.1:8000/ssreport/on_demand_ssreport Django Version: 1.7.6 Exception Type: ValueError Exception Value: too many values to unpack Exception Location: /home/rohit/Documents/matrix_cloud/env/local/lib/python2.7/site-packages/django/forms/widgets.py in render_options, line 530 I cannot use tuple here , as I need to split the values. Any idea what I can do?? -
Django auth api
I am following this short tutorial to make an api to authenticate users with Django. The tutorial mentions that this should not be used in production and I wanted to know why as I plan to use it in production. Is it just the '*' in the allowed hosts part which shouldn't be used? https://afdezl.github.io/post/authentication-react-native-django-1/ thanks -
Contact Form with Django 3, G Suite - email sending error
Goal Deploying a landing page on Digital Ocean built with Django 3. Adding my G suite account to the contact form so people can type in their email, subject, message and send it to me. What I have done I have built my contact from with the following guide. I have tested it and it prints out all the parameters in the terminal as it should Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: helllo From: customeremail@gmail.com To: admin@example.com Date: Tue, 17 Mar 2020 14:29:40 -0000 Message-ID: <12121212121212.1222212121212.1212121212121212@mymachinename.local> This is the message. After I have finished the tutorial I have added/switched the following things to the settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'mayname@mycompanydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have purchased a G Suite subscription that contains G Suite SMTP relay service that can send 10'000 email/day. ERRORS 1.After the 1st run I have received the following e-mail: Sign-in attempt was blocked myname@businessemaildomainname.com Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access. Check … -
Importing csv file into django and getting list index out of range error
I'm trying to upload a csv file into my django projects and save data into my model. The problem is i'm getting list index out of range but the data is uploaded correctly and saved into model. Can anyone please help me to solve this issue? this is my method in views.py : def admin_upload(request): template = "admin_upload.html" prompt = { 'order': 'CSV fichier cef, cin, nom, prenom, group, module, note_1, note_2, note_EFM' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a CSV file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = Note.objects.update_or_create( cef=column[0], cin=column[1], nom=column[2], prenom=column[3], group=column[4], module=column[5], note_1=column[6], note_2=column[7], note_EFM=column[8] ) context = {} return render(request, template, context) my model : class Note(models.Model): cef = models.CharField(max_length=30, unique=True) cin = models.CharField(max_length=30) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) group = models.CharField(max_length=10) module = models.CharField(max_length=30) note_1 = models.CharField(max_length=5) note_2 = models.CharField(max_length=5) note_EFM = models.CharField(max_length=5) When i upload a csv file the data get uploaded but i get list index out of range error: IndexError at /import/ list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/import/ Django Version: 3.0.2 Exception Type: IndexError … -
formset doesn't save data
I've got a problem and i don't know how to solve it. I created formset where you can write your question in poll. I used formset because in future i want to make dynamic form from it. For now i just wanted one form to see if it works and ... it doesn't. When i click button everything is working as expected but when i click on detail view i can't see my choices. Also there is no data from form in database. Here is my code: model.py class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py class CreateChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) def __init__(self, *args, **kwargs): self.question = kwargs.pop('question') super(CreateChoiceForm, self).__init__(*args, **kwargs) ChoiceFormSet = modelformset_factory(Choice, form=CreateChoiceForm, extra=1) class ChoiceFormSet(ChoiceFormSet): def __init__(self, *args ,**kwargs): self.question = kwargs.pop('question') super(ChoiceFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def _construct_form(self, *args, **kwargs): kwargs['question'] = self.question return super(ChoiceFormSet,self)._construct_form(*args, **kwargs) views.py def createChoice(request, pk): question = get_object_or_404(Question, pk=pk) formset = forms.ChoiceFormSet(question=question) if request.method == 'POST': if formset.is_valid(): formset = forms.ChoiceFormSet(question=question, … -
Cannot assign "'type1'": "users.user_type" must be a "types" instance
I have a 'users' model that have a OneToOneField to UserModel and a ForeignKey Field to 'types' model. How can I save the ForeignKeyField in database? models.py: class types(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') name = models.CharField(max_length=100) def __str__(self): return self.name class users(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') user_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) mobile = models.CharField(max_length=20) def __str__(self): return self.mobile + "(" + self.user.first_name + " " + self.user.last_name + ")" @property def full_name(self): return '%s %s' % (self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def update_user_users(sender, instance, created, **kwargs): if created: users.objects.create(user=instance) instance.users.save() views.py: def signup(request): if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.users.mobile = form.cleaned_data.get('mobile') user.users.user_type = form.cleaned_data.get('user_type') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('index') else: form = forms.SignUpForm() return render(request, 'user/signup.html', {'form': form}) forms.py: lass SignUpForm(UserCreationForm): mobile = forms.CharField(max_length=20) user_type = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'mobile', 'user_type', ) But, I have this error: Cannot assign "'type1'": "users.user_type" must be a "types" instance. -
how to change field type and retain choices defined in model django 3.0
I am new to Django, I am trying to change field type by retaining choices defined in model. this is my model class MyModel(models.Model): class Type(models.IntegerChoices): INDIRECT= 0 DIRECT = 1 BOTH = 2 name = models.CharField(max_length=20) category = models.IntegerField(choices=Type.choices) price= models.IntegerField() and this is my form class class MyForm(forms.ModelForm): #category = forms.ChoiceField(widget=forms.RadioSelect()) class Meta: model = SPA fields = [ 'name', 'category', 'price' ] I know we can change the field type with the above commented line. but it doesn't bring choices from model.... Please advice how to achieve it. -
django migration on kubernetes replica set
I ran in to a problem, while deploying the django application in kubernetes pod having 3 replicas. Here is the problem: -> I have some db migration to be run in the django application. -> The migration python manage.py migrate --noinput --fake-initial runs during the application startup. -> When I deploy my helm chart having this deployment with 3 replicas, all the 3 replica try to migrate at the same time, the db lock timeout happens. Or some migration fails, saying table already exist. This happens only during the the fresh helm install chart installation, as all pods comes up together. I have not faced this issue while helm upgrade due to rolling update strategy, because only 1 pods comes up and do the migration. My question is: -> Is their any way to tell the kubernetes to bring up replica one-by-one during the helm install just like it do during upgrade. -> Is their any way I can avoid my error through helm hooks, I cannot use helm preinstall (as I need service account and credential to connect to DB) or post install (As the worker thread in django app needs to be rebooted to make migration into effect) -
How can I store a list of model instances in a django model
I am trying to create a form generator in the django admin panel that allows users to create forms graphically by entering the form field name, field ID and field type. How can I go about doing this? I was thinking of creating a model for forms and referencing instances in the model of the whole form. Is this the best way to go about this? Is there a better way? Project is at librebadge.com -
Paginations with ajax and django
Here's the code for the views.py it's a method that receives the "get" request and then retreives the data of the objects after filtering in json format. my views.py @login_required(login_url='login') def filter(request, page=1): """Displays the results of the search for substitute products """ global data # First logic section value = request.GET.get('value') """ logic of seconde user search (get constum search with 3 fields ( grade, categorie, rating)) """ conditions = dict() for filter_key, form_key in (('grade', 'grade'), ('categorie', 'categorie'), ('rating__rating', 'rating')): value = request.GET.get(form_key, None) if value: conditions[filter_key] = value print(conditions) best_product = Product.objects.filter(**conditions) serialize_product = productSerializer(best_product, many=True) print(type(serialize_product.data)) context = { 'best_product': serialize_product.data, } print((context)) return JsonResponse(context) Here is the "query" code that retrieves the data entered (grade, category, rating) then sends it to the view(filter), after processing it retrieves the answer then displays all the objects (in "var html"). My problem is that I want to display just 15 objects at a time (pagination with 15 objects). my scripts.js $('#btn-filter').on('click', function (e) { e.preventDefault(); var grade = $('#grade').val(); var categorie = $('#categorie').val(); var rating = $('#rating').val(); $('#row-after').children().remove(); // alert( 'rating: ' + rating + ' grade: ' + grade+ ' categorie: ' + categorie ); $.ajax({ url: … -
Celery Eventlet Worker django.db.utils.DatabaseError within Docker
I have a web application which is locally run with docker-compose. It contains Django connected to PostgreSQL, Celery and RabbitMQ. Every time I run a shared_task I get the following DatabaseError. worker_1 | [2020-03-17 20:03:40,931: ERROR/MainProcess] Signal handler <bound method DjangoWorkerFixup.on_task_prerun of <celery.fixups.django.DjangoWorkerFixup object at 0x7fa4dbf3ead0>> raised: DatabaseError("DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 and this is thread id 140345963084624.") worker_1 | Traceback (most recent call last): worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send worker_1 | response = receiver(signal=self, sender=sender, **named) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 166, in on_task_prerun worker_1 | self.close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 177, in close_database worker_1 | return self._close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 186, in _close_database worker_1 | conn.close() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner worker_1 | return func(*args, **kwargs) worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 286, in close worker_1 | self.validate_thread_sharing() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 558, in validate_thread_sharing worker_1 | % (self.alias, self._thread_ident, _thread.get_ident()) worker_1 | django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 … -
Submitting Individual Django Formsets with AJAX
I'm trying to set up a page that will give the user the ability to edit multiple expenses at a time. Since it's not just a field or 2 that they may update i want to give them the ability to submit after updating each one. I've gotten as far as being able to serialize the form with...but not sure where to go from here. <form > <table> <div class="fieldWrapper"> {{ form.Notes.errors }} <label for="{{ form.Notes.id_for_label }}">Notes:</label> {{ form.Notes }} </div> ....rest of form.... </table> <a id="sv_btn{{forloop.counter0}}" class="btn-floating btn-large waves-effect waves-light blue" onclick="exp_sv({{forloop.counter0}})"><i class="material-icons">save</i></a> </form > and then the Java... function exp_sv(x) { console.log("Inside validate button function("+x+")") var serializeData = $('form').serialize(); console.log(serializeData); }; -
How to add a column to table throught active model in vritualenv django?
I am running an application in a virtual enviroment in Django 1.7.11. I have a model which MySQL table has 3 columns but I want to add one more column and fill it out manually. When I do that, and make changes in the model I get an 500 Internal server error. Is there a way to do it on more Pythonic way? I have installed all the necessary requirements but when I run python manage.py makemigrations I get this error: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ImportError: No module named django.core.management All the modules are imported, and the application is running normally when I undo my changes in the model. -
DRF: how do I call a class inside another class method?
I have two separate methods: to load and validate a csv file FileUploadView(APIView) [PUT] to add new objects to the database based on their uploaded file data CsvToDatabase [POST] file upload class FileUploadView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = (permissions.AllowAny,) def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 else: status = 406 r = "File format error" return Response(r, status=status) create instances class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data ... #some logic ... serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('csv_upload/', FileUploadView.as_view(), name='csv_upload'), path('from_csv_create/', CsvToDatabase.as_view(), name='csv_vendor_create'),] At the moment I am simply passing manually to Postman the result of the PUT method of FileUploadView class (Response(r, status=status) get me json ) to POST method of CsvToDatabase class. Of course, this option is not suitable for a working application. I would like to know if there is a way to call the POST method automatically inside FileUploadView class after the .csv file is processed and json is received. I know I can transfer a … -
How to make an image responsive after setting its height and width in bootstrap
So I'm building this portfolio, and I found out ways to make the text and other stuff responsive, but I'm unable to make the picture responsive, I have set its height to 325, but when I shrink the page, the image isn't responsive. How should I make it responsive. The original image dimensions are around 1000 x 900, I tried shrinking the image size and using img-fluid but that didn't work as well. When I shrink the page When the page is in full view <img src="{% static 'shetha.jpg' %}" height="325 "/> -
Find nested JS object value from specific script tag with Beautiful Soup
I am scraping a site with beautiful soup to grab image/s, this has worked fine for every site so far and I have even managed to create some custom case-types. But one particular site is causing me issues as iit returns all the images in a JavaScript object wrapped inline in a script tag. The object is quite large as it holds all the product info, the specific bit I am looking for is nested pretty deep in productArticleDetails > [the product id] > normalImages > thumbnail > [the image path]. Like so: <script> var productArticleDetails = { ... '0399310001': { ... 'normalImages': [ { 'thumbnail': '//image-path.jpg', ... } ] } } So I am looking to just extract the image path. It is also not the only thing wrapped in a script tag in the returned 'soup', there are loads of other javascript tags in the code. So far I have saved the HTML to a variable and then run: soup = BeautifulSoup(html) scripts = soup.find_all('script') So I am left with an object that contains all the <script> elements from html Somehow within that scripts object I need to find that specific node in the correct chunk of JS … -
Django - Form returning invalid due to empty form field
In my project, I have a Django form which consists of an ImageField and a CharField. I pass this form to my template, and display it. On the form, I set the method attribute to POST. In my view I handle this request, and return a redirect in return. However form.is_valid() is returning False in my view, and I print the forms errors in the console. Here is the error returned from form.errors: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> It is saying my ImageField input field is empty, however I definitely select a file for the ImageField in the browser, therefore I don't know the reason why it's saying that the input field is blank. My code is below. forms.py: class CreatePost(forms.Form): // The field that is not being assigned a file image = forms.ImageField(allow_empty_file=False, required=True, widget=forms.FileInput(attrs={'id': 'image'})) description = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Add a caption:', 'id': 'description'})) views.py: def create(request): context = {} if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): print("YES") return redirect('home') else: print(form.errors) context['error'] = 'Please enter valid form data' else: form = CreatePost() context['form'] = form return render(request, 'create.html', context) Template: <form action="{% url 'create' %}" method="POST"> {% csrf_token %} {% for field in … -
How to set Current_company_flag using Django
I am creating a model for storing Experience... Here is my model class Experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) company = models.CharField(max_length=255, blank=True) current_company = models.BooleanField(default=False) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime.now) In this current_company is used to showing it is the current company .... This is my form for getting the data from user class ExperienceForm(forms.ModelForm): class Meta: model = Experience exclude = ['user'] This is my view class ExperienceFormView(TemplateView, LoginRequiredMixin): template_name = 'accounts/profile/expereince_form.html' form_class = ExperienceForm def post(self, request, *args, **kwargs): context = self.get_context_data() if context['form'].is_valid(): data = context['form'].save(commit=False) data.user = request.user data.save() return JsonResponse({'status': 'success', 'message': 'Created Successfully'}, status=201, safe=False) return super(ExperienceFormView, self).render_to_response(context) def get_context_data(self, **kwargs): context = super(ExperienceFormView, self).get_context_data(**kwargs) form = ExperienceForm( self.request.POST or None) # instance= None context["form"] = form return context What is the best way to implment the following use cases 1) If I enable my current_company as True then the previous object having current_company becomes False 2)If there is no previous object then ignore the first use case..... -
Django admin how do you add a queryset as a read only linked property field
This is what my admin class looks like: @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('associated_risks',) associated_risks is a queryset property that I have set in the model like so: @property def associated_risks(self): return Risk.objects.filter(control__project__associated_controls__in=self.associated_controls.all()) The isssue is that the admin page it's a read only field shown like this: Would it be possible to set it as an m2m field similar to how other m2m fields in the django admin page are set up? (multi select form) -
Error 10061 connecting to localhost:6397. No connection could be made because the target machine actively refused it
I'm trying to learn Redis with Django framework. My program is intended to count image views but when I click on the image details it gives me above mentioned error. I am unable to make connection with redis. Here's the link to my detail error http://dpaste.com/1TAJ4MF I have installed and run redis cli on WINDOWS 10 and here is a snip of my settings.py code # Configuring Redis database REDIS_HOST = 'localhost' REDIS_PORT = 6397 REDIS_DB = 0 views.py import redis from django.conf import settings def detail(request, id): profile = get_object_or_404(Profile, id=id) # increment total image views by 1 total_views = r.incr('profile:{}:views'.format(profile.id)) return render(request, 'images/detail.html', {'profile': profile, 'total_views': total_views}) detail.html <body> <img src="{{ profile.photo.url }}" width="500" height="500" alt="Image not found"> <br> {{ profile.user.username.title }}. {{ profile.dob }} <br> {{ total_views }} view{{ total_views|pluralize }} </body> -
My Django web app isn't functioning properly
I'm fairly new at Django and I've been making a login and registration form using bootstrap and then connecting the bootstrap template with Django. The form has a sign in and sign-up page which has a smooth transition when you click on each of them. But when I click on the sign-up, nothings happening.I've set up the static files and the website is displaying correctly although not functioning correctly. Can someone help me resolve this problem? I've provided the CSS file here https://easyupload.io/gq48hs. The login and registration page looks like this https://ibb.co/jr4pm3N Bootstrap {% load static %} <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Online Timetable - Student Login and registration form</title> <link rel='stylesheet' href='https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css'><link rel="stylesheet" href="{%static 'css/style.css' %}"/> </head> <body> <!-- partial:index.partial.html --> Login & registration Form --> SIGN IN SIGN UP USERNAME PASSWORD Keep me signed in Forgot password? USERNAME E-MAIL PASSWORD CONFIRM PASSWORD I agree </body> <!-- partial --> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> <script src="{% static 'css/script.js' %}"></script> </body> </html> $('.btn-enregistrer').click(function() { $('.connexion').addClass('remove-section'); $('.enregistrer').removeClass('active-section'); $('.btn-enregistrer').removeClass('active'); $('.btn-connexion').addClass('active'); }); $('.btn-connexion').click(function() { $('.connexion').removeClass('remove-section'); $('.enregistrer').addClass('active-section'); $('.btn-enregistrer').addClass('active'); $('.btn-connexion').removeClass('active'); }); URLS.Py from django.urls import path from .import views urlpatterns = [ path('',views.login), ] Views.py from django.shortcuts import render from django.http import HttpResponse …