Error while passing a POST data to form wizard - django-forms

I have an initial form as below
forms.py
class LoginForm(forms.Form):
activity_no = forms.CharField()
username = forms.CharField()
views.py
def test(request):
if request.method == 'POST' :
form = LoginForm(request.POST)
if form.is_valid() :
act_no = form.cleaned_data['activity_no']
username = form.cleaned_data['username']
form_data = {}
form_data['activity_no'] = act_no
form_data['username'] = username
return render_to_response("test1.html", { 'form_data' : form_data}, context_instance=RequestContext(request))
else:
form = LoginForm()
return render_to_response("test.html", {'form': form }, context_instance=RequestContext(request))
test.html
{% extends "admin/base.html" %}
{% block content %}
<form action="/todo/test/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
test1.html
{% extends "admin/base.html" %}
{% block content %}
<form action="/todo/login/" method="post">{% csrf_token %}
{% for name, data in form_data.items %}
<input type="hidden" name={{name}} value={{data}}>
{% endfor %}
<input type="submit" value="Yes"/>
</form>
{% endblock %}
I fill this form, display few contents of a file and pass the above form data to a form wizard
But when I pass the data to the form wizard via post method in the template, I get a "ManagementForm Data missing" error but if the data is passed through the GET method, I don't get any error but as defined, the data is seen in the url in the GET method ( in my case it contains username which I don't want to disclose)
My Form Wizard
class LoginWizard(SessionWizardView):
def __name__(self):
"""When using decorators, Django tries to get the name of the
function and since we're a class, we'll fail. So add this method to
compensate."""
return 'LoginWizard'
template_name = "wizard_form.html"
def done(self, form_list, **kwargs) :
form_data = process_form_data(form_list)
My query is that how would I handle the post data in the form wizard.
Please let me know if I am missing anything or any other information is required from my end.

You need to add {{ wizard.management_form }} in your template as explained it in reference django wizard templates.
Like:
{% extends "admin/base.html" %}
{% block content %}
<form action="/todo/test/" method="post">{% csrf_token %}
{{ wizard.management_form }}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Add that in all templates for wizard.

Related

Updating a SQL Alchemy list without reloading the page?

I am working on a small Flask app and the user is able to update a list of items via using a form to submit some data.
I am currently using SQL Alchemy as the ORM for my database and using the list in my template to display the items. I want to update it so that when the list is updated. The page is updated without the user having to reload the page.
I have tried this with AJAX using the below script but the update is not occurring.
$(document).ready(function(){
$('form').on('submit',function (e) {
$.ajax({
type: 'post',
url: '/todo',
data: $('#todoInput').serialize(),
success: function (q) {
console.log(q);
}
});
e.preventDefault();
});
}
My template:
{% extends "base.html" %}
{% block script %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/custom.js') }}"></script>
{% endblock %}
{% block content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="row justify-content-md-center">
<div class="col-md-auto">
<h1>What needs to be done today?</h1>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<form action="" method="post">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.todo (id="todoInput") }}
{{ form.submit (class_="btn btn-primary btn-sm") }}
</div>
</form>
<div id="todoList">
<ul class="list-group">
{% for todo in todos %}
<li class="list-group-item d-flex justify-content-between align-items-center">
{{ todo.body }}
<button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock %}
Model:
from datetime import datetime
from app import db, login
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
todos = db.relationship('Todo', backref='owner', lazy='dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
#login.user_loader
def load_user(id):
return User.query.get(int(id))
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Todo {}>'.format(self.body)
Route:
#app.route('/todo', methods=['GET', 'POST'])
def todo():
if current_user.is_authenticated:
form = TodoForm()
todos = current_user.todos.order_by(Todo.timestamp.desc()).all()
if form.validate_on_submit():
new_todo = Todo(body=form.todo.data, owner=current_user)
db.session.add(new_todo)
db.session.commit()
flash('Todo added')
todos = current_user.todos.order_by(Todo.timestamp.desc()).all()
return render_template('todo.html', form=form, todos=todos)
return render_template('todo.html', form=form, todos=todos)
flash('You first need to login or register')
return redirect(url_for('index'))
The todos list is what im trying to update. But it just reloads the page :/
You need to do two things. Firstly you need to be sure that your database is updated. That means that your form was submitted successfully. This can be done by submitting the form manually via an ajax call. This is more or less what you did. Did you check, whether your backend receives the form-submission and updates the database?
Secondly you need to update the html in the browser. Normally the page is refreshed automatically if your form is submitted. If you dont want a page reload, you need to add some client-side logic, to ensure that the page is updated. This can easily be done with a little bit of javascript.
Edit:
Your custom js might be missing }); at the end. Or did you just forget to post it here?

form.is_valid() is false when it shouldn't be

So i'm new in Django and i'm trying some tutorials. This code is exact same as the one in tutorial but it does not work form me.
views.py
from .forms import BlogPostForm
def blog_post_create_view(request):
form = BlogPostForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
else:
print(form.slug, form.title, form.content)
template_name = "form.html"
context = {"form": None}
return render(request, template_name, context)
forms.py
from django import forms
class BlogPostForm(forms.Form):
title = forms.CharField()
slug = forms.SlugField()
content = forms.CharField(widget=forms.Textarea)
form.html
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1> {{ title }}</h1>
{% endif %}
<form method="POST" action="."> {% csrf_token %}
{{ form.as_p }}
<button type="submit">SEND</button>
</form>
{%endblock%}
So when I run this, code the is_valid() functions returns False and I get :
AttributeError: 'BlogPostForm' object has no attribute 'slug'

Django - ajax poll with results on the same page

I'm learning django and I need help with my app.
In a page I have a poll: I want that after a user has voted, the poll form disappears and a div #ajaxresults appears with the updated votes for each option.
I'm using an ajax call but I can't return the updated votes.
If I call directly '/polls/4/results' I can see the right list but I can't include that block on the same page of the form.
What am I missing?
urls.py
app_name = 'polls'
urlpatterns = [
path('', views.index, name='list'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
view.py
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
#return render(request, 'polls/results.html', {'question': question})
return redirect(question.get_absolute_url())
#require_POST
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
selected_choice = question.choice_set.get(pk=request.POST['selectionId'])
selected_choice.votes += 1
selected_choice.save()
return redirect('polls:results', question_id = question_id)
detail template (extends base.html)
<form id="quiz-module" action="#">
<input type="hidden" id="pollId" name="pollId" value="{{question.id}}">
{% csrf_token %}
<fieldset>
<h2>{{ question.question_text }}</h2>
<ul>
{% for choice in question.choice_set.all %}
<li><input type="radio" name="opt" value="{{ choice.id }}" {% if forloop.first %}required {%endif%}/>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</fieldset>
</form>
<section id="quiz-results">
<h3>Your vote</h3>
<p id="ajaxresults"></p>
<h3>All votes</h3>
<dl>
{%block updated_results %}{% endblock %}
</dl>
</section>
template vote is empty
template results (extends nothing)
{%block updated_results %}
{% for choice in question.choice_set.all %}
<dt>{{ choice.choice_text }}: </dt><dd id="choiceId-{{ choice.id }}">{{ choice.votes }}</dd>
{% endfor %}
{% endblock %}
js
var args = {
type:"POST",
url:"/polls/"+pollId+"/vote/",
data:data,
success: function( data ) {
//print your vote
results.children('#ajaxresults').html(selectionText);
form.hide('fast');
results.show('fast');
},
error: function(xhr, status, error) {
alert(error+'<br/>'+"Sorry. Can't submit your vote. Please, reload the page and try again")
},
};
$.ajax(args);

Adding an object to a dropdown list without reloading the page

Hi I have a 'member' model that references a 'role' model. What I would like is when a user creates a 'member' they can either choose from a list of default 'roles' (that have been loaded to the database when the server starts using fixtures) or they can click on add role and then type in and click submit and the newly created role is created and assigned to the newly created 'member' object.
I would like it so that I am able to just create a role without submitting, and the role then appears in the dropdown menu for the role field in the member model. Is this where I would need to learn about AJAX to implement this feature?
Models
class MemberRole(models.Model,get_fields):
name = models.CharField(max_length = 20)
def __unicode__(self):
return self.name
class Member(models.Model,get_fields):
first_name = models.CharField(max_length = 20)
role = models.ForeignKey(MemberRole, null = True, blank = True)
View
def add_member(request):
model_url = 'member-add'
if request.method == "POST":
rform = MemberRoleForm(request.POST, instance=MemberRole())
mform = MemberForm(request.POST, instance=Member())
if rform.is_valid() and mform.is_valid():
new_role = rform.save()
new_member = mform.save(commit=False)
new_member.role = new_role
new_member.save()
return HttpResponseRedirect('members')
else:
rform = MemberRoleForm(instance=MemberRole())
mform = MemberForm(instance=Member())
return render_to_response('create_model.html', {'role_form': rform, 'member_form': mform, 'model_url': model_url,},context_instance=RequestContext(request))
snippet create_model.html
<div id = "subtemplate">
<form action="{% url model_url %}" method="POST">
{% csrf_token %}
{% if model_url == 'member-add' %}
{% for field in member_form %}
{% if field.label == 'Role' %}
<div id="roleExistsMemberForm">
<button type="button" onclick="showDiv()">Add Role</button>
{{ field.errors }}
{{ field.label_tag }} {{ field }} {{ field.help_text }}
</div>
{% else %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endif %}
{% endfor %}
<div Id="addRoleOnMemberForm">
{% for field in role_form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
</div>
{% else %}
<ul>
<li>{{ form.as_ul }}</li>
</ul>
{% endif %}
<div id="centerbuttons">
<input id="save_contact" type="submit" value="Add"/>
</div>
</form>
Yes, Ajax would be the first point of call for something like this. You can submit the form in the background to a Django view, the view could then respond with a fresh list of options to re-populate the drop down list with.

Update a date-time field (from system) but don't make it visible to user

The following is my "view" which renders a form through "editpost.html". I want to update the timestamp (datetime field) to be edited by the system time, but don't want that to be visible to the user. I tried using "hidden" keyword in the modelform definition Meta class, but that does not update the time correctly. I tried doing it in the template but doesn't work. Any ideas?
def editpost(request, postid):
blog = BlogPost.objects.get(pk=postid)
if request.method == 'POST':
form = BlogPostForm(request.POST, instance=blog)
blog = form.save()
return HttpResponseRedirect('/blog/%s' % str(postid))
else:
form = BlogPostForm(initial={'timestamp': datetime.now()}, instance=blog)
form.save(commit=False)
return render_to_response("editpost.html", {'form': form, 'postid': postid}, RequestContext(request))
editpost.html
{% block content %}
<form action="." method="post">{% csrf_token %}
{% for field in form %}
{% if field.label_tag != "Timestamp" %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endif %}
{% endfor %}
<input type="submit" value="Save" />
</form>
{% endblock %}
May be better would be rewrite def save(...) of the model. You can try it:
def save(self, *args, **kwargs):
self.timestamp = datetime.now()
super(Dog,self).save(*args, **kwargs)

Resources