please help fix the error
I added to the site and access authorization system to the user profile . Each user has the ability to change the login. for this he must in the following form to enter login and click submit:
from django import forms
from userprofile.models import UserProfile
from django.contrib.auth.models import User
from django.conf import settings
import os
class UserProfileForm (forms.ModelForm):
class Meta:
model = UserProfile
fields = ('family', 'name', 'nation', 'status', 'login', 'nation_show')
def clean_family (self):
family = self.cleaned_data ['family']
letters_quantity = len (family)
if letters_quantity < 4 :
raise forms.ValidationError (" little beech in the name! " )
return family
def clean_login (self):
login = self.cleaned_data ['login']. strip ()
if login! ='':
login_form_db = User.objects.filter (username = 'qwe')
if login_form_db:
login_form_db = login_form_db.username
if login == login_form_db:
raise forms.ValidationError (" this username is busy " )
else:
User.username = login
User.save (self)
return login
but in the end I get the following message error :
AttributeError at / userprofile /
'QuerySet' object has no attribute 'username'
Request Method: POST
Request URL: http://127.0.0.1:8000/userprofile/
Django Version: 1.6.2
Exception Type: AttributeError
Exception Value:
'QuerySet' object has no attribute 'username'
Exception Location: c: \ Python33 \ django_projects \ mutants \ userprofile \ forms.py in clean_login, line 26
filter() returns a queryset. Since you need to get the User object by username, use get() instead:
login_form_db = User.objects.get(username='qwe')
Related
I checked the other posts on here that have the attribute error that I have, but they seem to be for different reasons. I am currently requesting the information from a form for users to update a project page. Then, if the form is valid, I am saving the form, saving the project, then trying to return redirect to the project page; however, when I click the button, the computer renders the error page. I will attach my forms.py, views.py, models.py, and urls.py:
Views.py for the update section:
#wraps(function)
def wrap(request, *args, **kwargs):
user = request.user
name = kwargs.get('name')
if uProjects.objects.filter(project=Project.objects.get(name=name), user=user, ifAdmin=True).exists():
return function(request, *args, **kwargs)
else:
return HttpResponseRedirect('/')
return wrap
#admin_check
def update(request, name):
project = Project.objects.get(name = name)
if request.method == "POST":
pr_form = ProjectUpdateForm(request.POST,
request.FILES,
instance=project)
#if is_admin in Member == True: #need to authenticate user, access user permissions, if user has permission:
if pr_form.is_valid():
pr_form.save()
messages.success(request, f'This project has been updated.')
request.project.save()
return redirect('project')
else:
pr_form = ProjectUpdateForm(instance=project)
context = {
'pr_form': pr_form
}
return render(request, 'projects/updateproject.html', context)
forms.py for ProjectUpdateForm:
class ProjectUpdateForm(forms.ModelForm):
class Meta:
model = Project
fields=['name', 'department', 'department','bPic', 'logo',
'department', 'purpose', 'projectTag', 'lookingFor', 'recruiting']
urls.py
from projects import views as p
path('project/<str:name>/', p.project, name='project'),
path('editproject/<str:name>/', p.update, name="editproject"),
Thanks, please let me know what I can do.
Your error is in line request.project.save(), request doesn't have project attribute.
And actually you don't need to call save() method for project.
Because ProjectUpdateForm is the ModelForm and ModelForm.save() (Django docs) method will create a new instance of the specified model or update assigned instance.
#admin_check
def update(request, name):
project = Project.objects.get(name = name)
if request.method == "POST":
pr_form = ProjectUpdateForm(request.POST,
request.FILES,
instance=project)
#if is_admin in Member == True: #need to authenticate user, access user permissions, if user has permission:
if pr_form.is_valid():
# save() returns an instance object, you can use it to manipulate your object.
instance = pr_form.save()
messages.success(request, f'This project has been updated.')
# YOUR ERROR IS ⬇️ HERE request doesn't have project attribute
# request.project.save()
# redirect with arguments
return redirect('project', name=instance.name)
...
Also your redirect must contain argument name, because your project url required name attribute:
redirect('project', name=instance.name)
I'm trying to store the first name and last name of a user in my datatbase upon hitting the submit button so that next time when I manually check in Terminal what's inside my database, I can see exactly what the user inputted.
This is the error I'm getting:
I'm assuming the error is coming from my views.py file:
from django.http import HttpResponse
from .models import Person
from django.shortcuts import render
def index(request):
if request.method == 'POST':
first_name = request.POST.get('firstName')
last_name = request.POST.get('lastName')
if first_name and last_name:
user = Person.objects.create(firstName=first_name, lastName=last_name)
user.save()
return render('request', 'music/index.html')
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
The code is passing 'request' (string literal) to django.shortcuts.render which expected Request object as the first parameter.
Pass the request parameter of the view function:
return render('request', 'music/index.html')
should be:
return render(request, 'music/index.html')
I'm testing a django app from this tutorial: http://tutorial.djangogirls.org/en/django_admin/README.html
I've created a test:
from django.test import TestCase
from django.utils import timezone
from .models import Post
from django.contrib.auth.models import User
# Create your tests here.
class PostTest(TestCase):
def test_create_post(self):
# Create the post
post = Post()
# Set the attributes
post.author = User
post.title = 'My first post'
post.text = 'This is my first blog post'
post.published_date = timezone.now()
post.created_date = timezone.now()
# Save it
post.save()
# Check we can find it
all_posts = Post.objects.all()
self.assertEquals(len(all_posts), 1)
only_post = all_posts[0]
self.assertEquals(only_post, post)
# Check attributes
self.assertEquals(only_post.author, User)
self.assertEquals(only_post.title, 'My first post')
self.assertEquals(only_post.text, 'This is my first blog post')
self.assertEquals(only_post.published_date.day, post.published_date.day)
self.assertEquals(only_post.published_date.month, post.published_date.month)
self.assertEquals(only_post.published_date.year, post.published_date.year)
self.assertEquals(only_post.published_date.hour, post.published_date.hour)
self.assertEquals(only_post.published_date.minute, post.published_date.minute)
self.assertEquals(only_post.published_date.second, post.published_date.second)
self.assertEquals(only_post.created_date.day, post.created_date.day)
self.assertEquals(only_post.created_date.month, post.created_date.month)
self.assertEquals(only_post.created_date.year, post.created_date.year)
self.assertEquals(only_post.created_date.hour, post.created_date.hour)
self.assertEquals(only_post.created_date.minute, post.created_date.minute)
self.assertEquals(only_post.created_date.second, post.created_date.second)
When I run python manage.py test I get this error:
Creating test database for alias 'default'...
ERROR: test_create_post (blog.tests.PostTest)
Traceback (most recent call last):
File "C:\Users\shenk\Documents\Programming\django_projects\djangogirls\blog\tests.py" , line 13, in test_create_post
post.author = User
File "c:\Users\shenk\Documents\Programming\django_projects\djangogirls\myvenv\lib\site-packages\django\db\models\fields\related.py", line 627, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>": "Post.author" must be a "User" instance.
----------------------------------------------------------------------
Ran 1 test in 0.001s
How can I create an object of User instance to test the Post? In my model it's defined as author = models.ForeignKey('auth.User')
This line looks bogus:
# Set the attributes
post.author = User
post.author is expecting for you to assign an instance of the User class to it, not the User class itself. Try something like:
u = User(...)
u.save()
post.author = u
I have an app called profiles which just leverages the django-registration-redux module. I am trying to create a form that allows the user to edit it, with the information they already have in it, but it isn't showing up. I can get it to show up without the information, but not the profile information that already exists.
urls.py
from django.conf.urls import url
from profiles import views
urlpatterns = [
url(r'^(?P<username>[-\w]+)/$', views.single, name='profile_single'),
url(r'^(?P<username>[-\w]+)/edit/$', views.edit, name="profile_edit"),
]
views.py
def edit(request, username):
instance = Profile.objects.get(user=username)
# It would be good to have an in depth understanding of what the actual request module does
if request.user == instance.user:
form = ProductForm(request.POST or None, instance = instance)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.slug = slugify(form.cleaned_data['title'])
profile.save()
return HttpResponseRedirect('/user/%s'%(user.username))
return render_to_response("profiles/edit.html", locals(), context_instance=RequestContext(request))
The error that I am recieving is:
Exception Value: invalid literal for int() with base 10: 'admin'
You need to check username field of User model.
To do that, replace the following line:
instance = Profile.objects.get(user=username)
with:
instance = Profile.objects.get(user__username=username)
So I'm still a newbie in Django and I would like to have your advices regarding this point :
I have a User system in my application which extend from userena:
class FindUrGeekUserProfile(UserenaBaseProfile):
user = models.OneToOneField( User, unique = True, verbose_name ='userData', related_name='myProfile',db_index = True)
type = models.CharField(max_length = 2, choices = USER_TYPE, blank = True, null = True, db_index = True)
def __unicode__(self):
return 'Name: ' + self.user.username + ' Type: ' + self.type
When a User registers in my website he completes login, password and email fields.
The first time a user will connect though my website, he will see a page asking him what's his usertype : Type1 or Type2...
I want to verify in each login_registered view that the user has defined his type. Until now, i created a function I use in every registered view:
def checkUserType(user):
if(user.type != None)
return True
else:
retur False
#login_registered
def myView(request):
if (checkUserType(request.user)):
Continue....
else:
return redirect('setUserType') # Page where the user will set his type
Is there a better way to that in Django? Using some built in function ?
Thanky ou for your help
There's at least a better way:
#login_registered
def myView(request):
if not checkUserType(request.user):
return redirect('setUserType') # Page where the user will set his type
# user has the type, continue
Also, you could write a custom middleware, and do the check/redirect in process_request(). It could look like:
from django import http
from django.core.urlresolvers import reverse
class SetUserTypeMiddleware(object):
urls = ['/some/path/that/requires/user/type/',]
def process_request(self, request):
if not request.user.is_authenticated():
return
for url in urls: # customize url matching to your taste
if url in request.path_info:
return http.HttpResponseRedirect(reverse('setUserType'))
Middleware is a cool feature, it's simple and powerful. Just don't forget to register them in settings.MIDDLEWARE_CLASSES.