Django #login_required redirects to home page - django

I have an issue with the below code. When I login below and try to submit the create.html template it redirects me to Home page (via home function in views and record is not saved in database). When i remove #login_required and directly navigate to /products/create , the record is saved down in database. I am confused why this is happening. Any assistance will be appreciated
I removed (#login_required) and directly navigated to /products/create and it works perfectly. However whenever I login and then use /products/create the record is not saved in database
Create.html
{%extends 'base.html'%}
{%block content%}
{%if error%}
{{error}}
{%endif%}
<h2> Create </h2>
{% csrf_token %}
<form action="create" method="POST" enctype="multipart/form-data">
{% csrf_token %}
Title:
<br/>
<input type="text" name = "title"/>
<br/><br/>
Body:
<br/>
<input type="textbox" name = "body"/>
<br/><br/>
URL:
<br/>
<input type="text" name = "url"/>
<br/><br/>
<input type="submit" class = "btn btn-primary" value = "Add Product"/>
</form>
{%endblock%}
Main url.py
from django.contrib import admin
from django.urls import path,include
from products import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/',include('accounts.urls')),
path('products/',include('products.urls')),
path('',views.home,name='home'),]
Sub project url.py
from django.urls import path,include
from . import views
urlpatterns = [
path('create',views.create,name='create'),]
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import path
from .models import Product
from django.utils import timezone
def home(request):
return render(request, 'products/home.html')
#login_required
def create(request):
if request.method == 'POST':
if request.POST['title'] and request.POST['body'] and request.POST['url']:
product=Product()
product.title = request.POST['title']
product.body = request.POST['body']
product.url = request.POST['url']
product.pub_date = timezone.datetime.now()
product.save()
return render(request,'products/test.html',{'error':'all conditions checked'})
else:
return render(request,'products/test.html',{'error':'all conditions not checked'})
else:
return render(request, 'products/create.html',{'error':'post method not checked'})
For reference
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
votes_total = models.IntegerField(default=1)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
* Login function *
def login(request):
if request.method == 'POST':
user = auth.authenticate(username=request.POST['username'],password=request.POST['password'])
if user is not None:
auth.login(request,user)
return redirect('home')
else:
return render(request,'accounts/login.html',{'error':'incorrect username or password'})
else:
return render(request,'accounts/login.html')

Related

Django - UserEditView is missing a QuerySet?

trying to create an edit profile for users and i keep getting this error what should i add or change ? is my models right for UserEditView
this is my views.py (all of it edited)
maybe the vendor its not compatitable with User edit view
anything elses needs to be added or should i just change something
all imports are for vendor and UserEditView
from tkinter import Entry
from django.contrib.auth.models import User
from xml.dom.minidom import Entity
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserCreationForm , UserChangeForm
from django.utils.text import slugify
from django.shortcuts import render, redirect
from .models import Profile, Vendor
from products.models import Product
from .forms import ProductForm
# Create your views here.
def become_vendor(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
vendor = Vendor.objects.create(name=user.username, created_by=user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'vendor/become_vendor.html', {'form': form})
#login_required
def vendor_admin(request):
context = {
'user':request.user
}
vendor = request.user.vendor
products = vendor.products.all()
return render(request,'vendor/vendor_admin.html',{'vendor': vendor , 'products': products ,'context':context})
#login_required
def add_house(request):
if request.method == 'POST':
form = ProductForm (request.POST, request.FILES)
if form.is_valid():
product = form.save(commit=False)
product.vendor = request.user.vendor
product.slug = slugify(product.عنوان)
product.save()
return redirect('vendor_admin')
else:
form = ProductForm()
return render(request,'vendor/add_house.html',{'form': form})
class UserEditView(generic.UpdateView):
models = User
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
seccess_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
urls.py
from django.urls import path
from .import views
from .views import UserEditView
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpattern =[
path('signup/', views.become_vendor, name='become_vendor'),
path('profile/', views.vendor_admin, name='vendor_admin'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'),
path('edit_profile/', UserEditView.as_view(template_name='vendor/edit_profile.html'), name='edit_profile'),
]
edit_profile.html
(where the error pops up)
{% extends "base.html"%}
{% load static %}
{% block content %}
<title>title</title>
<div class="section pt-9 pb-9">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title">
<div class="wrap-title">
<h3 class="title">
<span class="first-word"></span>
</h3>
<br>
<form method="post" >
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button class='button'>Update</button>
</form>
</div>
<hr>
{% endblock content %}
I think that you didn't declare your model correctly:
class UserEditView(generic.UpdateView):
# models = UserChangeForm #That has no sense.
model = User #The name of your model (Probably the default one: User).
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
success_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
Other thing. You have declared your template name twice. According to your views.py you can delete the template_name on your urls.py:
path('edit_profile/', UserEditView.as_view(), name='edit_profile'),

Django: Including a form inside a listview

I am trying to insert a newsletter signup form into my base.html template which is a listview that displays upcoming events and featured shops and everytime I submit the form it returns a 'HTTP error 405'
Any help with this would be appreciated
Views.py
from django.shortcuts import render
from django.views.generic import ListView, TemplateView
from events.models import Event
from newsletter.forms import NewsletterSignUpForm
from shops.models import Shop
class HomeListView(ListView):
template_name = 'core/index.html'
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
context.update({
'events': Event.get_upcoming_events()[:1], # returns only the first event in the list
'shops': Shop.objects.all(),
})
context['newsletter_form'] = NewsletterSignUpForm()
return context
def get_queryset(self):
return None
forms.py
from django.forms import ModelForm
from .models import Newsletter
class NewsletterSignUpForm(ModelForm):
class Meta:
model = Newsletter
fields = ['email']
Models.py
from django.db import models
class Newsletter(models.Model):
email = models.EmailField(unique=True)
date_subscribed = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return f'{self.email}'
base.html
<form method="post">
{% csrf_token %}
{{ newsletter_form|crispy }}
<button class="btn btn-primary" type="submit">Sign Up!</button>
</form>
first add action url in form to handle post data
<form method="post" action="{% url 'submit_url' %}">
{% csrf_token %}
{{ newsletter_form|crispy }}
<button class="btn btn-primary" type="submit">Sign Up!</button>
</form>
urls.py
add url
path('your_url',views.formSubmit,name='submit_url')
views.py
def formSubmit(request):
if request.method == 'POST':
form = NewsletterSignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('your_list_view_url')
or you can use FormMixin along with classbased views
formmixin with classbased views

Django 1.10 Form Fields Using Foundation 6 Not Showing In Template

I am trying to build a simple landing page in Django that will allow users to sign up for an email newsletter. I am using this cookie cutter template - https://github.com/Parbhat/cookiecutter-django-foundation - because it integrates Foundation 6 from the jump.
The challenge is that the form fields are not showing in the template. Any help would be appreciated.
My models.py is:
class Subscribe(models.Model):
email = models.EmailField()
subscription_status = models.BooleanField(default=True)
create_date = models.DateTimeField(auto_now_add = True, auto_now = False)
update_date = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return self.email
My forms.py is:
from django import forms
from .models import Subscribe
class SubscribeForm(forms.ModelForm):
class Meta:
model = Subscribe
fields = ('email',)
My views.py is:
from django.shortcuts import render
from subscribers.forms import EmailForm, SubscribeForm
from .models import Subscribe
def home(request):
form = SubscribeForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
#we might need to do something here.
email = form.cleaned_data['email']
new_join_old, created = Subscribe.objects.get_or_create(email=email)
#new_join.save()
context = {"form": form}
template = "pages/home.html"
return render(request, template, context)
And my template is:
{% extends "base.html" %}
{% load foundation_formtags %}
{% block content %}
<section class="hero">
<!-- HERO SECTION -->
<div class="homebox">
<div class="wrap">
<p>Lorem Ipsum</p>
<form class="form" method="post" action=""> {% csrf_token %}
{{ form|as_foundation }}
<input type='submit' value='Subscribe' class='btn' />
</form>
</div>
</div>
</section>
My urls.py is:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
from subscribes.views import home
urlpatterns = [
url(r'^$', home, name='home'),
]
Thanks!

Error uploading file in django

I am trying to attach a file in django models, but when I hit submit button the selected file immediately disappears and the form submission fails . What is going wrong here?
forms.py
from django import forms
from .models import IssueNotice
class IssueNoticeForm(forms.ModelForm):
class Meta:
model = IssueNotice
fields = ('title', 'content','issuer','attachment',)
models.py
from django.db import models
from django.utils import timezone
from django import forms
class IssueNotice(models.Model):
title = models.CharField(max_length=300)
content = models.TextField()
attachment = models.FileField(upload_to='attachments')
issuer = models.CharField(max_length=100)
issuer_id = models.ForeignKey('auth.User')
issued_date = models.DateTimeField(default = timezone.now)
def publish(self):
self.issued_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from .models import IssueNotice
from .forms import IssueNoticeForm
def issue_notice(request):
if request.method == "POST":
form = IssueNoticeForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['attachment'])
notice = form.save(commit = False)
notice.issuer_id = request.user
notice.issued_date = timezone.now()
notice.save()
return redirect('home_page')
else:
form = IssueNoticeForm()
return render(request, 'webadmin/issue_notice.html',{'form':form})
issue_notice.html
{% extends 'webadmin/base.html' %}
{% block content %}
<div class="col-md-8">
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Issue</button>
</form>
{% endblock %}

HttpResponseRedirect doesn't work after new_join.save()

I tried to make simple request form. And I need to redirect user to "thank you" page after successful form sent. But after user hit "send" button - nothing happens. Just reload form page without form cleaning also.
Form is on "call" page, redirect needs "confirm" page...
So, task is: user fill the form on page "call" and after hitting "send" button, goes to "confirm" page.
My model:
# -*- coding: utf-8 -*-
from django.db import models
from django.forms import ModelForm
# Create your models here.
class Join(models.Model):
class Meta():
db_table = 'expert_request'
user_expert = models.CharField(max_length=100)
user_name = models.CharField(max_length=100)
user_cost = models.CharField(max_length=100)
user_email = models.EmailField()
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.user_email
my "forms.py":
from django import forms
from userform.models import Join
class JoinForm(forms.ModelForm):
class Meta:
model = Join
This is my "views.py":
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect, Http404
# Create your views here.
from userform.forms import JoinForm
from userform.models import Join
def userform(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
new_join.save()
HttpResponseRedirect('/confirm/')
context = {"form": form}
template = "userform.html"
return render(request, template, context)
def confirm(request):
return render(request, 'confirm.html')
This is my URL's:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^$', 'expert.views.index', name='index'),
url(r'^(\d+)/?$', 'expert.views.index'),
url(r'^call/$', 'userform.views.userform', name='call'),
url(r'^confirm/$', 'userform.views.confirm', name='confirm'),
)
My template "userform.html":
{% load staticfiles %}
<form style="position:relative" method="POST" action="">{% csrf_token %}
{{ form.user_expert }}
<p style="position:absolute; top:50px; left:20px; color:#FF0000;">{{ form.user_expert.errors.as_text }}</p>
{{ form.user_name }}
<p style="position:absolute; top:182px; left:20px; color:#FF0000;">{{ form.user_name.errors.as_text }}</p>
{{ form.user_cost }}
<p style="position:absolute; top:50px; left:380px; color:#FF0000;">{{ form.user_cost.errors.as_text }}</p>
{{ form.user_email }}
<p style="position:absolute; top:182px; left:380px; color:#FF0000;">{{ form.user_email.errors.as_text }}</p>
<button type="submit">Send</button>
<div class="clear"></div>
</form>
Maybe you forgot the return statement in userform view function? Fix its beginning like this:
def userform(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
new_join.save()
return HttpResponseRedirect('/confirm/')