When I tried to register in my site, it's instantly buffering,
The server is working properly and others were coded finely.
The urls.py
urlpatterns = [
#Login Page
url(r"^login/$", login, {'template_name':'users/login.html'},
name='login'),
#Logout Page
url(r"^logout/$", views.logout_view, name="logout"),
# Registration Page
url(r"^register/$", views.register, name='register'),
]
The views.py
def register(request):
"""Register a new user."""
if request.method != "POST":
#display blank register form.
form = UserCreationForm()
else:
# process completed form.
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# Log the user in and then redirect to home page
authenticate_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticate_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
Double checked I am in the right views.py
The register.html is:
{% extends "learning_logs/base.html" %}
{% block content %}
<form action="{% url "users:register" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">log in</button>
<input type="hidden" name="next" value="{% url "learning_logs:index" %}">
</form>
{% endblock content %}
Where might be the problem live?
Related
The form is always sending a Get request instead of a Post which has been explicitly added using method = "POST". So, not able to persist the data to db. I have just started with Django so, any help will be appreciated.
Below are the code snippets:
create_order.html
<form method="POST" action="{% url 'home' %}">
{% csrf_token %}
{{form}}
<input class="btn btn-primary btn-sm" type="submit" name="Submit">
</form>
urls.py
urlpatterns = [
path('', views.dashboard, name='home'),
path('products/', views.product, name='products'),
path('customer/<str:cust_id>/', views.customer, name='customer'),
path('create_order/', views.create_order, name='create_order'),
]
views.py
def create_order(request):
form = OrderForm()
if request.method == 'POST':
print("In Post", request.method)
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
print("In else", request.method)
print(form.is_valid())
if form.is_valid():
form.save()
return redirect('/')
context = {'form' : form}
return render(request, 'accounts/create_order.html', context)
terminal output
In else GET False
You are making a POST request to the wrong view. It should be the create_order view, so:
<form method="POST" action="{% url 'create_order' %}">
{% csrf_token %}
{{ form }}
<input class="btn btn-primary btn-sm" type="submit" name="Submit">
</form>
Note that you should not validate the form in case of a GET request, since then you only render the form. So the view logic should be:
def create_order(request):
if request.method == 'POST':
print("In Post", request.method)
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = OrderForm()
context = {'form' : form}
return render(request, 'accounts/create_order.html', context)
Try to add form action method in your HTML file
<form action="" method="post">{% csrf_token %}
{{ form}}
<input type="submit" value="Submit Feedback" />
</form>
</div>
I am trying to build a simple blog with a basic post function through a very simple form. The function I am trying to accomplish is:
if the new post POSTs (no errors etc.) save to the database and redirect to the newly created post_details page. Otherwise I want it to re render the post form again. I keep getting the error NoReverseMatch at /post/pk and I cannot find my error. I am obviously not understanding something properly. The related code is below:
views.py
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
post_edit.html
{% extends 'blog/base.html' %}
{% block content %}
<h2>New post</h2>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
]
I found my error inside my link for in my template view post_detail.html:
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
It was redirecting properly to post_detail.html but the link above was breaking my page.
guys i need a small help
here is my views.py
def signup(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
verification=VerificationForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
username = userObj['username']
email = userObj['email']
password = userObj['password']
return HttpResponseRedirect('/index/verification/')
# if
if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()):
User.objects.create_user(username, email, password)
user = authenticate(username = username, password = password)
login(request, user)
return HttpResponseRedirect('/')
else:
raise forms.ValidationError('Looks like a username with that email or password already exists')
else:
raise forms.ValidationError('a valid')
else:
form = UserRegistrationForm()
verification = VerificationForm()
return render(request, 'question/signup.html',context= {'verification':verification,'form' : form})
here you can see i have declared two context variables one is form and the other one is verification now i want to use
now this is my signup.html
{% extends 'question/index.html '%}
{% block body_block %}
<div class="conrainer">
<form method="POST">
{% csrf_token %} {{ form.as_p }}
<button type="submit">Submit</button>
</form>
facebook auth
</div>
{% endblock %}
now i have used form variable in this page
and i want to use verification varible in another page as django views are not made to use two templates in a single view
after searching a lot in online forums i came to know about {% include tag %}
after trying to use that tag after going through documentation
this is how my verification.html is
{% include 'question/signup.html' with obj=verification only%}
<div class="container">
<form method="post">{% csrf_token %}
<p>{{verification.as_p}}</p>
<p>{{obj.as_p}}</p>
<input type="submit" name="verify" value="" action='.' align='center'name='submit'>
</form>
</div>
here is my urls.py file
urlpatterns = [
# url(r'^/',views.home,name='home'),
url(r'^home/',Home,name='home'),
url(r'^ques/',Create.as_view(success_url="/index/home/"),name='ques'),
url(r'^signup/',signup,name='signup'),
# url(r'^signup/',MyFormView.as_view(),name='signup'),
url(r'^verification/',TemplateView.as_view(template_name="question/verification.html")),
url(r'^logout/$', auth_views.logout,name='logout'),
url(r'^search/',Search,name='search'),
url(r'^accounts/', include('allauth.urls')),
# url(r'^verify/',verificationView,name='signup'),
# CreateView.as_view(model=myModel, success_url=reverse('success-url'))
]
but after trying it so many ways either obj or verification shows up in the site is there any way where i can only get the context object instead of getting the subit button and all from my signup.html using INCLUDE any kind of help is appreciated
I used Django’s built in authentication system to create a log in, sign up and log out function. I want to add the ability to change your bio so that other users can view that bio through your profile page.
Below is my code:
register.html template
{% if user.is_authenticated %}
<h3 class="Logged">You must log out first before you can register a new account</h3>
{% else %}
<div class="signup">
<form method="post" action="{% url 'register' %}">
{% csrf_token %}
<p>Username: </p>
{{ form.username }}<br>
<p>Required. 150 characters or fewer. Letters, digits and #/./+/-/_ only. Password: </p>
{{ form.password1 }}<br>
<p>Your password can't be too similar to your other personal information. Your password must contain at least 8 characters. Your password can't be a commonly used password. Your password can't be entirely numeric.</p>
<p>Password Confirmation: </p>
{{ form.help_text}}
{{ form.password2 }}<br>
<p>Enter the same password as before, for verification</p>
{% if form.errors %}
<p class="invalid">What you have entered is invalid</p>
{% endif %}
<input type="submit" = value="Register">
<br><br>
</form>
</div>
{% endif %}
views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('index')
else:
form = UserCreationForm()
context = {'form' : form}
return render(request, 'registration/register.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('login', views.log, name='log'),
path('register', views.register, name='register'),
path('accounts', views.accounts, name='accounts'),
]
Any help is appreciated
URLS.PY
from yourapp import views as yourapp_views
url(r'^user/(?P<user_login_name>[\w\-]+)/$', extension_views.view_user_profile)
YOURAPP.VIEWS.PY
from django.contrib.auth.models import User
from django.shortcuts import render
def view_user_profile(request, user_login_name):
args = {}
args['user_profile'] = User.objects.get(username=user_login_name)
return render(request, 'your_template_to_render.html', args)
your_template_to_render.html
{{ user_profile }} {{ user_profile.id }} {{ user_profile.firstname }}
I want to redirect a homepage after login in, but the request.user is always anonymous.Where the errors hide?
the code:
urls.py
urlpatterns = patterns('',
url(r'^login/$', login_view),
url(r'^main/$', main_view,name='main'),
)
i have a login form named forms.py
class LoginForm(forms.Form):
username = forms.CharField(required=True,
label='',
max_length=12,
error_messages={'required':'username'},
widget=forms.TextInput(
attrs={'placeholder':'username',
'class':'form-control'}))
password = forms.CharField(required=True,
label='',
max_length=12,
min_length=6,
error_messages={'required':'password'},
widget=forms.PasswordInput(
attrs={'placeholder':'password',
'class':'form-control'}))
def clean(self):
if not self.is_valid():
raise forms.ValidationError('username and password are required')
else:
cleaned_data = super().clean()
the view file:
def login_view(request):
if request.method == 'GET':
form = LoginForm(auto_id=False)
return render_to_response('game/login.html',
RequestContext(request, {'form': form,}))
else:
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username,
password=password)
if user is not None and user.is_active:
auth.login(request, user)
return render_to_response('game/main.html',
context_instance=RequestContext(request))
else:
return render_to_response('game/login.html',
RequestContext(request,
{'form': form,'password_is_wrong':True}))
else:
return render_to_response('weapon/login.html',
RequestContext(request, {'form': form,}))
#login_required(login_url='/game/login/')
def main_view(request):
user = request.user
return render_to_response('weapon/main.html',
{'user':user},
context_instance=RequestContext(request))
login.html include:
<form class="form-signin" role="form" action="{% url 'game:main' %}" method="post">
{% csrf_token %}
<h2 class="form-signin-heading">Login in</h2>
{{ form.as_p }}
<label class="checkbox">
<input type="checkbox" value="remember-me"> remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
main.html include:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
{% if user.is_authenticated %}
{{ user.username }} Successful
{% else %}
failed
{% endif %}
</body>
</html>
Any suggestions would be much appreciated.
After login you are redirecting the user to game/main.html whereas in my opinion you should redirect user to main_view instead.
The code block in views.py should be:-
EDITED:
if user is not None and user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/game/main')
The form in your login template is pointing to the main view action="{% url 'game:main' %}" not the login view, your form never gets handled.
You should point it to the same login view to handle the authentication, simply use action="." too keep it on the same URL as the login view or point it specifically using the same technique you're using already with main, i.e.
urlpatterns = patterns('',
url(r'^login/$', login_view, name='login'),
url(r'^main/$', main_view, name='main'),
)
And in your template:
action="{% url 'game:login' %}"