how to integrate API with HTML in django template? - django

I am using both POST and GET method through python requests to fetch datas and submit data in an API.
class ApiLoginView(TemplateView):
template_name = 'index.html'
def post(self,request):
email = request.POST.get('email')
print(email)
password = request.POST.get('password')
print(password)
API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxx'
API_URL = 'http://dev.com/rest/storeLogin'
parameter = {
'authToken':API_KEY,
'email':email,
'password':password,
}
r = session.post(url = API_URL, params=parameter)
print(r.json()['code'])
return render(request,'index.html')
With this above views.py class method i'm trying to post data.and I have an readymade HTML form for login ready.
<form class="my-login-form" action="/login" method="post">
{% csrf_token %}
<div class="field-wrap">
<input type="email" name="email" required autocomplete="off" placeholder="Email Id"/>
</div>
<div class="field-wrap">
<input type="password" name="password" required autocomplete="off" placeholder="Password">
</div>
<button class="button button-block"/>Login</button>
<div class="forgot"><a class="user-form-toggle" href="#forgot">Forgot Password?</a></div>
</form>
So my dilemma is how to map both class based view and html form. Right now it seems html form is stand alone!

You should check djangorestframework. It's a good framework for defining REST APIs with multiple formats, filters, etc, by doing mostly configuration instead of code.

Related

How to Add Subscribe option in a Django Website

I am trying to add a subscribe to newsletter option on a django website. When a visitor enters
a valid email address it will be stored in the database. The subscription form is part of the base.html template.
All other templates of the website extend this template. I wish to implement this in a DRY way.
This is how I am trying to do it :
forms.py :
from dataclasses import fields
from django import forms
from . models import Subscribers, MailMessage
class SubcribersForm(forms.ModelForm):
class Meta:
model = Subscribers
fields = ['email', ]
views.py :
def base(request):
if request.method == 'POST':
form = SubcribersForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = SubcribersForm()
context = {'form': form}
return render(request, 'base.html', context)
The template: base.html
<form method = "POST" class="signup-form form-inline justify-content-center pt-3">
{% csrf_token %}
<div class="form-group">
<label class="sr-only" for="semail">{{context}}</label>
<input type="email" id="semail" name="semail1" class="form-control mr-md-1 semail" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary">Subscribe</button>
</form>
models.py :
class Subscribers(models.Model):
email = models.EmailField(null=True)
date = models.DateTimeField(auto_now_add=True)
def __str__self(self):
return self.email
In the backend, I can see that the Subscribers table has been created. However, when I enter any email address from the home
page and click subscribe button it does not store it in the database. What could be the issue here?
It could be that you have no action declared in your form. Assuming you have a url like this:
path('add-subscriber/', base, name='base'),
...your form would need a way to call it upon submit, like this:
<form method = "POST" action="{% url 'base' %}" class="signup-form form-inline justify-content-center pt-3">
{% csrf_token %}
<div class="form-group">
<label class="sr-only" for="semail">{{context}}</label>
<input type="email" id="semail" name="semail1" class="form-control mr-md-1 semail" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-primary">Subscribe</button>
</form>

How to register users in Django while maintaining frontend bootstrap template?

I am trying to register users for a multi user complaint management system using django. The frontend is already ready and I just have to do the backend. I am fairly new at django and this is my first project so I'm very confused in how to maintain the bootstrap view while being able to register users and authenticate them.
The bootstrap template is:
```<div class="col-lg-4 login-bg">
<h4 class="reg-title"><strong>Get Started...</strong></h4>
<p class="login-reg">Already have an account? <a class="log-reg-link" href="login.html">Log In </a> here</p>
<hr>
<form class="" action="/Dashboard/" method="post">
<p class="reg-field-title"><strong>First Name*</strong></p>
<input type="text" class="form-control col-lg-10 log-inp-field" placeholder="First Name" required>
<p class="reg-field-title"><strong>Last Name*</strong></p>
<input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Last Name" required>
<p class="reg-field-title"><strong>Email ID*</strong></p>
<input type="email" class="form-control col-lg-10 log-inp-field" placeholder="Enter email" required>
<p class="reg-field-title"><strong>Password*</strong></p>
<input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required>
<button type="submit" class="btn btn-dark btn-lg col-lg-10 reg-btn">Register</button>
</form>```
this is my accounts model:
```from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=130)
last_name = models.CharField(max_length=130)
email = models.EmailField(blank=True)
Password = models.CharField()
I don't understand what to do? What to put in the views and the forms?
One approach might be to use AJAX docs. You can make API calls to your backend on press of the login button and authenticate the user without needing to POST to another route.
Or you can use entend to not repeat HTML in different templates.
create the view that handles the registration, it's going to be a view that handles a form:
view.py :( this a standart exemple from the documentation )
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
in the template :
name.html :
<div class="col-lg-4 login-bg">
<h4 class="reg-title"><strong>Get Started...</strong></h4>
<p class="login-reg">Already have an account? <a class="log-reg-link" href="login.html">Log In </a> here</p>
<hr>
<form class="" action="/Dashboard/" method="post">
{{form}}
<button type="submit" class="btn btn-dark btn-lg col-lg-10 reg-btn">Register</button>
</form>
form is a context it's the result of your view and you send it to the template, then render it with the Django template language {{form}} you can read more about this: django forms
Django also provide a default Auth system and if you don't like it there a package called django allauth it's one of the best auth system, there is you can just follow a tutorial on YouTube for Django default Auth or Jango all-out it's easy

django the way to access data from input form

My symptom is when I click the modify button and then I write down the information on new window that is implemented by bootstrap div part. However, my database doesn't change at all. Please ignore ... in codes, I delete attributes that looks messy. Codes can have typo, because I wrote it down manually to find a bug, but I didn't find.
I tried in view.py, address_modify makes return Httpresponse(street), but It returned None.
view.py
def address_modify(request, adid):
cat = get_object_or_404(Address, adid=adid)
if request.method == "POST":
old_adid = adid
email = request.user.email
street = request.POST.get("street", None)
city = request.POST.get("city", None)
...
Address.objects.filter(adid=adid).update(..., street=street, city=city, state=state, ...)
return redirect('/address/')
return redirect('/address/')
template ( I name it address.html)
<button class="btn btn-success" data-toggle="modal" data-target="#modify">MODIFY</button>
<div class ="model fade" id="modify" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<from action="" method="POST">{% csrf_token %}
</div>
<div class="modal-body">
<input type="text" name="street">
<input type="text" name="city">
...
...
<input type="text" name="zipcode">
</div>
<div class="modal-footer">
<a href="{% url 'address_modify' i.adid %}">{% csrf_token %}
<button type="button" class="btn btn-primary">Save Change</button></a>
<div></form>
urls.py
url(r'^address_modify/(?P<adid>[0-9]+)/$', MyAppView.address_modify, name='address_modify'),
In django the best practice is to create a forms.py file to handle forms, its really easy you can read the doumentation on it, basically the form will ensure that all your data are read.
That is not how you implement form and form submit. Your link is not submitting anything, it's just opening a link. This is the standard form syntax:
<form method="POST">
{% csrf_token %}
... your form input fields here ...
<input type="submit" value="Save changes">
</form>
You must submit the form. Note type="submit" there.
Next to that, Django has forms feature. Use it. Create forms.py as #Saumel-Omole suggested. Form for model Address would look like this:
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = '__all__'
Then you modify your view to use the form like:
def address_modify(request, adid):
cat = get_object_or_404(Address, adid=adid)
form = AddressForm(instance=cat)
if request.method == 'POST':
form = AddressForm(request.POST, instance=cat)
if form.is_valid():
form.save()
return redirect('/address/')
else:
print(form.errors) # change to logging
return render(request, 'address.html', {'form': form})
Go over the official Django tutorial. These basics are all there. Maybe it is going to take you a day or two to get through it, but long-term that's going to be far less than guessing and googling around for days for basic stuff.

Django Custom Template Form and {{next}}

I'm stuck on creating form, looks like {{ forms.as_p }}.
I need to login to website using this form. Uing forms.as_p it everything works perfectly, but I need to create my own customized form.
Problem is, that after reading lot's of website's and documentation I still can't understand, how to create custom form with my css class and input fields.
I tried this one:
action="", method ="post"
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" required="">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" required="">
</div>
<input type="submit" class="btn btn-primary block full-width m-b" value="Log In" />
But it doesn't work.
What fields, I've missed.
Also I have another question: Is it possible to custom "next" variable to redirect after login on my custom page? And how I can do it?
Normally you use your forms.py to create a form that you can use in your HTML-Code via Jinja.
Your forms.py could look like this:
from django import forms
class ProfileForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
age = forms.IntegerField(label='Your age')
Then you would do some cleaning to make sure the data passed to the form has the right format.
def clean_name(self):
name = self.cleaned_data.get('name')
if not name:
raise forms.ValidationError('You have to type in a name.')
return name
In your views.py:
def some_view(request):
form = ProfileForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data.get('name')
//do something with the name
user = User.objects.get(username=username)
user.username = name
user.save()
return redirect('to_profile_of_user')
return render(request, 'change_profile.html', {'form':form})
Here it is very important that you pass the form to your template(HTML).
Your change_profile.html:
<form action="" method="POST" enctype="multipart/form-data">
{{form.as_p}} //That is the form you passed
<input type="submit" value="Change" />
</form>
I hope my answer gives you a little bit of advice. Now you have seen a complete roundtrip. Maybe you should have a closer look at the Django documentation. It is very helpful.
The code is written on the fly and not tested. But it is enough for an overview. You should not forget to import the things you need. I did not do that.

form.is_valid() always returning False in Django

Below is my code for Form submission .when i submit the form form,is_valid always returning false not sure want went wrong with my code. I am just started learning Django any help is highly appreciated TIA
HTML
{%extends 'base.html'%}
{% block content %}
<div class="container">
<form method="post" class="form-signin" action="/loginvalidation/">{% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
{% endblock %}
Html file
view.py
def loginvalidation(request):
print request
form = LoginssForm(request.POST or None)
print form.is_valid()
if form.is_valid():
save_it=form.save(commit=False)
print save_it.email
save_it.save()
user = authenticate(username='john', password='secret')
if user is not None:
# the password verified for the user
if user.is_active:
print("User is valid, active and authenticated")
else:
print("The password is valid, but the account has been disabled!")
else:
# the authentication system was unable to verify the username and password
print("The username and password were incorrect.")
return render(request,"about-us.html",locals(), context_instance=RequestContext(request))]
View. py for my code
Model.py
class LogIn(models.Model):
email=models.EmailField(null=False,blank=False)
password=models.CharField(max_length=1201,null=True,blank=True)
timestamp=models.DateTimeField(auto_now_add=True,auto_now=False)
updated=models.DateTimeField(auto_now_add=False,auto_now=True)
Model of application
Model of applicationModel of application
form.py
class LogInForm(forms.ModelForm):
class Meta:
model=LogIn
fields = '__all__'
Above is my code for Form submission. When I submit the form, form.is_valid always returns False. I just started learning Django any help is highly appreciated.
It appears you're missing a "name" attribute on your fields in the HTML file, thus the value is never actually getting posted to Django. If just add name="email" and name="password", respectively, to the fields, then the values should get passed through and begin properly validating.
However, that being said, I agree with Alasdair's comment above. It would be far more secure and recommended to use Django's built in authentication system.