Django Custom Template Form and {{next}} - django

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.

Related

how to insert data to database without forms.py in django

This method works fine for me can some one say how to add file or images like this
def insert_students(request);
name = request.POST['name']
class = request.POST['class']
student = studentsmodels(name=name, class=class)
student.save()
return redirect('/')
return render(request, "insertpage.html")
Using Django forms would make your life so much easier, frankly. However, you can still create objects without forms and add files to them. Instead of request.POST the files are stored in request.FILES the documentation goes into detail about how files are uploaded:
https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/
def submit_form(request):
if request.method == POST:
name = request.POST["name"]
class = request.POST["class"]
if Mymodel.objects.filter(name=name, class=class).exist():
messages.infor("class and name already exist")
else:
MyModel.objects.create(name=name, class=class)
return render(request, "submit_form.html)
submit_form.html
<form action="{% url 'submit_form' %}" method="post">
{%csrf_token%}
<input name="name" placeholder="Enter Name" type="text">
<input name="class" type="text" placeholder="Enter Class">
<button class="button is-success is-fullwidth is-medium mt-5"
type="submit">submit
</button>
</form>

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>

Difference between two methods in django

What's difference between two methods and which is better for long run ? Is there any advantage one over other?
To add a staff:
(1st Method)
views.py
def add_staff(request):
return render(request, 'hod_template/add_staff_template.html')
def add_staff_save(request):
if request.method != 'POST':
return HttpResponse('Method not allowed')
else:
first_name = request.GET.get('first_name')
last_name = request.GET.get('last_name')
username = request.GET.get('username')
email = request.GET.get('email')
password = request.GET.get('password')
address = request.GET.get('address')
try:
user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2)
user.staffs.address = address
user.save()
messages.success(request, 'Staff Added Successfully')
return HttpResponseRedirect('/add_staff')
except:
messages.error(request, 'Failed to Add Staff')
return HttpResponseRedirect('/add_staff')
urls.py
path('add_staff/', add_staff),
path('add_staff_save/', add_staff_save),
add_staff.html
<form role="form" action="/add_staff_save">
{% csrf_token %}
<div class="card-body">
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<!-- same for first_name, last_name, username, address -->
<div class="card-footer">
<button type="submit" class="btn btn-primary btn-block">Add Staff</button>
</div>
</div>
</form>
(2nd Method)
make a form in forms.py of all fields first_name, last_name, username, address
and then call in view and validate it.
forms.py
class StaffForm(forms.ModelForm):
class Meta:
model = Staff
fields = ('first_name', 'last_name', 'username', 'address')
views.py
def add_staff(request):
if request.method == 'POST':
form = StaffForm(data=request.POST)
if form.is_valid():
messages.success(request, 'Staff Added Successfully')
form.save()
else:
form = StaffForm()
return render(request, 'staff.html', {'form':form})
urls.py
path('add_staff/', add_staff),
staff.html
<form role="form" action="/">
{% csrf_token %}
{{ form.as_p }} <!-- render form as paragraph -->
</form>
Both methods work well and staff model have all the required field.
Sorry for long question since its getting too long I'm not adding staff model. If you need plz let me know.
of course the second method is much way better than the first one
because you should do cleaning and validation in other files like forms.py in each individual section
and also you can add more options and other things that maybe will be useful after a time
and you should be aware of that and predict some changes for improvement too!
and with making forms and use generics , you will write less code than doing it by yourself in hardcode in views.
so don't hesitate and choose method2
2nd method is better than 1st one. 2nd method give more flexibility you only have to make a form in forms.py and you can use it in different locations while for 1st method you have to use 2 urls just to show form and save it . Also you can use filters like crispy_forms_tags on form as {{ form|crispy }}. So obviously in long run 2nd method is better.

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.

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.