Using 'is_authenticated' with Django 1.5 Custom User Models - python

I have made a custom user model for a project I am doing, and I am trying to use is_authenticated to allow people to access their profile and change it. However, it says there is no WSGI object. I have no idea why this could be and I would like some help!
from django.shortcuts import render
from django.contrib.auth import get_user_model
from userstest.models import CustomUser
from userstest.admin import CustomUserCreationForm, CustomUserChangeForm
u = get_user_model()
def index(request):
form = CustomUserCreationForm()
if request.u.is_authenticated():
a = request.u
form2 = CustomUserChangeForm(instance=a)
return render(request, "index.html", {'form2': form2})

As the error states, there is no "u" attribute on the request object. Simply change request.u to request.user.
def index(request):
form = CustomUserCreationForm()
if request.user.is_authenticated():
form2 = CustomUserChangeForm(instance=request.user)
return render(request, "index.html", {'form2': form2})

Related

"redirect" function of django is not working and after submitting the form, user remains on same page

In the function "createProject" of views.py, I want that after submitting the form user should redirect to the "projects" page.
But I don't know what is my mistake here. After submitting the form it does not redirect the user to "projects" page but remains on the same page.
"views.py" file:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import ProjectForm
from .models import Project
def projects(request):
projects = Project.objects.all()
context = {'projects':projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
return render(request, 'projects/single-project.html')
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
redirect('projects')
context = {'form':form}
return render(request, 'projects/project_form.html', context)
Here is "urls.py" file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.projects, name = 'projects'),
path('project/<str:pk>/', views.project, name = 'project'),
path('create-project/', views.createProject, name = 'create-project'),
]
Here is "project-form.html" [I am using Django "ModelForm"]:
from django.db.models.base import Model
from django.forms import ModelForm
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'description', 'demo_link', 'source_link', 'tags']
Can anyone help me in finding the mistake here ?
Why after submitting the form, it is not redirecting it to the "projects" page and remain on same page?
This issue is because the redirect response was never returned, so:
if form.is_valid():
form.save()
return redirect('projects')
# ^^^ Add this

Python crash course 19-5 object has no attribute 'owner'

learning python through the python crash course book. Having this issue where somehow it says that there is no attribute 'owner' for each blogpost when there seems to be one? Would appreciate any guidance, cheers all!
Added to the very bottom of settings.py
#MY SETTINGS
LOGIN_URL = 'users:login'
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length=50)
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
This is the code when i run django shell to see the owner associated with each blogpost
from blogs.models import BlogPost
for a in BlogPost.objects.all():
print(a, a.owner)
My first post! aaaaaa ll_admin
Second blog post ll_admin
No season 2 in product ll_admin
ll_admin
is this the tutle ll_admin
ssd ll_admin
ssaaa ll_admin
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import BlogPost
from .forms import BlogPostForm
# Create your views here.
def index(request):
"""The home page for blogs"""
return render(request, 'blogs/index.html')
#login_required
def posts(request):
"""Show all blogposts"""
posts = BlogPost.objects.filter(owner=request.owner).order_by('date_added')
context = {'posts': posts}
return render(request, 'blogs/posts.html', context)
#login_required
def new_post(request):
"""Add a new blogpost"""
if request.method != 'POST':
#No data submitted; create a blank form.
form = BlogPostForm()
else:
#POST data submitted, process data
form = BlogPostForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:posts')
#Display a blank or invalid form
context = {'form': form}
return render(request, 'blogs/new_post.html', context)
#login_required
def edit_post(request, post_id):
"""Edit existing post"""
post = BlogPost.objects.get(id=post_id)
if request.method != "POST":
#Initial request, pre-fill form with the current post
form = BlogPostForm(instance=post)
else:
#Post data submitted, process data
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:posts')
#return redirect('blogs:posts', post_id=post.id)
context = {'post':post, 'form':form}
return render(request, 'blogs/edit_post.html', context)
This is all that I have edited to add in the login functions, cant seem to spot the error. Thank you for helping!
In your posts view:
#login_required
def posts(request):
"""Show all blogposts"""
posts = BlogPost.objects.filter(owner=request.owner).order_by('date_added') # here
context = {'posts': posts}
return render(request, 'blogs/posts.html', context)
The request object is storing 2 values:
The instance of the currently logged in user under the name user (changes to AnonymousUserObject instance when logged out)
auth depending on the type of authentication used
You are calling request.owner and obviously getting an error because a request object has no owner attribute, change the marked line line this:
posts = BlogPost.objects.filter(owner=request.user).order_by('date_added')
And it should work.

get_object_or_404 is undefined

I'm trying to update my Profile model with some data that I get from a form, but I get this error
name 'get_object_or_404' is not defined
Here's my code for the view (It's pretty basic at this point)
from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.models import User
from users import models
from users.models import Profile
from .forms import WeightForm
# Create your views here.
def home(request):
profile = get_object_or_404(pk=id)
form = WeightForm(request.POST, instance=profile)
if form.is_valid():
form.save
return render(request, 'Landing/index.html',{'form':form})
You need to import it. Furthermore in a get_object_or_404(…) [Django-doc], you first specify a model class or a queryset, so in this case get_object_or_404(Profile, …):
from django.shortcuts import get_object_or_404
def home(request):
profile = get_object_or_404(Profile, pk=id)
form = WeightForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return render(request, 'Landing/index.html',{'form':form})
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Using an extended usermodel, how can I create two model instances with two modelforms in the same view?

First off, I want to say that I am new to django though I understand most of it, forms have always been confusing to me.
I have two models in which I need to create an instance from, the standard built in User model and my own UserProfile model.
The problem I am facing is that really do not know how to display two forms (one for each model) in the template and on save() then tell django that the newly created UserProfile instance's User = model.ForeignKey belongs to the also newly created User.
My forms.py is fairly simple:
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from .models import UserProfile
class UserForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ('display_name', 'avatar', 'birthday', 'usertype', 'daw', 'usergenre')
In my views.py I've tried doing this:
from .forms import UserForm
from .forms import UserProfileForm
# Create your views here.
def RegisterView(request):
if request.method == 'POST':
form = UserForm(request.POST)
form2 = UserProfileForm(request.POST)
if form.is_valid():
if form2.is_valid():
return HttpResponseRedirect('/login/')
return render(request, 'register.html', {'form': form, 'form2': form})
But when I try to access /register I get this error:
http://dpaste.com/19NH2A6
You should use save() method.
Next time you have a problem, check the official Django documentation.
ModelForms - save() method
from .forms import UserForm
from .forms import UserProfileForm
from django.http import HttpResponseRedirect
def RegisterView(request):
if request.method == 'POST':
form = UserForm(request.POST, prefix='uf')
form2 = UserProfileForm(request.POST, prefix='upf')
if form.is_valid():
if form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect('/login/')
elif request.method == 'GET':
form = UserForm(prefix='uf')
form2 = UserProfileForm(prefix='upf')
return render(request, 'register.html', {'form': form, 'form2': form2})
When you hit /register page from browser, your view gets GET request, you have created form only for POST request
from .forms import UserForm
from .forms import UserProfileForm
# Create your views here.
def RegisterView(request):
if request.method == 'POST':
form = UserForm(request.POST, prefix='uf')
form2 = UserProfileForm(request.POST, prefix='upf')
if form.is_valid():
if form2.is_valid():
return HttpResponseRedirect('/login/')
elif request.method == 'GET':
form = UserForm(prefix='uf')
form2 = UserProfileForm(prefix='upf')
return render(request, 'register.html', {'form': form, 'form2': form2})
You should read the traceback yourself so that you can find the error easily.
It says;
Exception Type: NameError at /register/
Exception Value: name 'HttpResponseRedirect' is not defined
You've used HttpResponseRedirect but you didn't import it, therefore it is not defined.
Add this to top of your code.
from django.http import HttpResponseRedirect

What is the appropriate way to set up a form and view in Django to accommodate both creating and updating a model

I am working with sensitive code and I am not able to share specifics based on rules at my job. However, I have a pretty specific issue that should be easy to help with without code. I am new to Django and I am using legacy code. My issue is that I need to build a form that will update an instance of the model if it already exists and if it does not exist, then the form will create and save a new instance of the model. Any suggestions or examples of what it might look like?
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
The only difference would be to pass the form an instance argument for existing objects.
myapp/models.py
from django.db import models
class Article(models.Model):
# Define fields here
myapp/forms.py
from django.forms import ModelForm
from myapp.models import Article
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
myapp/views.py
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from myapp.models import Article
from myapp.forms improt ArticleForm
def create_entry(request):
if 'POST' == request.method:
form = ArticleForm(data=request.POST, files=request.FILES)
if form.is_valid():
obj = form.save()
return redirect('your-view')
else:
form = ArticleForm()
context = {'form': form}
render_to_response('myapp/create_entry.html', context, context_instance=RequestContext(request))
def edit_entry(request, article_id):
article = get_object_or_404(Article, pk=article_id)
if 'POST' == request.method:
form = ArticleForm(data=request.POST, files=request.FILES, instance=article)
if form.is_valid():
obj = form.save()
return redirect('your-view')
else:
form = ArticleForm(instance=article)
context = {'form': form}
render_to_response('myapp/edit_entry.html', context, context_instance=RequestContext(request))

Categories