I'm trying to make a non model form that just gets input text for a chat like interface.
views.py
def get_input(request):
if request.method == 'POST':
form = inputForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = inputForm()
return render(request, 'index.html', {'form': form})
def shelley_test(request):
form = inputForm()
return render(request, 'shelley_test.html')
form.py
from django import forms
class inputForm(forms.Form):
input = forms.CharField(label='input field')
shelley_test.html
<form action="/get_input/" method="get">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
please please help. I'm new at django and stumped :(
You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input.
Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form.
Related
I've imported this from django.contrib.auth.forms import UserCreationForm
used csrf_token in the form but still when I hit submit the page reloads but doesn't save the data to database.
def signup(req):
if req.method == 'POST':
form = UserCreationForm(req.POST)
if form.is_valid():
form.save()
form = UserCreationForm()
reg_con={
'regform': form
}
return render(req, 'signup.html', reg_con)
form
<form action="." method="POST">
{% csrf_token %}
{{ regform.as_ul }}
<input type="submit" value="Sign Up">
</form>
This is normally because something is wrong with your form the problem is however that you each time construct a new form, and you thus can not see what went wrong. You should only create a new form in case it is a GET request, so:
def signup(req):
if req.method == 'POST':
form = UserCreationForm(req.POST)
if form.is_valid():
form.save()
else:
form = UserCreationForm()
reg_con={
'regform': form
}
return render(req, 'signup.html', reg_con)
Try removing the action attribute from your form tag. Also don't forget to redirect after calling form.save()
The form field won't show up in the browser. There is only the submit button showing up.
views.py code:
def vote(request, pk):
# check if request is post
if request.method == 'POST':
# create a form and populate it with data from request
form = forms.Vote(request.POST)
if form.is_valid():
fact = Fact.objects.get(pk=pk)
fact.votes += int(form.cleaned_data['vote'])
fact.save()
return HttpResponseRedirect(reverse(
'facts:detail',
args=(pk,)
))
else:
form = forms.Vote()
return render(request, 'facts/fact_detail.html', {'form': form})
template(fact_detail.html) code:
<form method='POST'>
{% csrf_token %}
{{ form }}
<input type="submit" value="vote" />
</form>
Form class(forms.py) code:
VOTE_CHOICES = [
(1, 'upvote'),
(0, 'downvote')
]
class Vote(forms.Form):
vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect())
In views.py for the vote method initialize the form variable locally, before passing it as a parameter.
def vote(request, pk):
form=""
//rest of the code//
return render(request, 'facts/fact_detail.html', {'form': form})
I recommend check generic editing views from django documentation I think it has the solution
[ https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-editing/#createview][1]
I am practicing Django and now working on some project. In this project, my input type isn't responding to clicks. I have tried to put same input form on other project and it's working. But on current project it isn't. Can't figure it out why.
Html code:
<form action="" method="POST">
{{ form.as_p }}
<input type="submit" value="Contact">
</form>
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass
else:
form = ContactForm()
context = {
"Welcome_text": "Sveiki atvykÄ™",
"form": form
}
return render(request, "home.html", context)
After user logs in, user is able to submit a form. On click of submit button, data is being stored in DB, but how should I connect this information to the submitting user.
I would need the code as well as the structure of the new db
Kind of starting out in django.
Any help would be appreciated!!!
I have included user as foreign key in the CustomizeRequest model, but now how do i fill in this information?
Exact Scenario: After user log in, once he comes to contactUs.html, he submits a form which tells the number of travellers. This number is being stored in the DB. But now how do I connect each of these numbers to the submitted user?
models.py
class CustomizeRequest(models.Model):
user = models.ForeignKey(User)
travellers = models.CharField(max_length=2)
def __str__(self):
return self.travellers
contactUs.html
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="btn-group" data-toggle="buttons">
{% for radio in crform.travellers %}
<label class="btn btn-default {% if radio.choice_label = '1' %}active{% endif %}" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
{{ radio.tag }}
</label>
{% endfor %}
</div>
<button type="submit" class="btn btn-default btn-block btn-warning">SUBMIT</button>
</form>
views.py
def contactUs(request):
if request.method=="POST":
form = CustomizeRequestForm(request.POST)
form.save()
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Based on catavaran answer (with a check to see if the form is valid):
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
form = CustomizeRequestForm(data=request.POST or None)
if request.method == "POST":
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
pass # could add a notification here
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Logged user is available as request.user property. You can get the unsaved model instance using form.save(commit=False) trick, set the user field and then save the instance to database:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
if request.method == "POST":
form = CustomizeRequestForm(request.POST)
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work.
Any help is appreciated.
Here is the relevant code..
This is my add/model.py
from django.db import models
from django.forms import ModelForm
class addTask(models.Model):
task = models.CharField('Task', max_length=60)
taskNotes = models.CharField('Notes', max_length=600)
def __unicode__(self):
return self.task
class addTaskForm(ModelForm):
class Meta:
model = addTask
template/addTHEtask.html. This is getting referenced correctly.
<form action="/todo/" method="post">
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
add/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from myToDo.add.models import addTask, addTaskForm
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response('addTHEtask.html', {'form': form})
To properly debug your code, change your template to:
<form action="/todo/" method="post"> {{ csrf_token }}
{{ form.errors }}
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
And your view to:
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response(
'addTHEtask.html',
{'form': form},
context_instance=RequestContext(request))
I don't think the context_instance will do anything significant for you, but it is usually the right thing to pass when using render_to_response.
Showing the errors in the form may help you track down what the actual problem is. Your code looks (mostly) correct, except the missing csrf_token. Adding the token, and displaying any errors, should show you what is going wrong.