I am making a simple personal website. I make a box to input user data (name, email, and message). I want this data is sent to my django admin. I have test it and it works in local. But when i deploy it, i didn't get any data whenever i submit from the box. Note : i do not use django form for some reason. I want to use my own custom form.
this is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Feedback
from .forms import FeedbackForm
def index(request):
if (request.method == "POST"):
name = request.POST.get("Name")
email = request.POST.get("Email")
message = request.POST.get("Message")
record = Feedback(name=name, email=email, message=message)
record.save()
return render(request, 'main.html')
this is my models.py
from django.db import models
class Feedback(models.Model) :
name = models.CharField(max_length=50)
email = models.EmailField()
message = models.CharField(max_length=200)
def __str__(self):
return self.name
this is my html form
<form action="{% url 'index' %}" method="POST" target="_self">
{% csrf_token %}
<div class="w3-row-padding" style="margin:0 -16px 8px -16px">
<div class="w3-half">
<input class="w3-input w3-border" type="text" placeholder="Name" required name="Name" >
</div>
<div class="w3-half">
<input class="w3-input w3-border" type="email" placeholder="Email" required name="Email">
</div>
</div>
<input class="w3-input w3-border" type="text" placeholder="Message" required name="Message" >
<button class="w3-button w3-black w3-right w3-section" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</form>
I'm not sure what platform you have deployed the project on, but one of the first things I would try is to make sure you have run database migration. (Which I'm assuming you have done if you have access to the admin area, but it might be worth running again just to make sure.)
python manage.py makemigrations
python manage.py migrate
I made some modifications to your HTML form to more closely follow the Django documentation. Notably, the addition of enctype="multipart/form-data" and an id tag to each input: i.e. id="name". Here is a link to the documentation: https://docs.djangoproject.com/en/3.1/topics/forms/
<form action="{% url 'index' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="w3-row-padding" style="margin:0 -16px 8px -16px">
<div class="w3-half">
<input class="w3-input w3-border" type="text" placeholder="Name" name="Name" id="name" required>
</div>
<div class="w3-half">
<input class="w3-input w3-border" type="email" placeholder="Email" name="Email" id="email" required>
</div>
</div>
<input class="w3-input w3-border" type="text" placeholder="Message" name="Message" id="message" required>
<button class="w3-button w3-black w3-right w3-section" type="submit"><i class="fa fa-paper-plane"></i>SEND MESSAGE</button>
</form>
It could be an issue with copying/pasting code, but I noticed the fields on your model are over-indented. Make sure you are using a single tab before each field.
# models.py
class Feedback(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
message = models.CharField(max_length=200)
def __str__(self):
return self.name
If you are able to see the terminal, are you getting a 200 response with your POST request? It should look something like this:
"POST / HTTP/1.1" 200
One of the other things I'd check is to ensure your database is configured properly in settings.py (This is assuming you are using the sqlite database)
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
If you aren't seeing anything in the admin area, make sure you have registered your model in admin.py
from django.contrib import admin
from .models import Feedback
admin.site.register(Feedback)
Related
It's my first time doing a Django Form challenge.
The challenge for now is just from a HTML Template get the last_name information and store into DB from views. So I have a scenario below:
models.py:
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
an HTML template, I will put below only the form part:
<form action="{% url 'store' %}" method="post">
{% csrf_token %}
<div class="form-group row">
<label for="last_name" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="last_name" placeholder="Last Name">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Send Last Name</button>
</div>
</div>
</form>
And the views.py itself... I created a InsertLastName ModelForm to store the data from the form, but didn't work. For some reason, when I tryed to call form.cleaned_data I reveived an error about the is_valid() verification. Seens like that I'm not getting the information from label.
class InsertLastName(forms.ModelForm):
class Meta:
model = Person
fields = ['last_name']
exclude = ['first_name']
def index(request):
persons = Person.objects.all()
context = {'persons': persons}
return render(request, '/index.html', context)
def store(request):
form = InsertLastName(request.POST or None)
print(form.cleaned_data['last_name'])
return HttpResponse("Storing a new Last Name object into storage")
What is the correct way to get the information from last_name label in my form?
I'm following that documentation and coding from a challenge template.
Your just set attr name for your input html tag
Example:
<input type="text" name="first">
And for get input in function store in view.py:
request.POST.get("first")
Add this to your html template in your form
{{persons}}
I've created a template for updating account profiles using a Bootstrap snippet (from https://www.bootdey.com). With the django default format (like {{ form.as_p }}), updating accounts works (for example, when I modify the first name, it changes in the database). When I use the bootstrapp snippet, it doesn't update: it goes straight to 'homepage' without updating (as explained in views.py).
In forms.py
class EditAccountForm(UserChangeForm):
class Meta:
model = Account
fields = ('email','first_name','last_name')
In views.py
def EditProfile(request):
context= {}
if request.POST:
form = EditAccountForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
email = form.cleaned_data.get("email")
raw_password = form.cleaned_data.get("password1")
account = authenticate(email=email,password=raw_password)
return redirect('profile_page')
else:
context['edit_form'] = form
return redirect('homepage')
else:
form = EditAccountForm(instance=request.user)
context['edit_form'] = form
return render(request,'Account/edit_page.html',context)
the template: edit_profile.html (I only show the first_name part as example)
<form method = "POST" class="form" novalidate="">
{% csrf_token %}
<div class="row">
<div class="col">
<div class="row">
<div class="col">
<div class="form-group">
<label>First name</label>
<input class="form-control" type="text" name="firstna" value={{ edit_form.first_name.value }}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col d-flex justify-content-end">
<button class="btn btn-primary" type="submit">Save Changes</button>
PS: I've preferred to use those snippets instead of the Django style since I find them more attractive and offer more freedom.
Please check you are taking same value if you are changing the data in views like if you are using (name="firstna") in template so for First Name you have to take same in views.
Same question is asked here you can go and follow below link
[How to update user profile in Django
I'm working on the django authentification request and I get the forbidden error I checked my code but it doesn't seem I'm having an error.
HTML
<div class="grad"></div>
<div class="header">
<div>MLAT<span>SI</span></div>
</div>
<form action="{{views.login_user}}" method="POST">{% csrf_token %}
<div class="login">
<img src="{% static "img/Airplane.png" %}">
<div id="h" class="home">
<input type="text" placeholder="Login" name="username" value="">
<input type="password" placeholder="Mot de passe" name="password" value="">
<input style="float: left; width: 173px" type="submit" value="Log in" >
<input formaction="/form_registration.html/" style="float: right; width: 173px" type="submit" value="Register">
views.py
def login_user(request):
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
you seem like you have a problem in the import package. And the way you're calling the views are incorrect you should read the Django documentation well
Looks like a duplicate of: Django - {% csrf_token %} was used in a template, but the context did not provide the value
Basically, your login_user view isn't making use of any render/context, hence the error (I don't know if that's the same view that is called when the url for login is called). So Django sees the csrf_token but never converts it to an actual token value.
from django.shortcuts import render
But really both your form and view look very wrong. The form action {{ views.login_user }} is incorrect. You can't call a view that way. And your Register button goes to what looks like an HTML page.
As the title says, I would like to make a search bar form throughout my site. But I don't want to repeat the POST function on all the classes and was hoping there would be an easier way. The search bar is on my base template.
This is my form in my base template:
<form class="navbar-form navbar-right" method="POST" role="search">
<div class="form-group">
<div class="input-group">
<input class="form-control" id="navbarInput-01" type="search" name="search" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn"><span class="fui-search"></span></button>
</span>
</div>
</div>
</form>
My main python file:
import web
from bin import Categories, Search
from web import form
render = web.template.render('templates/', base='layout')
db = web.database(dbn="sqlite", db="webDB")
urls = (
'/', 'home',
'/about', 'about',
'/contact', 'contact',
'/blog', 'blog',
'/faqs', 'faqs',
'/tos', 'tos',
'/cat', Categories.app_cat,
'/search', Search.app_search
)
class home:
def GET(self):
return render.home()
def POST(self):
data = web.input()
search = data.search
raise web.seeother('/search/'+search)
I only made a POST method for my home page but I'd like all my pages to have it. I have many classes and copy/pasting this will be tedious.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
CSRF Protection in Django 1.4
I am trying to make a simple system for ticket reservation for rockets using Django. However, every time I try to reserve a ticket, I get the Forbidden 403 error: CSRF token missing or incorrect.
Here is my code:
models.py:
class Tickets(models.Model):
rocket_line = models.ForeignKey('Rockets')
date = models.DateField()
number_of_seats = models.IntegerField()
email = models.CharField(max_length=50)
ordered_on = models.DateTimeField()
total_price = models.DecimalField(max_digits=10, decimal_places=2)
def __unicode__(self):
return str(self.id)
views.py:
def order(request):
if request.method == 'POST':
order = Tickets(
rocket_line = Rockets.objects.get(id=request.POST['rocket_line']),
date=request.POST['date'],
number_of_seats=request.POST['number_of_seats'],
email=request.POST['email'],
ordered_on=datetime.now(),
total_price=(float(number_of_seats) * float(Rockets.objects.get(id=request.POST['rocket_line']).rprice))
)
order.save()
return HttpResponseRedirect('/menu/')
else:
all_rockets = Rockets.objects.all().order_by('rtime')
return render_to_response('order.html', { 'all_rockets': all_rockets}, RequestContext(request))
order.html:
<h1>You can order a ticket here:</h1>
<form action="/order/" method="post">
<p>
<label>Rocket_line</label>
<select name="rocket_line">
{% for rocket in all_rockets %}
<option value="{{ rocket.id }}">{{ rocket }}</option>
{% endfor %}
</select>
<label>Date</label>
<input name="date" value="YYYY-MM-DD" type="text" size="10" />
<label>Number of seats</label>
<input name="number_of_seats" value="" type="text" size="10" />
<label>E-mail</label>
<input name="email" value="#" type="text" size="50" />
<br /><br />
<input class="button" value="Order" type="submit" />
</p>
</form>
<br />
Could you help me to resolve, where the problem might be?
taken from the almighty django's docs:
Step 1:
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)
Step 2:
<form action="." method="post">{% csrf_token %}
that {% csrf_token %} is all you need to add to your template.
there's other solutions around (decorators or ajax based) but this one is the fastest and most used (i think, at least... it requires no hassle whatsoever to be implemented)