The project I am working on is the blogging website and I am stuck at this signup process, I want it to function like after signup, the user lands on the home page, but instead this is showing me the above error
views.py:
def handleSignup(request):
if request.method == 'POST':
username = request.POST['username']
fname = request.POST['fname']
lname = request.POST['lname']
email = request.POST['email']
pass1 = request.POST['pass1']
pass2 = request.POST['pass2']
# creating users
myuser = User.objects.create_user(username, email, pass1)
myuser.first_name = fname
myuser.last_name = lname
myuser.save()
messages.success(request, 'your account have been successfully created!')
return redirect(request, "/home.html")
else:
return HttpResponse("error 404 not found")
urls.py:
urlpatterns = [
path("", views.home, name="home"),
path("contact/", views.contact, name="contact"),
path("about", views.about, name="about"),
path("signup/", views.handleSignup, name="handleSignup"),
]
forms in base.html:
<form action="/signup/" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name = 'username' placeholder="choose a unique username">
</div>
<div class="form-group">
<label for="fname">Firstname</label>
<input type="text" class="form-control" id="fname" name = 'fname' placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Lastname</label>
<input type="text" class="form-control" id="lname" name= 'lname' placeholder="Last Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name = 'email' placeholder="email#example.com">
</div>
<div class="form-group">
<label for="pass1">Choose Password</label>
<input type="password" class="form-control" name = 'pass1' id="pass1">
</div>
<div class="form-group">
<label for="pass2">Confirm password</label>
<input type="password" class="form-control" name = 'pass2' id="pass2">
</div>
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
the error log:
NoReverseMatch at /signup/
Reverse for '<WSGIRequest: POST '/signup/'>' not found. '<WSGIRequest: POST '/signup/'>' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://127.0.0.1:8000/signup/
Django Version: 3.1
Exception Type: NoReverseMatch
Exception Value:
Reverse for '<WSGIRequest: POST '/signup/'>' not found. '<WSGIRequest: POST '/signup/'>' is not a valid view function or pattern name.
Exception Location: C:\Users\jayant nigam\projects\practise\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable: C:\Users\jayant nigam\projects\practise\Scripts\python.exe
Python Version: 3.8.5
Python Path:
['C:\\Users\\jayant nigam\\projects\\everythingcs',
'C:\\Python38\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Users\\jayant nigam\\projects\\practise',
'C:\\Users\\jayant nigam\\projects\\practise\\lib\\site-packages']
Server time: Mon, 28 Sep 2020 17:39:46 +0000
the error line which it is highlighting:
return redirect(request, "/home.html")
You specified path("", views.home, name="home") in your urls.py, therefore you can just do:
return redirect("/")
You shouldn't be passing request as a first argument to redirect(), you only need to provide a URL (relative or absolute) most of the time.
Actually, as a best practice, that URL should be provided using reverse, e.g.:
from django.urls import reverse
...
return redirect(reverse('home'))
See the doc for redirect().
Related
I need to see user's input display on django's admin page, from what i have read, I need to use list_display but there is nothing appearing on admin page. Maybe there is a problem in the views.py but everything looks good.
Here is my code:
Views.py
def process_e(request):
website_name = request.POST["website_name"]
product_name = request.POST["product_name"]
phone_number = request.POST["phone_number"]
website_details = request.POST["website_details"]
website_content = request.POST["website_content"]
created_objs = Enterprise.objects.create(website_name=website_name, product_name=product_name, phone_number=phone_number, website_details=website_details, website_content=website_content)
legth_of_todos = Enterprise.objects.all().count()
created_items = Enterprise.objects.all()
if request.method == 'POST':
if request.POST.get('website_name') and request.POST.get('product_name') and request.POST.get('phone_number') and request.POST.get('website_details') and request.POST.get('website_content'):
post=Enterprise()
post.title= request.POST.get('website_name')
post.content= request.POST.get('product_name')
post.content= request.POST.get('phone_number')
post.content= request.POST.get('website_details')
post.content= request.POST.get('website_content')
post.save()
return render(request, 'enterprise.html', {"created_items":created_items})
else:
pass
else:
return render(request,'enterprise.html')
Admin.py
from django.contrib import admin
from service.models import Enterprise
class PaymentsAdmin(admin.ModelAdmin):
list_display = ('website_name', 'product_name', 'phone_number', 'website_details',
'website_content')
admin.site.register(Enterprise, PaymentsAdmin)
Models.py
from django.db import models
class Enterprise(models.Model):
website_name = models.CharField(max_length=50)
product_name = models.CharField(max_length=200)
phone_number = models.CharField(max_length=200)
website_details = models.CharField(max_length=200)
website_content = models.CharField(max_length=200)
Html
<div class="form-group">
<label>Website name</label>
<input type="text" name="website_name" class="form-control" placeholder="First name">
</div>
<div class="form-group">
<label>Product name (if there is)</label>
<input type="text" name="product_name" class="form-control" placeholder="First name">
</div>
<div class="form-group">
<label>Phone number</label>
<input type="text" claa="phone_name" class="form-control" placeholder="First name">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">What kind of content should your website upload?</label>
<textarea class="form-control" name="website_content" rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Website details</label>
<textarea class="form-control" name="website_details" rows="3"></textarea>
</div>
Yes. list_display is used to show a model's fields in the ListView of a model. You also need at least one model instance.
I have created a Django application in which i have a signup page which asks a user to upload their profile picture.
When I'm uploading the profile picture through the Django admin panel, the images are being uploaded to the correct path and are being displayed in the website. However, the error comes when I directly select the image to upload when signing up and then When I click on the uploaded image in Django admin it shows page not found and the path to the image is being showed as C:\Users\hp\Workspace\findem\media\image.jpg
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'findem/static')
]
# media folder settings
MEDIA_ROOT = os.path.join(BASE_DIR , 'media').replace('\\', '/')
MEDIA_URL = '/media/'
User Model
class UserProfile(AbstractBaseUser, PermissionsMixin):
"""Represents a user profile inside our system"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255, default=profile_pic)
profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='photos/User.jpg')
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
highest_degree_earned = models.CharField(max_length=255, blank=False)
college_name = models.CharField(max_length=255, blank=False)
graduation_year = models.IntegerField(default=2020, blank=False)
Template :
<form class="needs-validation" novalidate autocomplete="off"
action="{% url 'signup' %}", method="POST" >
{% csrf_token %}
<div id="Personal_Information">
<h5 class="loginSignup">Personal Information</h5>
<div class="form-group row">
<label for="inputprofile" class="col-sm-2 col-form-label">Profile Picture</label>
<div class="col-sm-5">
<div class="input-group">
<div class="custom-file">
<input type="file" accept="image/png, image/jpeg, image/gif" class="custom-file-input" id="inputprofile" name="inputprofile">
<label class="custom-file-label" for="inputprofile" aria-describedby="inputprofile">Choose file</label>
</div>
</div>
</div>
</div>
<div class="form-group required row">
<label for="inputname" class="col-sm-2 col-form-label">Full Name <span id="required-field">*
</span>
</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="inputname" id="inputname" placeholder="Enter Your Full Name" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter your full name.</div>
</div>
</div>
<div class="form-group row">
<label for="inputemal" class="col-sm-2 col-form-label">Email <span id="required-field">*</span></label>
<div class="col-sm-5">
<input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Enter a Valid Email Address" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please provide a valid email.</div>
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label">Password <span id="required-field">*</span></label>
<div class="col-sm-5">
<input type="password" class="form-control" id="inputPassword" name="inputPassword" placeholder="Choose a Password" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please chose a valid password.</div>
</div>
</div>
<button type="submit" class="btn btn-success mt-3" id="loginButton">Sign Up</button>
</form>
view :
def signup(request):
"""View for Signing-up into the system"""
if request.method == 'POST':
# Get form value
profile_picture = request.POST.get('inputprofile')
name = request.POST.get('inputname')
email = request.POST['inputEmail']
password = request.POST['inputPassword']
highest_degree_earned = request.POST['inputDegree']
college_name = request.POST['CollegeName']
graduation_year = request.POST['inputGradYear']
skill_1 = request.POST['upload_skill1']
skill_2 = request.POST.get('upload_skill2', '')
skill_3 = request.POST.get('upload_skill3', '')
skill_4 = request.POST.get('upload_skill4', '')
skill_5 = request.POST.get('upload_skill5', '')
skill_6 = request.POST.get('upload_skill6', '')
join_date = datetime.now()
# Check Username
if UserProfile.objects.filter(name=name).exists():
messages.error(request, "That Name already taken")
return redirect('signup')
# Check email
else:
if UserProfile.objects.filter(email=email).exists():
messages.error(request, "That email is being used")
return redirect('signup')
else:
# Looks Good
user = UserProfile.objects.create_user(profile_picture=profile_picture, name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
# #Login after register
# auth.login(request, user)
user.save()
messages.success(request, "You are now registered and can log in")
return redirect('login')
else:
return render(request, 'pages/signup.html')
Change your form tag to be be like this :
<form class="needs-validation" novalidate autocomplete="off"
action="{% url 'signup' %}", method="POST" enctype="multipart/form-data">
add request.FILES to profile_picture like that :
profile_picture = request.FILES.get('inputprofile') or None
Than in your create request you do that :
else:
if UserProfile.objects.filter(email=email).exists():
messages.error(request, "That email is being used")
return redirect('signup')
else:
# Looks Good
if profile_picture != None
user = UserProfile.objects.create_user(profile_picture=profile_picture, name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
else:
user = UserProfile.objects.create_user(name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
For the default picture try to change it to this :
profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='/media/photos/User.jpg')
In the HTML form, you need to use.
enctype="multipart/form-data"
Without that, the file is not sent to the server.
Add this tag to your form
<form method="post" enctype="multipart/form-data">
....
</form>
and to get the files at django part use request.FILES.get('filename') in your view
profile_picture = request.FILES.get('inputprofile')
I'm creating a Contact page on my portfolio site which when the user fills out and submits will automatically send it as an email to my personal email account. But when I hit Submit I get "Method Not Allowed (POST):/contact/" in my terminal, "HTTP ERROR 405" in my browser and no email in my account.
My HTML:
<form action="" method="POST">
{% csrf_token %}
<div class="row form-group">
<div class="col">
<input name="f-name" type="text" class="form-control" placeholder="First name" required>
</div>
<div class="col">
<input name="s-name" type="text" class="form-control" placeholder="Last name" required>
</div>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="email-input" aria-describedby="emailHelp" placeholder="name#mail.com" required>
<small id="emailHelp" class="form-text text-muted">I Wont Share Your Email!</small>
</div>
<div class="form-group text-center">
<textarea name="e-message" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="your message..." required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
My views.py:
class ContactView(TemplateView):
template_name = 'contact.html'
def send_message(self, request):
if request.method == 'POST':
message = request.POST['f-name', 's-name', 'email', 'e-message']
send_mail('Contact Form', message,['email#gmail.com'],
fail_silently=False)
return render(request, 'thanks.html')
My project urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('projects/', views.ProjectView.as_view(), name='projects'),
path('blog/', views.BlogView.as_view(), name='blog'),
path('contact/', views.ContactView.as_view(), name='contact'),
path('thanks/', views.ThanksView.as_view(), name='thanks'),
My application urls.py
from django.conf.urls import url
from blog import views
app_name = 'blog'
urlpatterns = [
url(r'^$', views.AboutView.as_view(), name='about'),
url(r'^projects/$', views.ProjectView.as_view(), name='projects'),
url(r'^blog/$', views.BlogView.as_view(), name='blog'),
url(r'^contact/$', views.ContactView.as_view(), name='contact'),
url(r'^thanks/$', views.ThanksView.as_view(), name='thanks'),
Iv been searching for similar answers for a few hours and anything similar hasnt helped so far Maybe I should re build my form in Django forms? I dont want to risk going too far changing too much and breaking my site!
Django does not support post method on template view implicitly. You have to define post method yourself in template view like this
class ContactView(TemplateView):
template_name = 'contact.html'
def post(self, request, *args, **kwargs):
message = request.POST['e-message']
send_mail('Contact Form', message,['email#gmail.com'], fail_silently=False)
return render(request, 'thanks.html')
The rest will be handled automatically
I tried to use 6 different tutorials to get this done, but all of them gave different variations so I'm really frustrated at the pace I'm making...
I think I'm nearing the last few steps but I need some help. Here is the code I have in my Django project:
# -- settings.py--
EMAIL_BACKEND = 'django.core.mail.backends.stmp.EmailBackend'
EMAIL_HOST = 'http://smtp.gmail.com/'
EMAIL_HOST_USER = 'a spare Gmail I have'
EMAIL_HOST_PASSWORD = 'the password'
EMAIL_USE_TLS = False
EMAIL_PORT = 465
..
# -- views.py --
# (assumed relevant imports are imported)
class ContactView(FormView):
template_name = 'CONTACT.html'
form_class = ContactForm
success_url = 'Success!'
context_vars = {
'example_name_f': 'Adam',
'example_name_l': 'Smith',
'example_email': 'smith.a#gmail.com',
'example_subject': 'Sales proposal',
'example_text': 'Hi Mark, I have a sales proposal for you!',
}
def get(self, request):
return render(request, 'CONTACT.html', ContactView.context_vars)
def contact(self, request):
if request.method == 'POST':
form = self.form_class(data=request.POST)
if form.is_valid():
time = request.POST.get('time', '')
first_name = request.POST.get('first_name', '')
last_name = request.POST.get('last_name', '')
email_address = request.POST.get('email_address', '')
subject = request.POST.get('subject', '')
text = request.POST.get('text', '')
send_mail(subject, text, email_address,
['999#outlook.com'], fail_silently=False)
return redirect('CONTACT-done.html') # CONTACT-done is a temporary success screen
return render(request, 'CONTACT.html', ContactView.context_vars)
The relevant portion of HTML:
<div class="container-fluid" style="width: 100%; height: 100%">
<form action="" method="post">
<label for="first-name">First Name</label>
<input id="first-name" name="first-name" type="text" placeholder="{{ example_name_f }}">
<!-- Note: placeholder vs value attributes similar -->
<!-- id is for HTML, name is for views.py -->
<label for="last-name">Last Name</label>
<input id="last-name" name="last-name" type="text" placeholder="{{ example_name_l }}">
<!-- Its unnecessary to use context vars for placehoder text -->
<label for="email">Email Address</label>
<input id="email" name="email" type="email" placeholder="{{ example_email }}" required>
<label for="subject">Subject</label>
<input id="subject" name="subject" type="text" placeholder="{{ example_subject }}">
<label for="text">Message:</label>
<input id="text" name="text" type="text" placeholder="{{ example_text }}" required>
<input type="submit" value="Send">
</form>
</div>
Some tutorials recommended a {{ form.as_p }} approach in HTML but some just did the basic HTML style as I did above. Not sure what to do from here.
Clicking send on my website gives a 403 CSRF verification failed. Request aborted.
Please explain in as simple a way as possible, I'm not brand new to programming but I'm not a CS person either. Thanks.
you need the CSRF token:
<form ...>
{% csrf_token %}
...
</form>
As in this official documentation example:
I am using this code for a register form. But the post request doesn't work and give me an error :
ValueError at /register/
The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
views.py
class RegisterView(View):
def get(self,request):
register_form = RegisterForm()
return render(request, 'register.html',{'register_form':register_form})
def post(self,request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get("email", "") user_psw = request.POST.get("password", "")
user_profile=UserProfile()
user_profile.username = user_name
user_profile.email = user_name
user_profile.password=make_password(user_psw)
user_profile.save()
send_register_email(user_name,"register")
pass
urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
import xadmin
from users.views import LoginView , RegisterView
import xadmin
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('',TemplateView.as_view(template_name="index.html"),name="index"),
path('login/',LoginView.as_view(),name="login"),
path('register/',RegisterView.as_view(),name="register"),
path("captcha/", include('captcha.urls'))
]
forms.py
class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=5)
captcha = CaptchaField(error_messages={"invalid":"please input correctly"})
register.html
<div class="tab-form">
<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
<input type='hidden' name='csrfmiddlewaretoken' value='gTZljXgnpvxn0fKZ1XkWrM1PrCGSjiCZ' />
<div class="form-group marb20 ">
<label>邮 箱</label>
<input type="text" id="id_email" name="email" value="None" placeholder="请输入您的邮箱地址" />
</div>
<div class="form-group marb8 ">
<label>密 码</label>
<input type="password" id="id_password" name="password" value="None" placeholder="请输入6-20位非中文字符密码" />
</div>
<div class="form-group marb8 captcha1 ">
<label>验 证 码</label>
{{ register_form.captcha }}
<img src="/captcha/image/2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011/" alt="captcha" class="captcha" /> <input id="id_captcha_0" name="captcha_0" type="hidden" value="2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011" /> <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" />
</div>
<div class="error btns" id="jsEmailTips"></div>
<div class="auto-box marb8">
</div>
<input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="注册并登录" />
<input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' />
{% csrf_token %}
</form>
</div>
request information
Request information
USER
AnonymousUser
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'9dQylxY3htVbBMNFunnYwgnarkfjSVioz5rhu0uADk0ShssTFGl9144OEwJoUlPX'
email
'1#1.com'
password
'123456'
captcha_0
'2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011'
captcha_1
''
FILES
No FILES data
no matter whether the verification code I input is wrong or right, the error is always The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
Django's view should return some response.
From doc:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.
So you need to add return statement to post() method, e.g. like this:
def post(self,request):
...
return render(request, 'register.html',{'register_form':register_form})