I am making a web app with Django 1.7,python 2, but I am stuck in a part where I need that anonymous users can see the profiles of registered users (The URL is like this: "www.website.com/username) but I keep getting this error:
"invalid literal for int() with base 10:'andyjrr'"
where "andyjrr' is an username I pass it via URL.
This is my views.py:
def profiles(request, username):
context = RequestContext(request)
person = UserProfile.objects.get(user=username)
return render_to_response('detail.html',{'person':person},context)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,null=True,blank=True)
first_name = models.CharField(max_length=20,blank=True)
last_name = models.CharField(max_length=20,blank=True)
about_me = models.TextField(max_length=100,default='',blank=True)
experience = models.TextField(max_length=250,default='',blank=True)
offers = models.TextField(max_length=110,default='',blank=True)
TRACEBACK:
/home/andyjrr/Documents/jobby/users/views.py in profiles
person = UserProfile.objects.get(user=username)
I'm going to guess that the user field in the UserProfile model is a ForeignKey/OneToOne to auth.User.
If it is, then you'll need to modify your filter to join on the actually username of the auth.User model.
person = UserProfile.objects.get(user__username=username)
Related
I'm trying to retrieve the details of a user using the username test from an extended User model in Django. But I am unable to do it. It's giving me the error:
ValueError at / invalid literal for int() with base 10: 'test'
Following is my code:
models.py
class DocchainUser(models.Model):
docchainuser_name = models.OneToOneField(User, on_delete = models.CASCADE, default='x')
address = models.CharField(max_length=64,unique=True)
def __str__(self):
return self.address
views.py
def my_users(request):
if request.method == 'POST':
username = request.POST.get('username')
user = authenticate(username=username)
if user:
if user.is_authenticated:
signBool = signatureAuth(username)
if signBool == 'AUTHENTICATED':
login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0])
return HttpResponseRedirect('/dashboard')
....
And the signatureAuth() now:
def signatureAuth(username):
userModel = DocchainUser.objects.filter(docchainuser_name=username)
address = userModel.address
print(address)
...
I'm retrieving the user details using username: test in signatureAuth() method. test is already present in my User as well as DocchainUser model.
You don't have an extended user model, you have a separate model with a one-to-one relation to User. So in order to query that model by username, you need to follow the relationship.
userModel = DocchainUser.objects.filter(docchainuser_name__username=username)
Note, one of the reasons you struggled here is that your OneToOneField is probably misnamed; the relationship is with the entire model, not the username; you should call it just docchainuser.
(Also note, your if user.is_authenticated is pointless; that just checks that the user is an instance of User rather than AnonymousUser, which you know it is because you just explicitly retrieved it from the User model.)
so I have an eCommerce customer-facing app with a Django Admin interface. I want employees who will be using the admin to be able to create users. The problem is the custom regex validation I built in applies to the customer-facing side only, and when an employee wants to create a new user using the admin, my use of Django Validators throws an error when attempting to create the user.
I was wondering if (1) there was a way to reuse my UserManager class (inherited from models.Manager) which handles the customer-side validation, with Django admin also. If not, then (2) if I was to rely on Django Validators how could I clean up the code as to not throw errors like:
TypeError: "object of type 'int' has no len()
I've done a little homework trying to figure this out and found this thread: TypeError: object of type 'int' has no len() error assistance needed
This basically explains the error being thrown for this example is because it's trying to call len() on an int instead of a list. What I don't get is why don't I get this same error on the customer-facing side when a user signs himself up?
At any rate, I can't figure out how to implement the solution given how I set up my UserManager. I'm not using Django Forms and have tried fooling around with some of the clean methods, but am also trying not to repeat myself by reusing the validation I already wrote in the UserManager.
Here is my code, thanks for any help!
models.py
class UserManager(models.Manager):
def validation(self, postData, error_validation):
errors = {}
if error_validation == 'register':
if not NAME_REGEX.match(postData['first_name']):
errors['first_name'] = "First name can only contain letters."
if not NAME_REGEX.match(postData['last_name']):
errors['last_name'] = "Last name can only contain letters."
elif User.objects.filter(email=postData['email']):
errors['email'] = "Email already being used."
elif len(postData['password']) < 8:
errors['password'] = "Password must contain 8 or more characters."
elif not postData['password'] == postData['confirm_password']:
errors['password'] = "Both passwords must match!"
if error_validation == 'login':
user = User.objects.filter(email=postData['email'])
if not user or not bcrypt.checkpw(postData['password'].encode(), user[0].password.encode()):
errors['user_login'] = "Invalid credentials."
return errors
class User(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
dob = models.DateField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=35)
state = models.CharField(max_length=2)
zipcode = models.IntegerField(validators=[MinLengthValidator(5), MaxLengthValidator(10)])
phone = models.IntegerField(validators=[MinLengthValidator(10), MaxLengthValidator(10)])
email = models.CharField(max_length=65)
password = models.CharField(max_length=255)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
objects = UserManager()
def __str__(self):
return self.email
You are using MinLengthValidator and MaxLengthValidator on the IntegerFields, which will try to apply len() function on the integers. That's why you got this kind of error. You can change your zipcode and phone attributes to CharField, or just remove the validators.
One thing to note is that CharField doesn't have a min_length attribute.
So just as an ill-advised alternative, instead of using Min/MaxLengthValidator, you can use Min/MaxValueValidator Min/MaxValueValidator. What's cool is you can subclass the validators to handle custom error messaging:
models.py
from django.core.validators import MinValueValidator, MaxValueValidator
class ZipcodeMaxValueValidator(MaxValueValidator):
message = ("AWWW YEA ERROR!!")
class User(models.Model):
zipcode = models.IntegerField(validators=[MinValueValidator(99999), ZipcodeMaxValueValidator(99999)]
I am new to Django, Please forgive any silly mistakes in code or logic,
Intro: I am trying to create a user follower model in Django. Where users can follow and unfollow other users on the sites
Error: I have made the models for my follow/unfollow I have also made the views I am getting this error
AttributeError at /accounts/admin/follow/
Cannot use add() on a ManyToManyField which specifies an intermediary model. Use accounts.Contact's Manager instead.
The obj.followers.add(user) is highlighted in the traceback as the origin of the error
Below are my models.py
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse('accounts:profile', kwargs={'username': self.user.username})
class Contact(models.Model):
user_from = models.ForeignKey(User, related_name='suppporter')
user_to = models.ForeignKey(User, related_name='leader')
def __str__(self):
return '{} follows {}'.format(self.user_from, self.user_to)
User.add_to_class('following',
models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False))
I think the models.py may be good. The fault I believe is in my views.
Below is my view.py
class FollowToggle(LoginRequiredMixin, RedirectView):
def get_redirect_url(self, *args, **kwargs):
username = self.kwargs.get('username')
print(username + " This is the user who will be followed") # This prints correct
profile = get_object_or_404(Profile, user__username=username)
print(profile) # This prints correct
obj = get_object_or_404(User, username=username)
print(obj) # This prints correct
url_ = profile.get_absolute_url()
print(url_) # This prints correct
user = self.request.user
print(user) # This prints correct
if user.is_authenticated():
if user in obj.followers.all(): # I know this is the source of the error.
obj.followers.remove(user)
else:
obj.followers.add(user)
return url_
Below are the Urls.py just in case
url(r'^(?P<username>[-\w]+)/follow/$', views.FollowToggle.as_view(), name='follow'),
You cannot use add and remove method for manytomany relation defined through third model. From the docs:
Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships
Instead you should use Contact manager:
if user.is_authenticated():
if user in obj.followers.all(): # I know this is the source of the error.
Contact.objects.filter(user_to=obj, user_from=user).delete()
else:
Contact.objects.create(user_to=obj, user_from=user)
In Django 2.2 you can use add, remove and set methods (Docs)
You can also use add(), create(), or set() to create relationships, as long as your specify through_defaults for any required fields
I'm trying to create a private chat with channels, I'm encountering an issue when passing an username to the url.
invalid literal for int() with base 10: 'username'
This error probably occurs because I'm using a ForeignKey because everything worked well using a ChatField and I want to know how I can resolve this issue.
models.py :
class Room(models.Model):
gig = models.ForeignKey(Gig, null=True)
creator = models.ForeignKey(User, related_name='creator', null=True)
views.py
def new_room(request):
try:
#get the submited product object
gig = Gig.objects.get(id=request.POST.get('inGig_id'))
except Gig.DoesNotExist:
return redirect('/')
creator = request.user
Room.objects.get_or_create(gig=gig, creator=creator)
return redirect(commenting_room, gig=gig.id, creator=creator)
def commenting_room(request, gig, creator):
room = Room.objects.get(gig=gig, creator=creator) #error occurs here
...
urls.py
url(r'^room/(?P<gig>\d+)/(?P<creator>\w+)/$', views.commenting_room, name='commenting_room_detail'),
Any suggestion on how I can resolve this problem ?
You should pass the creator id to .get and not the username text passed via the url, since creator is a ForeignKey field in Room:
def commenting_room(request, gig, creator):
creator_id = User.objects.get(username=creator).id
room = Room.objects.get(gig=gig, creator=creator_id)
Short version:
I have a Django app used for recipes, and want to filter data to be sent to a template in my view. I basically want all recepies that are added by a specific user to be sent as context. The following filtering returns an error message invalid literal for int() with base 10: my_username.
recipes = Recipe.objects.filter(added_by = uname)
The variable uname is passed from a template. On the other hand, filtering on request.user works fine, but is not what I want.
recipes = Recipe.objects.filter(added_by = request.user)
Details:
My models are given (relevant fields) as:
class Recipe (models.Model):
...
...
added_by = models.ForeignKey(User)
Where User is an existing Django user. When I call {{ recipe.added_by }} in my template, I get the username as wanted. This username is passed on to a view with href="/profile/{{recipe.added_by}}", where the view looks like the following:
def profile(request, uname):
print uname #Correct username printed
print request.user #Logged in user (not relevant, as userprofile should be visible for all)
recipes = Recipe.objects.filter(added_by = uname) #Does not work. Why?
#recipes = Recipe.objects.filter(added_by = request.user)
form = CommentForm(request.POST)
context = {
'uname': uname,
'recipes': recipes,
'form': form,
}
return render(request, '*app_name*/profile.html', context)
Not sure what I am missing, but from what I can tell, it seems to have something to do with the fact that added_by has a Foreign Key to a User. I also tried to change the filter argument to recipe__added_by__added_by = uname according to [1], but Django then returned an error saying "Cannot resolve keyword 'recipe' into field", which seems obvious. My url is:
url(r'^profile/([a-zA-Z0-9]+)/$', 'profile', name='*app_name*-profile'),
Thanks for any reply. Sorry if this should have been obvious.
[1] Django models filter by foreignkey
You can try like:
recipes = Recipe.objects.filter(added_by__username = uname)
And request.user works fine for Recipe.objects.filter(added_by = request.user) because request.user is an object. details: https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
When child class defined as
class Recipe (models.Model):
...
...
added_by = models.ForeignKey(User)
makemigration generates foreign key as added_by_id.
So, you have to use corresponding field name in filter.
Eg: recipes = Recipe.objects.filter(added_by_id = uname)