not sure what to put in action attribute in form - python

This code is for my signup page as you can see action is set for signup
{% block content %}
<form class="form-horizontal" action="signup" method="post">
{% csrf_token %}
{{ form }}
<br />
<input type="submit" value="Sign up" class="btn btn-default" />
</form>
{% endblock %}
This is my views.py in the same app
from django.shortcuts import render
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('app:home')
# log the user in
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})
This is my url for which doesn't work
path('signup/', accounts_views.signup, name='signup')

Related

Don't return forms in context if they are not altered?

In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit).
All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button.
Is there any way to not return the form again?
home.html
....
<body>
{% load bootstrap4 %}
<form action="" method="POST" novalidate>
{% csrf_token %}
{% bootstrap_form form %}
</form>
<form action="" method="POST" novalidate>
{% csrf_token %}
<button class="btn btn-primary" name="click_button" type="submit">Grafik</button>
</form>
</body>
....
views.py
def get_post_from_submit(request):
if request.method == 'POST':
if "book_field" in request.POST:
# Do Stuff
form = form_book(request.POST)
if "click_button" in request.POST:
# Do Stuff
# Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context...
form = form_book()
return render(request, 'home.html',{"form": form})
One method would be to encapsulate just one form tag across both sections.
<form action="" method="POST" novalidate>
{% bootstrap_form form %}
<input type="submit" name="action" value="FormSubmit"/>
{% csrf_token %}
<input type="submit" name="action" value="Grafik"/>
</form>
Using name="action" you can differentiate the POST action in the view like so:
def get_post_from_submit(request):
if request.method == 'POST':
form = form_book(request.POST)
if request.POST['action'] == 'FormSubmit':
[...]
elif request.POST['action'] == 'Grafik':
[...]
return render(request, 'home.html',{"form": form})
The form_book will no be able to retain the form data whenever the Grafik POST type is send to the view.

csrf_token verification failed or aborted error with form

I'm getting CSRF verification failed. Request aborted.
My index view:
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'tasks':tasks,'form':form}
return render(request, 'tasks/list.html', context)
My list.html template with form:
<h3>TO DO</h3>
<form method="POST" action="/">
{% csrf_token %}
{{ form.title }}
<input type="submit" name="" value="Create Task">
</form>
{% for task in tasks %}
<div>
<p>{{ task }}</p>
</div>
{% endfor %}

django login form returns 'AnonymousUser' object has no attribute '_meta'

I am working on a django web app. In this web app, I have a login page. But when I use the click the login button, I get the following error message
'AnonymousUser' object has no attribute '_meta'
I tried looking for this online and found these links in StackOverflow. link1 and link2. But the answers provided in these links do not seem to be working for me.
This is my code so far
views.py
def login_page(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
user = form.get_user()
login(request, user)
if form.is_valid():
return redirect('global:homepage')
else:
form = AuthenticationForm()
return render(request, 'accounts/login.html', {'form': form})
login.html
<form class="" action="{% url 'accounts:login' %}" method="post">
{% csrf_token %}
{% for field in form %}
<p>
<div class="form-group">
{% render_field field class="form-control" placeholder=field.label %}
{% if field.help_text %}
<p class="help-block"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
{% for error in field.errors %}
<p style="color: red">{{ error|add_class:'text-danger' }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Log in</button>
</form>
Not sure what I am doing wrong or what the error message means
You need to call form.is_valid() before retrieving and logging in the user as they may not have provided the correct credentials
def login_page(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('global:homepage')
else:
form = AuthenticationForm()
return render(request, 'accounts/login.html', {'form': form})

Register page couldn't register user

I have setup register page by Django. The URL of register input on IE, register page is ok, but I cliked 'register' button on page, no register form display.
enter image description here
users\urls.py
urlpatterns = [
# register page
re_path('^register/$', views.register, name='register'),
]
users\views.py
def register(request):
"""register new user"""
if request.method != 'POST':
# display blank register form
form = UserCreationForm()
else:
# deal filled form
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# auto login, and redirect to home page
authenticated_user =authenticate(username=new_user.username,password=request.POST['password1'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
register.html
{% extends "learning_logs/base.html" %}
{% block content %}
<form method="post" action="{% url 'users:register' %}">
{% csrf_token %}
{{ form.as_P }}
<button name="submit">register</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}" />
</form>
{% endblock content %}
These are three methods to render the form.
{{ form.as_table }} will render them as table cells wrapped in tags
{{ form.as_p }} will render them wrapped in tags
{{ form.as_ul }} will render them wrapped in li
You can manually render the form with HTML also but fields name should be the same as the registration form.

Basic Django form response

I am new to Django and looking to build a quick form with a response.
I am trying to build a form which would ask the user to input his name when the user clicks submit the page should reload and just say "Hello .
urls.py
class Question1Form(forms.Form):
n = forms.CharField(max_length=100,
widget=forms.TextInput(
attrs={'placeholder': 'Number', 'class': 'form-control'}))
views.py
def home(request):
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = [Question1Form.ans()]
return HttpResponse(Question1Form.n)
else:
form = Question1Form()
return render(request, 'index.html', {'form': form})
index.html
<form action="" method="post" class="form">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="form-row form">
<div class="col-sm-4">
{{ form.n.errors }}
{{ form.n }}
</div>
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
So how the code s
You should call instance field, not class field and get value from validated(cleaned) data (see documentation):
return HttpResponse(form.cleaned_data['n'])
If you want to reload the same template with n value:
return render(request, 'index.html', {'form': form, 'n': form.cleaned_data['n']})
and at the template add:
{% if form.is_valid %}
<p> Hello {{ n }} </p>
{% endif %}
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = form.save()
return render(request, 'index.html', {'created': True})
Then in your HTML you can say
{% if created %}
<p> Hello </p>
{% endif %}
edit I see now you have no action in your form.
So you need to point to that view in your URLS.py.
for example.
from myapp import views as app_views
from django.conf.urls import url
urlpatterns =[
url(r'^my_form/$', app_views.home, name='save_form'),
]
And then add the action to your form.
<form action="{% url 'save_form' %}" method="post" class="form">

Categories

Resources