Django link two apps - django

im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app).
this is the error i get:
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
urls.py
...
from quickblog import views as core_views
from accounts import views as views_accounts
...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),
views.py (accounts app):
from django.shortcuts import render, redirect
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('accounts:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'reg_form.html', args)
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('accounts:view_profile'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'change_password.html', args)
This is my first django app, is there maybe anything i need to know about linking two apps within one project?
thanks

Related

Can we use instance in the form?

hello guys i am working on form i didint find how to get instance in the form. This is not a model form
def form(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
else:
form = Form()
return render(request, 'app/form.html', {'form': form})
You should have a form class something like below:
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Now To handle the form we need to instantiate it in the view for the URL where we want it to be published:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# process the data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Refer the Django documentation for more details.
https://docs.djangoproject.com/en/3.0/topics/forms/

save() got an unexpected keyword argument 'force_insert'

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created. Log In to continue.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
This is the code when I run it I get an error. But that error shouldn't be there since I am not overriding the the save() method. please help.
try to get each form input one by one and then save the form. for example:
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = YourModelName()
data.input1 = form.cleaned_data['input1']
data.input2 = form.cleaned_data['input2']
# ...
form.save()
messages.success(request, 'Your account created. You can now Login.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
I have a feeling that you are doing Corey Schafer's Django tutorial. If so, other users have had the same problem, which is discussed here:
Django - TypeError - save() got an unexpected keyword argument 'force_insert'
The issue lies in overriding the save method in your Profile model

Login using Class based view didn't work as expected while trying to login a user using email

my views.py:
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.shortcuts import render
from django.views.generic import View
from .forms import LoginForm, RegistrationForm
class Login(View):
form_class = LoginForm
initial = {'key': 'value'}
template_name = 'web/login.html'
def get(self, request):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request):
if request.method == 'POST':
form = self.form_class(initial=self.initial)
if form.is_valid():
email=form.cleaned_data['email']
password=form.cleaned_data['password']
auser = User.objects.get(email=email)
username = auser.username
buser = authenticate(username, password)
if buser:
if buser.is_active:
login(request, buser)
return HttpResponse('Good to Go...')
else:
return HttpResponse('your account is disabled...')
else:
print "Invalid login details: {0}, {1}".format(email, password)
HttpResponse('invalid login details...')
else:
return HttpResponse('Form is not valid!')
else:
form = self.form_class()
Here above I'm trying to login a user using email as unique field in class based views. But It raises 'Form is not valid!' as I specified in my views. I don't know what's going wrong with it exactly. Please Help me how to fix it?
Thanks in Advance
You need to change the post method of this class:
def post(self, request):
if request.method == 'POST':
form = self.form_class(data=self.request.POST)
if form.is_valid():
.....

Django Error:: global name 'HttpRequestRedirect' is not defined

I am getting this error, I tried working on it a lot but cannot understand whats wrong.
I am basically trying to make a signup registration that has a couple of forms to be filled
Request Method: GET
Request URL: http://127.0.0.1:8000/gi/
Django Version: 1.5.1
Exception Type: NameError
Exception Value:
global name 'HttpRequestRedirect' is not defined
Exception Location: /home/xx/Desktop/GoAmma/vendorAmmma/vreg/views.py in GIRegistration, line 42
Python Executable: /home/xx/Desktop/forfte/bin/python
Python Version: 2.7.3
The view is as shown below:
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm, LoginForm
from vreg.models import Vendor
from django.contrib.auth import authenticate, login, logout
def VendorRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= RegistrationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['emailadd'], password= form.cleaned_data['password'])
user.save()
vreg=Vendor(user=user)
vreg.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= RegistrationForm()
context={'form':form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
vreg= request.user.get_profile
context={'vreg':vreg}
return render_to_response('profile.html',context,context_instance=RequestContext(request))
#login_required
def GIRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= GIForm(request.POST)
if form.is_valid():
contact = form.save()
contact.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('generalinfo.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= GIForm()
context={'form':form}
return render_to_response('generalinfo.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method=='POST':
form=LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
vreg= authenticate(username=username,password=password)
if vreg is not None:
login(request,vreg)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
'''user not submitting form show the login form'''
form= LoginForm()
context={'form': form}
return render_to_response('login.html',context,context_instance= RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
Its HttpResponseRedirect not HttpRequestRedirect.
Change this return HttpRequestRedirect('/profile/') to return HttpResponseRedirect('/profile/')
P.S. Never use hardcoded urls in your code, use Reverse Resolution of URLs

DRYing out my Django view: Please help me!

I hope this is a good first question. I've been trying to DRY out my Django code, but unfortunately I keep getting hit with several errors! (Forgive me if I don't post the code with problems - I'll just post the code that works) I've tried using #decorators, and also putting a view within a view. Please help me!
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from blog.models import Post, User, Blog, Comment
from blog.forms import CommentForm, PostForm, BlogForm
from django.core.urlresolvers import reverse
import datetime
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django import forms
def limiter(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
def postindex(request):
posts = get_list_or_404(Post.objects.all())
return render_to_response('index.html', {'posts':posts})
def onepost(request, postid):
post = get_object_or_404(Post, pk=postid)
if request.method == 'POST':
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
form = CommentForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
c = Comment(owner=request.user,
post=Post.objects.get(pk=postid),
time=datetime.datetime.now(),
text=cd['text'])
c.save()
return HttpResponseRedirect(reverse('blog.views.onepost',
args=[postid]))
else:
form = CommentForm()
return render_to_response('single.html',
{'post':post,'comments':post.comment_set.all(),
'form':form},
context_instance=RequestContext(request))
def userlist(request):
users = get_list_or_404(User.objects.all())
return render_to_response('userlist.html', {'users':users})
def bloglist(request, userid):
blogs = get_list_or_404(Blog.objects.filter(owner__pk=userid))
return render_to_response('bloglist.html', {'blogs':blogs})
def postlist(request, blogid):
posts = get_list_or_404(Post.objects.filter(blog__pk=blogid))
return render_to_response('postlist.html', {'posts':posts})
def landing(request):
return render_to_response('landing.html', {})
def dash(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
user = request.user
blogs = Blog.objects.filter(owner=request.user)
comments = Comment.objects.filter(owner=request.user)
posts = Post.objects.filter(blog__owner=request.user)
return render_to_response('dash.html',
{'user':user, 'blogs':blogs, 'comments':comments, 'posts':posts})
def newpost(request, blogid):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
blog = Blog.objects.get(pk=blogid)
if not request.user == blog.owner:
return HttpResponseRedirect(reverse('blog.views.dash'))
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
p = Post(title=cd['title'],
blog=Blog.objects.get(pk=blogid),
date=datetime.datetime.now(),
content=cd['content'])
p.save()
return HttpResponseRedirect(reverse('blog.views.postlist',
args=[blogid]))
else:
form = PostForm()
return render_to_response('chngpost.html',
{'blog':blog,
'form':form},
context_instance=RequestContext(request))
def editpost(request, postid):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
post = Post.objects.get(pk=postid)
if not request.user == post.blog.owner:
return HttpResponseRedirect(reverse('blog.views.dash'))
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post.title=cd['title']
post.content=cd['content']
post.save()
return HttpResponseRedirect(reverse('blog.views.onepost',
args=[postid]))
else:
form = PostForm(initial={'title':post.title,'content':post.content})
return render_to_response('chngpost.html',
{'post':post,
'form':form},
context_instance=RequestContext(request))
def delpost(request, postid):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
post = Post.objects.get(pk=postid)
if not request.user == post.blog.owner:
return HttpResponseRedirect(reverse('blog.views.dash'))
if request.method == 'POST':
post.delete()
return HttpResponseRedirect(reverse('blog.views.dash'))
return render_to_response('delpost.html',
{'post':post},
context_instance=RequestContext(request))
def newblog(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
if request.method == 'POST':
form = BlogForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
b = Blog(title=cd['title'],
owner=request.user)
b.save()
return HttpResponseRedirect(reverse('blog.views.bloglist',
args=[request.user.pk]))
else:
form = BlogForm()
return render_to_response('chngpost.html',
{'form':form},
context_instance=RequestContext(request))
def delcomment(request, commentid):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
comment = Comment.objects.get(pk=commentid)
if not (request.user == comment.post.blog.owner) | (request.user == comment.owner):
return HttpResponseRedirect(reverse('blog.views.dash'))
if request.method == 'POST':
comment.delete()
return HttpResponseRedirect(reverse('blog.views.dash'))
return render_to_response('delpost.html',
{},
context_instance=RequestContext(request))
(Hope that's formatted properly) The code I'd like to factor out especially is
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts.views.login_view'))
But of course any more suggestions would be appreciated! Thank you so much!
`
Use login_required decorator (docs)
Use modelforms for editing/creating models. (docs)
If you need to just pass something to template, use direct_to_template generic view (docs)
You can use #login_required decorator for that. You can find out more at Django documentation: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required.
Please describe any problems that you are experiencing.