My models file:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Profile(models.Model):
user= models.OneToOneField(User,on_delete=models.CASCADE)
description = models.CharField(max_length=100,default='')
city = models.CharField(max_length=100,default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
avatar = models.ImageField(upload_to='avatars/',blank=True,default='avatars/no.png')
genre = models.IntegerField(choices=((1, ("Homme")),
(2, ("Femme")))
)
def __str__(self):
return self.user.username
Locally when I fill the form, the image is saved in my folder media/avatars/.
But on heroku the image is not saved in this folder and therefore it can't be displayed.
Related
I am working on an app with Django backend and I am currently developing the signup page. Here's my code:
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from datetime import date
from .countries import COUNTRIES
from .hobbies import HOBBIES
class Hobbies(models.Model):
hobby = models.CharField(max_length=255, choices=HOBBIES)
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
def username(self):
usern = User.objects.get(id=self.user.id)
usern = usern.username
return usern
setup = models.BooleanField(default=False)
gender = models.CharField(max_length=100, blank=True)
dob = models.DateField(blank=True)
def age(self):
today = date.today()
age = today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
return age
orgin = models.CharField(max_length=300, choices=COUNTRIES, blank=True)
lives = models.CharField(max_length=300, choices=COUNTRIES, blank=True)
bio = models.CharField(max_length=150, blank=True)
email = models.CharField(max_length=255, blank=True)
image = models.ImageField(upload_to='images', blank=True)
hobbie = models.ManyToManyField('Hobbies', blank=True)
views.py-
from django.shortcuts import render
from rest_framework import viewsets, status
from .serializers import UserSerializer, ProfileSerializer
from .models import Profile
from django.db import IntegrityError
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth import authenticate
# Create your views here.
#.....
#csrf_exempt
def signup(request):
if request.method == 'POST':
data = json.loads(request.body)
username = data.get("username", "")
password = data.get("password", "")
try:
user = User.objects.create_user(username, '',password)
user.save()
created = True
profile = Profile.objects.create(user=user)
profile.save()
except IntegrityError:
created = False
return JsonResponse(created, safe=False)
Everything works when I try to create a new user without creating a new profile. But when I try to create a Profile when I am creating the User I get an "IntegrityError.": "NOT NULL constraint failed: home_profile.dob" .How can I fix this?
Your problem lies here:
dob = models.DateField(blank=True)
DateFields, if empty, are rendered as null in the database, so you need to add
dob = models.DateField(blank=True, null=True)
As a rule of thumb, blank=True says the field need not be filled in for forms. null=True says the database can accept a null value. The exception is for string types, eg CharField and TextField, which only use blank=True as django saves an empty string, "", rather than a null value.
I have made a feature in Django where every user can change his platform's logo. The image selected by the user will be saved in static/{user.customer.public_id}/platformLogo/image.jpg. When i save the changes, i can see the uploaded image's path which also contain unique public ID which i don't want user to see for security purpose. Can anyone help me to hide this image path in Django for user? Attaching my code part here below.
Here we can see the image path which has unique ID in path, which we need to hide
Here is the uploaded image path directory
Here is my models.py
from sre_constants import CATEGORY
from unicodedata import category
from attr import fields
from django.db import models
from datetime import date
from django.contrib.auth.models import User
import uuid
def upload_path(instance, filename):
filename = str(date.today())
name = instance.user.customer.public_id.hex
return f'{name}/platformLogo/{filename}.jpg'
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank =True, on_delete=models.CASCADE)
public_id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
name = models.CharField(max_length=200, null=True)
otp_code = models.CharField(max_length=6, null=True)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, unique=True)
phone = models.CharField(max_length=200, null=True)
profile_pic= models.ImageField(upload_to=upload_path, default='logo.png', null=True, blank=False,)
def __str__(self):
return self.name
Here is my views.py
#login_required(login_url='login')
def accountSetting(request):
customer = request.user.customer
form = CustomerForm(instance= customer)
if request.method == 'POST':
form = CustomerForm(data=request.POST, files=request.FILES, instance=customer)
if form.is_valid():
form.save()
context = {'form': form}
if request.user.is_anonymous:
return redirect("/")
return render(request, 'account-settings.html', context)
Here is my forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Customer
from django import forms
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
exclude = ['user', 'email','name','otp_code']
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','first_name','last_name', 'email', 'password1', 'password2']
Here is settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/platformLogo/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/platformLogo')
Since you already made public_id UUID, why not hash the logo and image name?
In Django environments I’ve used xsendfile with Apache or nginx. You end up placing the images in a folder that is accessible by Apache and served by apache, but can only be served after a request to the Django backend. It prevents all of the logos being visible to prying eyes.
I'm following a tutorial on Django in Python, I'm trying to add a bio to my user profile page, however I get this error:
OperationalError at /admin/users/profile/
no such column: users_profile.bio
Here is my models.py file:
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
bio = models.TextField(User)
def __str__(self):
return f'{self.user.username} Profile'
Here is my admin.py file:
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
Just change def __str(self):
def __str__(self):
return str(self.user.user)
OR
def __str__(self):
return 'Check if it is the problem'
I want to be able to replace my homepage image from the Django admin panel. I can upload to my ../media/homepage directory just fine but I want to first delete any image named "bg.jpg" and rename my new image to "bg.jpg".
models.py
from django.db import models
from django.core.files.storage import FileSystemStorage
from datetime import datetime
class Homepage(models.Model):
homepage_image = models.ImageField(upload_to="../media/homepage",blank=True)
image_text = models.CharField(max_length=200, blank=True)
header_title = models.CharField(max_length=200, blank=True)
header_text = models.TextField(blank=True)
class Meta:
verbose_name_plural = "Homepage"
def __str__(self):
return "Homepage"
Also is there any way I can display an image preview in the panel of the current image?
I am programming in Django 1.5 with Python 2.7 on Windows Vista. I am trying to create user profiles. However, when
I visit localhost:8000/admin/home/userprofile, I got the 1146, "Table 'demo.home_userprofile' doesn't exist error.
Now I have in settings.py:
AUTH_PROFILE_MODULE = 'home.userProfile'
and in models.py, where I have the defining values
from django.db import models
from django.contrib.auth.models import User
class userProfile(models.Model):
user = models.OneToOneField(User)
photo = models.ImageField(upload_to = url)
telefono = models.CharField(max_length = 30)
def url(self, filename):
ruta = "MultimediaData/Users/$s/%s"%(self.user.username, filename)
return ruta
def __unicode__(self):
return self.user.username
and in admin.py:
from django.contrib import admin
from demo.apps.home.models import userProfile
admin.site.register(userProfile)
I have been mulling this over for a while now. What seems to be wrong?