I am trying to submit a form, save to database and then show the cleaned_data on a new url. In the form I have a field called job_number. I would like to send the cleaned_data over to 127.0.0.1:8000/quotes/job_number
quote/views.py:
#login_required
def quote_view(request):
data_form = QuoteInformationForm()
if request.method == "POST":
data_form = QuoteInformationForm(request.POST)
if data_form.is_valid():
data_form.save(commit=True)
return redirect('quote')
else:
print('Error')
return render(request, "index.html", {'data_form': data_form})
#login_required
def submitted_quote(request):
return render(request, "quote.html")
urls.py:
urlpatterns = [
path('home/', quote_view, name='home'),
path('quote/', submitted_quote, name='quote'),
Currently all this does is open the form at http://127.0.0.1:8000/home/ using index.html. When I submit it will send the info to the database and redirect me to http://127.0.0.1:8000/quotes. This is fine. Now I just need to show the cleaned data on this url and change the url to include the job_number at the end. How can I do this?
you need to change url pattern like this:
urlpatterns = [
path('home/', quote_view, name='home'),
path('quote/<int:job_number>/', submitted_quote, name='quote'),
]
and submitted_quotes():
#login_required
def submitted_quote(request,job_number):
job = # Get Your job
return render(request, "quote.html", {"job":job})
and :
#login_required
def quote_view(request):
data_form = QuoteInformationForm()
if request.method == "POST":
data_form = QuoteInformationForm(request.POST)
if data_form.is_valid():
data_form.save(commit=True)
return redirect('quote{}'.format(data_form.id))
else:
print('Error')
return render(request, "index.html", {'data_form': data_form})
Related
I am getting the error NoReverseMatch in Django when I try to redirect the user to a new URL after processing a form upload and successfully saving the form.
Here is my views.py
#login_required
def profile(request):
if request.method == 'POST':
profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
files = request.FILES.getlist('resume')
resumes_data = []
if profile_form.is_valid():
for file in files:
try:
# saving the file
resume = profile_form.cleaned_data['resume']
parser = ResumeParser(file.temporary_file_path())
data = parser.get_extracted_data()
resumes_data.append(data)
profile_form.instance.name = data.get('name')
profile_form.instance.email = data.get('email')
profile_form.instance.mobile_number = data.get('mobile_number')
if data.get('degree') is not None:
profile_form.instance.education = ', '.join(data.get('degree'))
else:
profile_form.instance.education = None
profile_form.instance.company_names = data.get('company_names')
profile_form.instance.college_name = data.get('college_name')
profile_form.instance.designation = data.get('designation')
profile_form.instance.total_experience = data.get('total_experience')
if data.get('skills') is not None:
profile_form.instance.skills = ', '.join(data.get('skills'))
else:
profile_form.instance.skills = None
if data.get('experience') is not None:
profile_form.instance.experience = ', '.join(data.get('experience'))
else:
profile_form.instance.experience = None
profile_form.save()
return redirect('users-profile')
except IntegrityError:
messages.warning(request, 'Duplicate resume found')
return redirect('users-profile')
profile_form.save()
messages.success(request, 'Your profile is updated successfully')
# return redirect(reverse('userprofile', kwargs={"id": request.user}))
return redirect('userprofile')
else:
profile_form = UpdateProfileForm(instance=request.user.profile)
return render(request, 'user/resumeprofile.html', {'profile_form': profile_form})
#login_required
def myprofile(request, user_id):
profile = Profile.objects.get(id=user_id)
context = {'profile':profile}
return render(request, 'user/profile.html', context)
And here is my urls.py:
urlpatterns = [
path('', jobs_views.home, name='home'), #this is home function inside the views.py in the jobs folder
path('contact',jobs_views.contact, name='contact'),
# path('jobs/', jobs_views.job_list, name='job-list'),
path('jobs/<slug:slug>', jobs_views.job_detail, name='job_detail'), #slug will help us identify the specific instance of job
path('jobs-search/', jobs_views.job_search, name='job_search'),
path('profile/', jobs_views.profile, name='users-profile'),
path('userprofile/<int:user_id>',jobs_views.myprofile, name='userprofile')
]
The error occurs when I redirect the user to userprofile but I don't get any error when I redirect them to users-profile. Attached is a screenshot of the error message displayed. The Screenshot of the error
Any help will be highly appreciated.
You can go around it by just taking the user id from the request since they are required to be logged in.
In your urls.py paths, change the path userprofile to :
path('userprofile/',jobs_views.myprofile, name='userprofile') # remove id parameter
Then in your myprofile view, change to:
#login_required
def myprofile(request):
user_id = request.user.id
profile = Profile.objects.get(id=user_id)
context = {'profile':profile}
return render(request, 'user/profile.html', context)
i have a form for update view like this:
class editpost(forms.ModelForm):
class Meta:
model = Posts
fields = ['body']
and a view like this:
#login_required
def post_edit(request, user_id, post_id):
if request.user.id == user_id:
post = get_object_or_404(Post, pk=post_id)
if request.method == 'POST':
form = editpost(request.POST, instance=post)
if form.is_valid():
ep = form.save(commit=False)
ep.slug = slugify(form.cleaned_data['body'][:30])
ep.save()
messages.success(request, 'your post edited successfully', 'success')
return redirect('account:dashboard', user_id)
else:
form = EditPostForm(instance=post)
return render(request, 'editpost.html', {'form':form})
else:
return redirect('Posts:index')
and url.py like this:
from django.urls import path
from . import views
app_name = 'Posts'
urlpatterns = [
path('', views.index.as_view(),name='index'),
path('<int:year>/<int:month>/<int:day>/<slug:slug>', views.detailPost,name='detail'),
path('addpost/<int:user_id>', views.addpost,name='addpost'),
path('delpost/<int:user_id>/<int:post_id>', views.delpost,name='delpost'),
path('editpost/<int:user_id>/<int:post_id>', views.editpost,name='editpost'),
]
when i open editpost url i got this error,what should i do to fix it?
The path for editpost should point to your view method: views.post_edit not views.editpost
path('editpost/<int:user_id>/<int:post_id>', views.post_edit, name='editpost'),
I'm trying to create a form where users can add a new topic within a category. Then the users will be able to comment on each topic. Everything was working up until I tried adding the form page for new_topic
The error I receive:
ValueError at /new_topic/
The view speak_space.views.new_topic didn't return an HttpResponse object. It returned None instead.
Heres the code for my view.py and urls.py files:
view.py
from django.shortcuts import render, redirect
from .models import Category
from .models import Topic
from .forms import TopicForm
def index(request):
"""The home page for speak_space"""
return render(request, 'speak_space/index.html')
def categories(request):
"""Show all categories."""
categories = Category.objects.order_by('date_added')
context = {'categories': categories}
return render(request, 'speak_space/categories.html', context)
def category(request, category_id):
"""Show a single category(tribe) and all of its topics(convos)."""
category = Category.objects.get(id=category_id)
topics = category.topic_set.order_by('-date_added')
context = {'category': category, 'topics': topics}
return render(request, 'speak_space/category.html', context)
def topics(request):
"""Show all topics within a category(tribe)."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'speak_space/topics.html', context)
def topic(request, topic_id):
"""Show a single topic(convo/post) and all of it's replies."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'speak_space/topic.html', context)
def new_topic(request):
"""Add a new conversation topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('speak_space:topics')
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
and heres my url file:
from django.urls import path
from . import views
app_name = 'speak_space'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# Page that shows all categories
path('categories/', views.categories, name='categories'),
# Profile page for a category
path('categories/<int:category_id>/', views.category, name='category'),
# Page that shows all topics.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic(conversation)
# Where you go after you click on someones post
path('topics/<int:topic_id>/', views.topic, name='topic'),
# Page for adding a new conversation topic
path('new_topic/', views.new_topic, name='new_topic'),
]
and my forms page:
from django import forms
from .models import Topic
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
Your new_topic view doesn't return anything in case of GET request. You shoud make return statement common:
def new_topic(request):
"""Add a new conversation topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('speak_space:topics')
# The changes are here, now return will work for all requests types POST and GET
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
Deindent the following lines
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
inside your new_topic method.
I have a contact page for my website. The contact form is working but I want to add a background image to this page (which is saved in the database).But how can I combine my email(request) and a query to get the image ?
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm
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, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('./success')
return render(request, "contact/email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
models.py
from django.db import models
class Background(models.Model):
name = models.CharField(max_length=200, null=False)
image = models.ImageField(upload_to='./background/', default=None)
def __str__(self):
return self.name
urls.py
from django.conf.urls import url
from . import views
app_name = 'contact'
urlpatterns = [
url(r'^$', views.email, name='email'),
url(r'^success/$', views.success, name='success'),
]
You could retrieve the image on your view:
def get_background():
try:
background = Background.objects.get(name="your image name") # add your filters where to get the image
if background.image and background.image.url:
return background.image.url
except Background.DoesNotExist:
return
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
...
...
# add the background to context
return render(request, "contact/email.html", {'form': form, 'background_img': get_background()})
And in your HTML (it's just a exemple, always try to style your site with a separate css file):
...
<div {% if background_img %}style="background: url('{{background_img}}') center no-repeat;"{% endif %}>
...
I have different type of users each with different template.How can I change my URL to
url(r'^something/$', views.login_user, name='login_user'),
from
url(r'^$', views.login_user, name='login_user'),
when logged in.
my views
if user is not None:
if user.is_active:
login(request, user)
if user.groups.filter(name='hod').exists():
return render(request, 'retest/hod.html', {})
elif user.groups.filter(name='principal').exists():
return render(request, 'retest/principal.html', {})
elif user.groups.filter(name='Rep').exists():
return render(request, 'retest/home.html', {})
elif user.groups.filter(name='Ajithzen').exists():
return render(request, 'event/ajithzen.html', {})
elif user.groups.filter(name='graphics').exists():
return render(request, 'event/ashok.html', {})
elif user.groups.filter(name='Event_incharge').exists():
return render(request, 'event/incharge.html', {})
elif user.groups.filter(name='Event_coord').exists():
return render(request, 'event/chair.html', {})
elif user.groups.filter(name='IEEE').exists():
return render(request, 'event/ieee.html', {})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
else:
return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
return render(request, 'retest/login.html')
urls.py
url(r'^$', views.login_user, name='login_user'),
You might want something like this in your views:
# views.py
def login_user(request):
if user is not None:
if user.is_active:
login(request, user)
# you have to include a function to retrieve the group that this user belongs to
...
# then, for example if the user belongs to 'hod'
user_group = 'hod' # for example
# use a dictionary of URL names
urls = {
"hod": "user_hod", # this is just an example, you can use any url name of your preference, more about the url names below
"principal": "user_principal",
"Rep" : "user_Rep"
"Ajithzen" : "user_Ajithzen"
"graphics" : "user_graphics"
"Event_incharge" : "user_Event_incharge"
"Event_coord" : "user_Event_coord"
"IEEE": "user_IEEE"
}
# retrieve the url name
url = urls[user_group] # so if user_group was 'hod', you'd get 'user_hod' here
return redirect(url)
else:
return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
return render(request, 'retest/login.html')
def hod_user(request):
return render(request, 'retest/hod.html', {})
def principal_user(request):
return render(request, 'retest/principal.html', {})
def Rep_user(request):
return render(request, 'retest/home.html', {})
def Ajithzen_user(request):
return render(request, 'event/ajithzen.html',{})
def graphics_user(request):
return render(request, 'event/ashok.html',{})
def Event_incharge_user(request):
return render(request, 'event/incharge.html',{})
def Event_coord_user(request):
return render(request, 'event/chair.html',{})
def IEEE_user(request):
return render(request, 'event/ieee.html',{})
The idea here is that your login_user function will authenticate the user, and check the user's group. Based on this group, the function will redirect the user to his/her respective url, using the reverse() method. More about reverse and url names here.
More about redirect here.
Then in your urls.py:
# urls.py
urlpatterns = [
url(r'^login/$', views.login_user, name='login_user'),
# all your URLs for the different groups
url(r'^user/hod/$', views.hod_user, name='user_hod'),
url(r'^user/principal$', views.principal_user, name='user_principal'),
url(r'^user/Rep/$', views.Rep_user, name='user_Rep'),
url(r'^user/Ajithzen$', views.Ajithzen_user, name='user_Ajithzen'),
url(r'^user/graphics/$', views.graphics_user, name='user_graphics'),
url(r'^user/Event_incharge$', views.Event_incharge_user, name='user_Event_incharge'),
url(r'^user/Event_coord/$', views.Event_coord_user, name='user_Event_coord'),
url(r'^user/IEEE$', views.IEEE_user, name='user_IEEE'),
...
]
Here, we have URLs that map each URL to their own view - so each user group should have their own view in your views.py which you can create yourself. Generally, here you can think of your login_user as a way to route your users to their respective pages.