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.
Related
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
I'm trying to implement class Based views with permissions and they do not seem to connect, although I believe I strictly followed Django User's guide.
First: set up of a Custom User model, based on Proxies, in accounts.models
class CustomUser(AbstractUser):
some_fields...
Then, I created a Manager:
class EmployeeManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(status_type=CustomUser.StatusType.EMPLOYEE)
Followed by the type of profile:
class Employee(CustomUser):
objects = EmployeeManager()
class Meta:
proxy = True
permissions = [("communities.view_region", "Can view region")]
Where I set a permission, make the migrations and migrate.
After, I create the view:
import communities.models as comms
class RegionsListView(ListView):
model = comms.Region
Then, configuration of the url and its view:
rom django.urls import path, include
import communities.views as views
from django.contrib.auth.decorators import permission_required
app_name = 'communities'
urlpatterns = [
path("regions/list/", permission_required("communities.view_region")(views.RegionsListView.as_view()))
Then I log in as an employee and I get an error 403 when calling this url.
What did I miss ?
Remarks:
using permission_required = 'communities.view_region' in the view.py file produces the same result.
when logging as a superuser, I get of course the right page.
In order to implement the permissions, it had to be done programmatically, while creating a new user.
In the workflow,
the new User gets an activation e-mail with a unique link,
the click gives him access to the website and he is required to immediately change his password,
the validation implements the permission (in this case, a Group)
Here is the code.
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import redirect, render
from django.contrib.auth.models import Group
#login_required
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
user = form.save()
# Attributes to a user a group depending on his status.
user.groups.add(Group.objects.get(name=user.status_type))
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your PWD has been changed')
return redirect('change_password')
else:
messages.error(request, 'Please Correct the Error')
else:
form = PasswordChangeForm(request.user)
return render(request, 'accounts/change_password.html', {'form': form})
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
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))
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})