test2/urls.py
from django.conf.urls import url
from .import views
from .forms import forms
urlpatterns=[
url(r'^$',views.index,name='index'),
url(r'^thankyou/$',views.thankyou,name='thankyou')
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
views.py
this view should redirect to /test2/thankyou/ but why it is going to /thankyou
and what to do enable the view given by redirect method
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thankyou/')
else:
form = Get_name()
return render(request, 'test2/name.html' , {'form':form})
def thankyou(request):
return HttpResponse('sai chaitanya')
name.html
after submitting the form it should redirect to test2/thankyou but it is going to /thankyou.
<form action="/thankyou/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')]
class Get_name(forms.Form):
user_name = forms.CharField(label='user name',max_length='50',required=True)
pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password')
pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password')
email = forms.EmailField(label='email',max_length='100')
mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10')
address = forms.CharField(label='Address',max_length='100')
user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice))
It is going to /thankyou/ because you have hardcoded the URL /thankyou/:
return HttpResponseRedirect('/thankyou/')
You can redirect to /test2/thankyou/ by changing the code to:
return HttpResponseRedirect('/test2/thankyou/')
However the best practice is to reverse the URL instead of hardcoding it:
from django.urls import reverse
return HttpResponseRedirect(reverse('thankyou'))
This can be simplified using the redirect shortcut:
from django.shortcuts import redirect
return redirect('thankyou')
Related
Upon providing valid data and submitting a form, I get the following: Forbidden (CSRF cookie not set.): /membership/success/. I have a {% csrf_token %} in my template and my settings.py middleware is configured for CSRF.
#urls.py
from django.contrib import admin
from django.urls import path, include
from membership import views as ms_views
membership_patterns = ([
path("", ms_views.RegistrationPage.as_view(), name="register"),
path("success/", ms_views.SuccessPage.as_view(), name="success")
], 'membership')
urlpatterns = [
path('admin/', admin.site.urls),
path('membership/', include(membership_patterns, namespace="new_members"))
]
# membership/views.py
from django.shortcuts import render
from django.template.loader import get_template
from django.views import View
from django.http import HttpResponse, HttpResponseRedirect
from membership.forms import RegisterForm
from django.urls import reverse
# Create your views here.
class RegistrationPage(View):
def get(self, request):
register_page = get_template('membership/signup.html')
register_form = RegisterForm()
return HttpResponse(register_page.render({'form' : register_form}))
def post(self, request):
submitted_form = RegisterForm(request.POST)
if submitted_form.is_valid():
return HttpResponseRedirect(reverse('membership:success'))
return HttpResponse(reverse('membership:register'))
class SuccessPage(View):
def get(self, request):
return HttpResponse("Success")
# signup.html
{% extends 'index.html' %}
{% block content %}
<form action="{% url 'membership:success' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
Once the form is submitted and valid, I'm expecting a 302 to occur. Like I said though I get 403 forbidden.
Since your success page has no logic, you can choose to exempt CSRF token for that.
Import the following module
from django.views.decorators.csrf import csrf_exempt
and put #csrf_exempt at the start of function
#csrf_exempt
def get(self, request):
return HttpResponse("Success")
Refer to https://docs.djangoproject.com/en/2.2/ref/csrf/
However, it is better to include {% csrf_token %} for each template you use to ensure consistent passing around of CSRF token
I have tried to entered data to Mysql database using Django. The user enters the required data through addSubscriber.html page to save in the database but the data entered is not saved in the database. Whenever I check the Mysql table (in this case 'Subscribers' table), the table is empty. Should I install mysql-connecter or not?
Here are my files:
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views import generic
from .models import Subscribers
from .forms import addSubsForm
#login_required
def dashboard(request):
user = request.user
context = {'user': user}
template = 'dashboard.html'
return render(request, template, context)
#login_required
def addSubscriber(request):
template = 'addSubscriber.html'
if request.method == 'POST':
form = addSubsForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
area = form.cleaned_data['area']
phoneNumber = form.cleaned_data['phoneNumber']
installationCost = form.cleaned_data['installationCost']
billNumber = form.cleaned_data['billNumber']
print name
Subs = Subscribers.objects.create(name=name, area=area, phoneNumber=phoneNumber, installationCost=installationCost, billNumber=billNumber)
Subs.save()
return redirect('report')
else:
form = addSubsForm()
return render(request, template, {'form': form})
#login_required
def report(request):
context = locals()
template = 'report.html'
return render(request, template, context)
models.py
from __future__ import unicode_literals
from django.db import models
class Subscribers(models.Model):
name = models.CharField(max_length=120)
area = models.CharField(max_length=30)
phoneNumber = models.CharField(max_length=10)
installationCost = models.CharField(max_length=10)
billNumber = models.CharField(max_length=100, unique=True)
addSubscriber.html
{%extends 'base.html'%}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="col-xs-7">
{% if form %}
<br>
<form class="POST" action="." method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit form" class="btn btn-primary"/>
</form>
{% endif %}
</div>
</div>
{% endblock %}
urls.py
from dashboard import views as dashboard_views
from profiles import views as profiles_views
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', profiles_views.home, name='homepage'),
url(r'^contact/$', profiles_views.contact, name='contact'),
url(r'^dashboard/$', dashboard_views.dashboard, name='dashboard'),
url(r'^dashboard/addSubscriber/$', dashboard_views.addSubscriber, name='addSubscriber'),
url(r'^dashboard/userDetail/$', dashboard_views.userDetail, name='userDetail'),
url(r'^dashboard/report/$', dashboard_views.report, name='report'),
url(r'^account/', include('allauth.urls')),
]
# this statement says that: if in the settings file, DEBUG is true than use this static URL
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Since you are using two databases, for saving entities you should specify which database to save by specifying
Subs.save(using='db2')
According to Django documentation:
If you don’t specify using, the save() method will save into the
default database allocated by the routers.
well you dont need all this extra things in the view as you are using form and why use create and also save??
just try this inside the form.is_valid
if form.is_valid():
f = form.save(commit=False)
f.save(using='db2')
return redirect('report')
I am new to Django 1.9 and I am currently coding a website. I am trying to make a contact form to go on the contact page. I have used the following code - which is in the a file called email.html:
{% extends 'blog/base.html' %}
<form method="post">
{% csrf_token %}
{{ form }}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
I've defined it in the view.py file:
from .forms import PostForm, ContactForm
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['nmam.ltd#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
return render(request, "blog/email.html", {'form': form})
def thanks(request):
return HttpResponse('Thank you for your message.')
.....
As well as in the forms.py file:
from django import forms
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea)
Also, in the urls.py file:
from django.conf.urls import patterns, url
from . import views
urlpatterns = [
url(r'^general.html/$', views.general, name='general'),
url(r'^dcmain.html/$', views.dcmain, name='dcmain'),
url(r'^dcmain.html/big_data.html/$', views.big_data, name='big_data'),
url(r'^dcmain.html/Data_Architecture.html/$', views.Data_Architecture, name='Data_Architecture'),
url(r'^dcmain.html/BI_MI.html/$', views.BI_MI, name='BI_MI'),
url(r'^dcmain.html/Master_Data.html/$', views.Master_Data, name='Master_Data'),
url(r'^dcmain.html/Data_Q.html/$', views.Data_Q, name='Data_Q'),
url(r'^dcmain.html/Project_M.html/$', views.Project_M, name='Project_M'),
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
]
When I link the email.html file to the main page and click on the link and it just shows the home page even though the url says I am on the email.html page (shown below):
I am totally new to programming in Django. I have tried researching it however, I can't find a solution. Please can someone help me.
Your URLs are most likely the problem. You can read more on Django URLs here.
Note, as the Django docs mention, the first URL pattern which matches the requested URL will be used. As a basic rule of thumb, I recommend putting your more specific URL patterns before your blank url patterns. For instance:
urlpatterns = [
url(r'^email.html/$', views.email, name='email'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^$', views.index, name='some_name'),
]
If this urls.py file is being included from a project urls.py file, you'll want these urls to be included before your root url pattern.
urlpatterns = [
url(r'^blog/', include('blog.urls', namespace='blog'),
url(r'', views.site_home, name='site_home'),
]
Which would then make your url to this page
Email
Which would render as
Email
I am new to django and I am currently trying to build a website that allows users to sign in and view other users profiles. So far I have managed to let users sign in but I can't work out how to view other peoples profiles.
Each profile uses the users username to create a url for their profile. Currently if I sign in as one user and change the URL to another users profile URL, it still displays the current users profile. I want something similar to pinterest where any person whether they are signed in or not can view peoples profiles.
Any help would be appreciated!
View
from django.http import HttpResponse
from django.shortcuts import render
from howdidu.forms import UserProfileForm
from howdidu.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
def index(request):
context_dict = {'boldmessage': "I am bold font from the context"}
return render(request, 'howdidu/index.html', context_dict)
#user profile form
#login_required
def register_profile(request):
profile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return index(request)
else:
print form.errors
else:
form = UserProfileForm()
return render(request, 'howdidu/register_profile.html', {'form': form})
#profile page using user name as url
#login_required
def profile_page(request, username):
user = get_object_or_404(User, username=username)
return render(request, 'howdidu/profile.html', {'profile_user': user})
project url
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView): #redirects to home page after registration
def get_success_url(self,request, user):
return '/register_profile'
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'howdidu_project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'', include('howdidu.urls')),
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #redirects to home page after registration
(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^(?P<username>\w+)/', include('howdidu.urls')), #do i need this?
)
# media
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
app url
from django.conf.urls import patterns, url
from howdidu import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
)
template
{% extends 'howdidu/base.html' %}
{% load staticfiles %}
{% block title %}{{ user.username }}{% endblock %}
{% block body_block %}
{% if user.is_authenticated %}
<h1>{{ user.username }} welcome to your profile page</h1>
<img src="{{ user.userprofile.profile_picture.url }}" width = "150" height = "150" />
<h2>{{ user.userprofile.first_name }}</h2>
<h2>{{ user.userprofile.second_name }}</h2>
<h2>{{ user.userprofile.user_country }}</h2>
{% endif %}
{% endblock %}
Register urls of your app in the configuration folder project_name/urls.py :
E.g :
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^user/', include('<app_name>.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Add a new route in your <app_name>/urls.py.
E.g :
from . import views
urlpatterns = [
url(r'profile/(?P<username>[a-zA-Z0-9]+)$', views.get_user_profile),
]
Add a view in <app_name>/views.py that take username (username of the user) to retrieve its information and send them into a template
E.g :
from django.shortcuts import render
def get_user_profile(request, username):
user = User.objects.get(username=username)
return render(request, '<app_name>/user_profile.html', {"user":user})
Create a template file in <app_name>/templates/<app_name>/user_profile.htmlto display user object :
{{ user.username }}
{{ user.email }}
{{ user.first_name }}
{{ user.last_name }}
Replace <app_name> by the name of your app and it should be good.
Have stuck here for 2 days. Hoping to get some enlightenment. The error code here is "'inputform' object has no attribute 'get'". I highly suspect the error is because of the forms.py. I want to make a dynammic choice field list there.
Model.py
from django import forms
from django.forms import ModelForm
from django.db import models
from dupont.models import dupont
class input(models.Model):
...
Region=models.CharField(max_length=100)
Forms.py
from django import forms
from django.forms import ModelForm
from .models import input
from anothermodel.models import A
from django.contrib.auth.models import User
import Queue
class inputform(forms.ModelForm):
regionlist = forms.ChoiceField(label=u'Region',choices=())
def __init__(self,*args,**kwargs):
super(inputform,self).__init__(*args,**kwargs)
self.fields['regionlist'] = forms.ModelChoiceField(queryset=anothermodel.objects.values('Region').distinct())
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import inputform
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def input(request):
if request.method == 'POST':
form = inputform(request.POST)
if form.is_valid():
return HttpResponseRedirect('templates/About')
else:
form = inputform()
return render_to_response('inputform.html', {
'form': form,
})
Part of html
<body>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post">{% csrf_token %}
{{ form.regionlist }}
{% for region in form.regionlist.choices %}
<option value="{{ val }}" {% ifequal data.val val %}selected {% endifequal %}>
{% endfor %}
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from metrics import views
from django.views.generic.list import ListView
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from inputform.views import input,ifglobal
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/',include('login.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^input', 'inputform.views.inputform'),
)
The trackback
Traceback:
File "C:\Python27\lib\site-packages\django-1.8.3 py2.7.egg\django\core\handlers\base.py" in get_response
223. response = middleware_method(request, response)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\middleware\clickjacking.py" in process_response
31. if response.get('X-Frame-Options', None) is not None:
Exception Type: AttributeError at /input
Exception Value: 'inputform' object has no attribute 'get'
The error is indeed in your URLs. Your pattern is pointing at 'inputform.views.inputform', ie the form, not the view. It should be 'inputform.views.input'.