AttributeError (Django) - django

I am getting an error:
'FeedBackForm' object has no attribute 'FeedBackForm'
I have tried all troubleshooting steps but no luck. It will be much appreciable if anyone can help.
form.py
from django import forms
class FeedBackForm(forms.Form):
name=forms.CharField()
Ldap_id=forms.CharField()
email=forms.EmailField()
company_name=forms.CharField()
feedback=forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render
from testapp import forms
# Create your views here.
def feedback_view(request):
form = forms.FeedBackForm()
# As here we are sending details to register.html and in html file
# we have not mentioned action where this file will go
# so it will come back here in views.py file only. :)
if request.method == 'POST':
form1 = form.FeedBackForm(request.POST)
if form1.is_valid():
print("Form Validation sucess and printing feedback info")
# Now to capture data we will use cleaned_data===>cleaned_data==>{name:value}
print('Name of editor:', form1.cleaned_data['name'])
print('LDAP of editor:', form1.cleaned_data['Ldap_id'])
print('EmailId:', form1.cleaned_data['email'])
print('Company:', form1.cleaned_data['company'])
print('Feedback provided:', form1.cleaned_data['feedback'])
# Note this above if form.is_valid(): will start working
# only when we will submit form otherwise it will not start.
my_dict = {'form': form}
return render(request, 'testapp/register.html', context=my_dict)
urls.py
from django.contrib import admin
from django.urls import path
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',views.feedback_view),
]

You can not use form.FeedbackForm, since you assigned form as FeedbackForm object. You should use forms.FeedbackForm:
from django.shortcuts import render
from testapp import forms
def feedback_view(request):
form = forms.FeedBackForm()
# As here we are sending details to register.html
# and in html file we have not mentioned action where
# this file will go so it will come back here in views.py
# file only. :)
if request.method == 'POST':
form1 = forms.FeedBackForm(request.POST)
if form1.is_valid():
print("Form Validation sucess and printing feedback info")
# Now to capture data we will use cleaned_data===>cleaned_data==>{name:value}
print('Name of editor:', form1.cleaned_data['name'])
print('LDAP of editor:', form1.cleaned_data['Ldap_id'])
print('EmailId:', form1.cleaned_data['email'])
print('Company:', form1.cleaned_data['company'])
print('Feedback provided:', form1.cleaned_data['feedback'])
# Note this above if form.is_valid(): will start working only
# when we'll submit form otherwise it will not start.
my_dict = {'form': form}
return render(request, 'testapp/register.html', context=my_dict)

Related

django redirect after form submission not working

new to django
so this one probably has a very simple answer but i cannot for the life of me find the specific solution to this. I am simply trying to redirect to a new URL after a form submission with a FileField.
I can navigate to the URL separately and it works fine.
The file uploads correctly so I know it is validated correctly.
But the redirect returns the following error:
Reverse for 'success' not found. 'success' is not a valid view function or pattern name.
I have tried a bunch of different naming conventions, but none has worked. It looks to me like I have setup the URL and passed it correctly.
Would really appreciate some help with this. The simplest problems are the most frustrating!
Here are the views.
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .forms import InvestmentReportForm
def upload(request):
if request.method == 'POST':
form = InvestmentReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = InvestmentReportForm()
return render(request, 'app/upload.html', {'form': form})
def success(request):
return HttpResponse("File successfully uploaded")
And my urls.py:
app_name = 'app'
urlpatterns = [
path('', views.index, name='index'),
path('upload/', views.upload, name='upload'),
path('success/', views.success, name='success'),
path('performance/', views.performance, name='performance'),
]
The answer was simple as I suspected. For others, if you use a namespace for a set of url patterns, you have to refer to that namespace when calling those urls. For this example:
return redirect('app:success')
def upload(request):
if request.method == 'POST':
form = InvestmentReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('success/')
else:
form = InvestmentReportForm()
return render(request, 'app/upload.html', {'form': form})

User matching query does not exist - django

I have a page which shows the user and their about. And in that, there's a link to update their about. But when I open that link it shows me with this error:
DoesNotExist at /profile/user/update_about/
User matching query does not exist.
And the traceback hightlights this line, which from the profile method in the views:
13. user = User.objects.get(username=unquote(user_name))
However this error does not occur when I load the profile method. It occurs only on the update_profile method in the views.
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from urllib import unquote
from django.contrib.auth.models import User
from models import About
from forms import AboutForm
# Create your views here.
def profile(request, user_name):
user = User.objects.get(username=unquote(user_name))
about = About.objects.get_or_create(user=user)
about = about[0]
return render(request, 'user_profile.html', {
'user':user,
'about_user':about
})
def update_about(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method == 'POST':
form = AboutForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
about = About.objects.get(user=user)
form = AboutForm(initial={'dob':about.dob})
return render(request, 'update_about.html',{
'form':form
})
urls.py
urlpatterns = patterns('',
# Examples:
url(r'(?P<user_name>[\w#%.]+)/$', 'user_related.views.profile', name='profile'),
url(r'(?P<user_name>[\w#%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),
What is causing this? Your help will be very much appreciated. Thank you.
You forgot to add the caret sign (^) at the first position of regex. So the first regex matched "update_about/" part of the url.
Fixed code:
url(r'^(?P<user_name>[\w#%.]+)/$', 'user_related.views.profile', name='profile'),
url(r'^(?P<user_name>[\w#%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),

Django - how to create and use context processors / the variables which the context processors return

Along with my
settings.py
and
urls.py
file, I created a
context_processors.py
file in the same directory. This is my context_processors.py file:
from django.contrib.auth.forms import AuthenticationForm
def loginFormCustom(request):
form = AuthenticationForm()
return {'loginForm': form,}
and this is my views.py:
from django.template import RequestContext
from tp.context_processors import loginFormCustom
def main_page(request):
variables = { 'title': 'This is the title of the page' }
return render(request, 'main_page.html', variables, context_instance=RequestContext(request, processors = loginFormCustom))
Now, when I run this and go to The URL which calls the main_page view, it gives me a TypeError at / saying:
'function' object is not iterable
and the traceback leads to this:
return render(request, 'main_page.html', variables, context_instance=RequestContext(request, processors = loginFormCustom))
any idea why? Am I using the context processor correctly?
The Django Docs say that the AuthenticationForm is just that, it is a Form, so I believe that you would need to call it in this way:
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
def main_page(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
# log in user, etc...
else:
form = AuthenticationForm() # Unbound Form
return render(request, 'main_page.html', context_instance=RequestContext(request, {'form': AuthenticationForm}))

Django retrieve data from db to complete a url pattern

I know this is an easy question, I am just not getting something...so thank you for your patience and advice.
I have a view that asks a user to register to use our app. The data he/she submits is stored in a database and he is sent off to another page to set up the application:
#views.py
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/dev/leaguepage/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
Rather than sending ALL users to the same page '/dev/leaguepage/', I need to send each user to his own page based on the PK in the database like: '/dev/PrimaryKey/' I am not sure how to make this happen either on the views file or in the URLs.py file:
#urls.py
from django.conf.urls.defaults import patterns, include, url
from acme.dc_django import views
urlpatterns = patterns('',
url(r'^leaguepage/$','acme.dc_django.views.leaguePage'),
url(r'^$', 'acme.dc_django.views.regPage'),
)
Thank you for your help!
dp
Updated code:
#url
url(r'^user/(?P<id>\d+)/$','acme.dc_django.views.leaguePage', name="league_page"),
#view
def regPage(request, id):
form = RegForm(request.POST)
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('league_page', kwargs={'id' :id}))
#return HttpResponseRedirect('/dev/leaguepage/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
You can do a reverse lookup on your leaguePage to do your redirect, passing in the values you need to resolve the pattern. You'll need to add a name to the URL pattern you want to reverse, but basically the syntax is:
return HttpResponseRedirect(reverse('my_detail', args=(), kwargs={'id' : id}))
Example URL pattern and view:
urlpatterns = patterns('my_app.views',
url(r'^my-pattern/(?P<id>\d+)/$', 'my_action', name='my_detail'),
)
def my_action(request, id):
#do something
Hope that helps you out.

Django View Value Error

I'm hitting a wall with this error. I'm sure I'm overlooking something basic, just can't seem to figure it out...
ValueError at /sing/register
The view sing.singer.views.grade didn't return an HttpResponse object.
the view file...
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponseRedirect
from django.template import Template, RequestContext
from dash.forms import GradeForm
def register(request):
if request.method == 'POST':
form = GradeForm(data=request.POST)
if form.is_valid():
new_dash_profile = form.save()
new_user = form.save()
return HttpResponseRedirect("/success/")
else:
form = RegisterForm()
return render_to_response('grade.html',{'form':form},context_instance=RequestContext(request) )
my urls.py
urlpatterns = patterns('dashboard.dash.views',
(r'^sing/register','register' ),)
my settings.py
TEMPLATE_DIRS = (
"/home/django/testing/sing/grade/templates",)
def register(request):
if request.method == 'POST':
form = GradeForm(data=request.POST)
if form.is_valid():
new_dash_profile = form.save()
new_user = form.save()
return HttpResponseRedirect("/success/")
else:
form = RegisterForm()
return render_to_response('grade.html',{'form':form},context_instance=RequestContext(request) )
your indents look off?
Initially you are entering the view with request != 'POST' which will never reach that else statement at the bottom, so you dont get a HttpResponse.
The other thing that looks strange is even if you fix your indents, you show the RegisterForm initially, and after the post request, you put the data from your RegisterForm into a GradeForm, if that doesn't validate you show pass your GradeForm to your template. Is this what you intended?
also in your urls.py I would add / to:
(r'^sing/register','register' ),)
like:
(r'^sing/register/','register' ),)
unless you want it to match (for example):
www.site.com/sing/registerasdf/
i might even suggest using '/$' at the end like this:
(r'^sing/register/$','register' ),)
to prevent matches to (for example):
www.site.com/sing/register/asdf/asdf/asdf/
www.site.com/sing/register/asdf/asdf/
www.site.com/sing/register/asdf/
Judging from the code, the only time it does not return a HttpResponse is when it's not a POST request. Maybe you are doing a GET instead?
I think its your HttpResonseRedirect. I can't say I've used it that often (if at all). If I were you I would try shortcut redirect
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect