Django store user image in model - django

I'm trying to create a field in a model, that should store an image for a registered user.
This image should be renamed and stored in a separate user directory like media/users/10/photo.jpeg.
I've searched a lot, but still can't find how to do it cleanly and correctly. It seems to me that many sites require the same functionality and this should be in django docs, but it is not.

You want to use the "upload_to" option on an ImageField
#models.py
import os
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
profile_image = ImageField(upload_to=get_image_path, blank=True, null=True)
This is code directly from a project of mine. The uploaded image goes to /MEDIA_ROOT/photos/<user_id>/filename
For what you want, just change the 'photos' string to 'users' in def get_image_path
Here is the small bit about it in the docs, under FileField details

I suggest you to look into django-photologue. Its a django app with all image managment, uploading and storing already done!
More about at: http://code.google.com/p/django-photologue/

You'll need to make a model that has a foreign key to the User model, where you can have an image field for the User. I would not recommend modifying the User model itself.

Related

I have replaced the user model provided by Django with the one I created, the problem is on the admin page

I have replaced the user model provided by Django with the one I created but I don't know how to solve the problem in admin can't process anything!
it always returns IntegrityError in /admin/mysite/userfiles/add/, working with insert, update or delete in admin
enter image description here
I really need your help, I've been looking everywhere but can't find anything?
Please before you ask a question, review this section: How to ask a question
If you want to add a UUID field in a model you need to import the following:
import uuid
Then in the model you need to create a new field:
unique_uuid = models.CharField(max_length=1024, null=True, blank=True)
Finally you need to update the default save method of the model:
def save(self, trigger=True, *args, **kwargs):
if not self.unique_uuid:
self.unique_uuid = uuid.uuid4()
super(ModelName, self).save(*args, **kwargs)
Its one of those things where you'd rather not start from here if you want to get there. In the Django doc, look Here
If you already have Django default user objects, then you have to extend using a OneToOne relation to an object of your own definition (it's often called a profile). So add
class Profile( models.Model)
user = models.OneToOneField( User, on_delete=models.CASCADE, )
uuid = models.UUIDField( default=uuid.uuid4, editable=False)
makemigrations and migrate and you will then be able to refer to user.profile.uuid. The default is a callable so the migration will call it to assign a unique UUID to all existing users (I think).
The doc I linked explains how to change Django admin to handle the profile object.
Anything else you want to add to your users goes in their profile object.

How do i have a different data for every account in Django

Excuse my lack of knowledge I'm a complete newbie to Backend Development.
I've had this very simple model for testing
class Text(models.Model):
text = models.CharField(max_length=30)
def __str__(self):
return self.text
And with that I have this simple app that saves text through a form
and also I've made an entire basic login & sign up system with UserCreationForm and AuthenticationForm and with that I've made 3 different users.
With my lack of knowledge, I'm expecting to see a completely fresh app with no text saved to it when I log in with brand new user. But instead I just saw the same texts saved as every other users.
So my question is what Django method should I learn so that my text database is empty everytime I create a new user
Thank you in advance
from django.contrib.auth.models import User
class Text(models.Model):
text = models.CharField(max_length=30)
user = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.text
now every text are related to user, on_delete you can search about it
You can add a user foreign key in this table which will point user table
like this
user= models.Foreignkey(User,on_delete=models.CASCADE)
and for showing the text you can query the Text.objects.filter(user=request.user)

Django blogs using Rest framework connecting mutliple images to that content in single object

Is there anyway where we can build logic Using django rest framework
where user can add blog with multiple images and content accordingly and when saved
and retrieved it should be able to display the same kind of UI depening up on the frontend app
same like medium platform
Note:
My question isn't about adding multiple images and content using Rest framework
but its about fetching and displaying the data based on how user sent it the server
For eg:
<Image>
content for that image
<Image2>
content for this image
i just want to know how to associate those images to that content
i want to add content to that image
or is there anyway where we can store image and all the content exacty and save it in TextField
I've searched a lot about this but unfortunately I've not found a way to make this happen
Read about relationships in Django (and SQL in general)
django relations
it sounds like you're looking for something like the following:
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
# Always override the user model provided by Django when starting a project. the docs themselves state that.
pass
class Image(models.Model):
image = models.ImageField()
added = models.DateTimeField(auto_now_add=True)
# using get_user_model to get the User model, always better then referencing User directly
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="user_images",
null=False,
blank=False
)
class ImageContent(models.Model):
title = models.CharField(max_length=140, null=False, blank=False)
content = models.TextField(max_length=500)
image = models.OneToOneField(Image, on_delete=models.CASCADE, null=False, blank=False)
Some notes:
I haven't dealt myself with Images field But I remember it does require a special library (pillow).
getting the data in a certain order should be easy enough if you understand the queryset object:
queryset link
using stuff like order_by will help you return the response in the order you like.
the models I've written here are not the only way to achieve the goal you've set, I strongly recommend reading about relations and models in Django.

Django - save user in another table

Is there a way to save my user registration in another table from the database?
I don't want to mix AdminUsers with CommonUsers (All the tutorials I've seen, they save the registration inside auth_user)
The reasons:
CommonUsers have different columns and informations
CommonUsers can upload content
AdminUsers verify the content uploaded by the CommonUsers and make sure there is nothing inappropriate
What do I need to use? models? modelform? forms?
The best solution for you is to subclass the User model and add the extra columns you need for your CommonUsers. Your code will probably end up looking something like this:
models.py
from django.contrib.auth import models
from django.db.models import *
class CommonUser(models.User):
custom_field1 = CharField(max_length=255, null=True)
custom_field2 = CharField(max_length=255, null=True)
Link to docs

Django user profile

When adding additional fields to a user profile, such as location, gender, employer, etc., should I be adding additional columns to django.contrib.auth.models.User and saving it there? Or should I be creating a new table to save user profile information?
Also, when a user uploads a profile picture, should I be saving this in the same table? (Note this is not a production server, I'm just doing this on my local runserver to figure things out). Thank you
You have to make a model for the user profile:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
location = models.CharField(max_length=140)
gender = models.CharField(max_length=140)
employer = models.ForeignKey(Employer)
profile_picture = models.ImageField(upload_to='thumbpath', blank=True)
def __unicode__(self):
return u'Profile of user: %s' % self.user.username
Then configure in settings.py:
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
Conceptually, OneToOneField is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object. This is the recommended way of extending User class.
class UserProfile(models.Model):
user = models.OneToOneField(User)
...
Current Django is 1.9 and here are some updates to the outdated accepted answer
use models.OneToOneField(User)
add related_name='profile'
use .__str__() and .format() for Python 3
like so
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
location = models.CharField(max_length=140)
gender = models.CharField(max_length=140)
...
def __str__(self):
return 'Profile of user: {}'.format(self.user.username)
Using related_name you can access a user's profile easily, for example for request.user
request.user.profile.location
request.user.profile.gender
No need for additional lookups.
Django provides a way of storing additional information about users in a separate table (called user profile).
Starting with Django 1.5 you can replace the default User with your custom user object using a simple settings entry:
AUTH_USER_MODEL = 'myapp.MyUser'
For slightly more details, check this Django documentation entry.
There's a solution I found here. Basically you just extend the default form UserCreationForm but keeping the same name. It works seamlessly with the way Django's docs tell you to do UserProfiles.
Answer can be updated to add signal receiver which will create the profile if it does not exist and update if it is already there.
#receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
This https://simpleisbetterthancomplex.com/tutorial/2016/11/23/how-to-add-user-profile-to-django-admin.html post also includes how to edit, list the custom profile in admin panel.
The current 2 top answers are outdated
If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. [..] Instead of referring to User directly [..] when you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.
from django.conf import settings
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="userprofile",
)
https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#referencing-the-user-model
If you want to get user profile data from user objects.
from django.contrib.auth.models import User
request.user.profile