I am making a social media app and i am adding a edit profile function to it. But for some reason, the profile image which the user chooses is not being uploaded to the database. Please help me to do so.
My views.py
def edit_profile(request):
user = request.user
user_profile = profile.objects.get(user__username=user)
Profile = user_profile
myuser = User.objects.get(username=user)
if request.method == 'POST':
try:
username = request.POST['username']
name = request.POST['name']
email = request.POST['email']
image = request.FILES['img']
myuser.username = username
myuser.first_name = name
myuser.email = email
myuser.save()
Profile.user = myuser.username
Profile.name = myuser.first_name
Profile.img = image
Profile.save()
return redirect('/')
except:
return redirect('/')
else:
context = {
'user':user_profile,
'myuser':myuser,
}
return render(request, 'edit_profile.html', context)
my tempateview
<form action="/users/edit_profile/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<center>
<img src="{{user.img.url}}" style="border-radius: 50%; widows: 150px;height:150px; margin-left:-50px" onclick="document.getElementById('image').click()"><br>
<span class="click" onclick="document.getElementById('image').click()">Change Profile Picture</span>
</center>
<input type="file" name="img" id="image" accept="image/*" style="display:none"><br><br>
<label> Username </label><br>
<input type="text" name="username" class="edit" value="{{user.user}}" spellcheck="false"><br><br>
<label> Name </label><br>
<input type="text" name="name" class="edit" value="{{user.name}}" spellcheck="false"><br><br>
<label> Email </label><br>
<input type="email" name="email" class="edit" value="{{myuser.email}}" spellcheck="false"><br><br><br>
<input type="submit" value="Save changes" style="width:40%; float:right; margin-right:120px">
</form>
my models.py
class profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
img = models.ImageField(default='default.png', upload_to='profile_pics')
def __str__(self):
return "Profile({})".format(self.user.username)
Everything is working. Only the image file cannot be uploaded. Please help. Thankyou in advance.
this was a problem for me too. i solved this by saving the object like so:
from django.core.files import File
Profile.img.save(image.name , File(image))
Profile.save()
hope it helped you.
Related
This question already has an answer here:
Django login user never come true
(1 answer)
Closed 4 months ago.
I'm making an educational website in Django 4.1.1, and i need students to be able to register and login, so i created a Custom User Model Table in my models.py file.
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager
class Custom(UserManager):
def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, **extra_fields)
class Student(AbstractUser):
objects = Custom()
sex = models.CharField(max_length=50,default='male')
is_superuser = None
is_staff = None
groups = None
user_permissions = None
class Meta:
verbose_name = "Student"
verbose_name_plural = "Students"
def __str__(self):
return self.username
and then i created an HTML registration form to get data from the user
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'css/register.css' %}">
<form method="post">
{% csrf_token %}
<input type="text" name="firstName" placeholder="First Name" required minlength="3" maxlength="30">
<input type="text" name="lastName" placeholder="Last Name" required minlength="3" maxlength="30">
<input type="text" name="username" placeholder="Username" required minlength="3" maxlength="30">
<small>{{error}}</small>
<input type="email" name="email" placeholder="Email" required maxlength="64">
<small>{{error}}</small>
<input type="password" name="password" placeholder="Password" required minlength="8" maxlength="32">
<input type="password" name="passwordAgain" placeholder="Confirm Password" required minlength="8" maxlength="32">
<small>{{paswword_error}}</small>
<input type="radio" name="sex" value="male" checked>Male</input>
<input type="radio" name="sex" value="female">Female</input>
<button type="submit">Submit</button>
</form>
<script src="{% static 'js/register.js' %}"></script>
</html>
and then i set up my views.py file to get the data and store it the database , everything worked well so far .
here is my view.py file :
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Student
from django.contrib.auth import authenticate,login,logout
# Create your views here.
def home(request):
# return HttpResponse('This is The Home Page !')
return render(request, 'home/index.html')
def register(request):
if request.method == 'POST':
firstName = request.POST['firstName']
lastName = request.POST['lastName']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
passwordAgain = request.POST['passwordAgain']
sex = request.POST['sex']
if Student.objects.filter(username=username).exists() or Student.objects.filter(email=email).exists() or password != passwordAgain:
error = "Alrady Taken"
paswword_error = "Paswwords Don't Match"
return render(request,'register/register.html',{'error':error,'paswword_error':paswword_error})
else:
user = Student.objects.create_user(username,email,password)
user.first_name = firstName
user.last_name = lastName
user.sex = sex
user.save()
return redirect('login')
return render(request,'register/register.html')
def login(request):
if request.method == 'Post':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('home')
else:
return HttpResponse('error')
return render(request, 'login/login.html')
the problem is that the Login functionality is not working, it is not working at all , it's not returning anything neither sucess nor errors !
so how can i set up a login functionality that compares the data gotten from the user with the data in the database, and log in the user based on the right match ?
The Problem was that i was miss-spelling the request.method == 'Post' , it should be request.method == 'POST' , the second problem was that i was naming my login view login, and that's unacceptable, because that name is already taken by django.contrib.auth.login, so i changed the view name , and the problem was solved successfully !
I am following a Django course on youtube, and I need a small change in my Django form.
The form looks like:
Rendering the form fields in 'edit-user.html' template:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-input">
<label for="id_{{field.label}}">{{field.label}}</label>
{{field}}
</div>
{% endfor %}
<div id="lrf-options">
<div id="lrf-btn">
<input class="btn" type="submit" value="Update">
</div>
</div>
</form>
What I am actually asking:
So in Avatar Currently: 1044-3840x2160.jpg, I want actual image to display here instead of <filename>.
I think maybe I need to change my forms.py to generate <img> tag instead if <a> tag but I don't know how to do this.
models.py
class UserModel(AbstractUser):
name = models.CharField(max_length = 90)
email = models.EmailField(unique = True)
about = models.TextField(blank = True, null = True)
avatar = models.ImageField(null=True, default="avatar.svg")
USERNAME_FIELD = 'email'
and forms.py is:
class UserForm(forms.ModelForm):
class Meta:
model = UserModel
fields = ['avatar', 'name', 'username', 'email', 'about']
and in views.py the update function is:
def editUserProfile(request):
user = request.user
form = UserForm(instance=user)
if request.method == 'POST':
form = UserForm(request.POST, request.FILES, instance = user)
if form.is_valid():
form.save()
return redirect('chat:userProfileView', uname = user.username)
context = {
'form' : form
}
return render(request, 'chat/edit-user.html', context)
You can add request.user.avatar.url instead of currently url.Hide input and use jquery to give a click to input:
<div class="form-input">
<label for="id_Avatar">Avatar</label>
Currently:
<img id="current-avatar" src="{{request.user.avatar.url}}"/>
<br>
<a id="change-avatar">Change</a>
<input id="avatar-input" style="display:none;" type="file" name="avatar" accept="image/*" id="id_avatar">
</div>
<script>
$("#change-avatar").click(function(){
$("#avatar-input").click();
});
</script>
If you don't have jQuery add this to your main HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
I have created a Django application in which i have a signup page which asks a user to upload their profile picture.
When I'm uploading the profile picture through the Django admin panel, the images are being uploaded to the correct path and are being displayed in the website. However, the error comes when I directly select the image to upload when signing up and then When I click on the uploaded image in Django admin it shows page not found and the path to the image is being showed as C:\Users\hp\Workspace\findem\media\image.jpg
Settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'findem/static')
]
# media folder settings
MEDIA_ROOT = os.path.join(BASE_DIR , 'media').replace('\\', '/')
MEDIA_URL = '/media/'
User Model
class UserProfile(AbstractBaseUser, PermissionsMixin):
"""Represents a user profile inside our system"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255, default=profile_pic)
profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='photos/User.jpg')
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
highest_degree_earned = models.CharField(max_length=255, blank=False)
college_name = models.CharField(max_length=255, blank=False)
graduation_year = models.IntegerField(default=2020, blank=False)
Template :
<form class="needs-validation" novalidate autocomplete="off"
action="{% url 'signup' %}", method="POST" >
{% csrf_token %}
<div id="Personal_Information">
<h5 class="loginSignup">Personal Information</h5>
<div class="form-group row">
<label for="inputprofile" class="col-sm-2 col-form-label">Profile Picture</label>
<div class="col-sm-5">
<div class="input-group">
<div class="custom-file">
<input type="file" accept="image/png, image/jpeg, image/gif" class="custom-file-input" id="inputprofile" name="inputprofile">
<label class="custom-file-label" for="inputprofile" aria-describedby="inputprofile">Choose file</label>
</div>
</div>
</div>
</div>
<div class="form-group required row">
<label for="inputname" class="col-sm-2 col-form-label">Full Name <span id="required-field">*
</span>
</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="inputname" id="inputname" placeholder="Enter Your Full Name" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter your full name.</div>
</div>
</div>
<div class="form-group row">
<label for="inputemal" class="col-sm-2 col-form-label">Email <span id="required-field">*</span></label>
<div class="col-sm-5">
<input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Enter a Valid Email Address" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please provide a valid email.</div>
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label">Password <span id="required-field">*</span></label>
<div class="col-sm-5">
<input type="password" class="form-control" id="inputPassword" name="inputPassword" placeholder="Choose a Password" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please chose a valid password.</div>
</div>
</div>
<button type="submit" class="btn btn-success mt-3" id="loginButton">Sign Up</button>
</form>
view :
def signup(request):
"""View for Signing-up into the system"""
if request.method == 'POST':
# Get form value
profile_picture = request.POST.get('inputprofile')
name = request.POST.get('inputname')
email = request.POST['inputEmail']
password = request.POST['inputPassword']
highest_degree_earned = request.POST['inputDegree']
college_name = request.POST['CollegeName']
graduation_year = request.POST['inputGradYear']
skill_1 = request.POST['upload_skill1']
skill_2 = request.POST.get('upload_skill2', '')
skill_3 = request.POST.get('upload_skill3', '')
skill_4 = request.POST.get('upload_skill4', '')
skill_5 = request.POST.get('upload_skill5', '')
skill_6 = request.POST.get('upload_skill6', '')
join_date = datetime.now()
# Check Username
if UserProfile.objects.filter(name=name).exists():
messages.error(request, "That Name already taken")
return redirect('signup')
# Check email
else:
if UserProfile.objects.filter(email=email).exists():
messages.error(request, "That email is being used")
return redirect('signup')
else:
# Looks Good
user = UserProfile.objects.create_user(profile_picture=profile_picture, name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
# #Login after register
# auth.login(request, user)
user.save()
messages.success(request, "You are now registered and can log in")
return redirect('login')
else:
return render(request, 'pages/signup.html')
Change your form tag to be be like this :
<form class="needs-validation" novalidate autocomplete="off"
action="{% url 'signup' %}", method="POST" enctype="multipart/form-data">
add request.FILES to profile_picture like that :
profile_picture = request.FILES.get('inputprofile') or None
Than in your create request you do that :
else:
if UserProfile.objects.filter(email=email).exists():
messages.error(request, "That email is being used")
return redirect('signup')
else:
# Looks Good
if profile_picture != None
user = UserProfile.objects.create_user(profile_picture=profile_picture, name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
else:
user = UserProfile.objects.create_user(name=name, email=email,
password=password, highest_degree_earned=highest_degree_earned, college_name=college_name,
graduation_year=graduation_year, skill_1=skill_1, skill_2=skill_2, skill_3=skill_3, skill_4=skill_4,
skill_5=skill_5, skill_6=skill_6, join_date=join_date)
For the default picture try to change it to this :
profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='/media/photos/User.jpg')
In the HTML form, you need to use.
enctype="multipart/form-data"
Without that, the file is not sent to the server.
Add this tag to your form
<form method="post" enctype="multipart/form-data">
....
</form>
and to get the files at django part use request.FILES.get('filename') in your view
profile_picture = request.FILES.get('inputprofile')
I have html form which I want to send and save to django model. When I try to send message I get an error:
ValueError at /account/userinfo/akylson/
"<Mail: hhh>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/account/userinfo/akylson/
Django Version: 1.11.3
Exception Type: ValueError
Exception Value:
"<Mail: hhh>" needs to have a value for field "id" before this many-to-many relationship can be used.
You can see my code below.
Here is my html form below:-
<form role="form" class="form-horizontal" method="post">
{% csrf_token %}
<div class="form-group">
<input type="checkbox" id="id_receiver" name="receiver" value="{{ user.username }}" checked hidden>
<label class="col-lg-2 control-label">Тема</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="id_subject" name="subject" value="{{ subject }}" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Сообщение</label>
<div class="col-lg-10">
<textarea rows="10" cols="30" class="form-control" id="id_message" name="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button"><i class="fa fa-plus fa fa-white"></i>
<span>Приложение</span><input type="file" name="files[]" multiple=""></span>
<button class="btn btn-send" value="submit" type="submit">Send</button>
</div>
</div>
</form>
Here is my view.py:
#login_required()
def userinfo(request, username):
username = User.objects.get(username=username)
args = {}
args['user'] = username
if request.method == 'POST':
sender = request.user
receiver = request.POST['receiver']
subject = request.POST['subject']
message = request.POST['message']
b = Mail.objects.create(sender=sender, receiver=receiver, subject=subject, message=message)
b.save()
return render(request, 'account/userinfo.html', args)
Here is my models.py:
class Mail(models.Model):
sender = models.ForeignKey(User, related_name='mail_sender')
receiver = models.ManyToManyField(User, related_name='mail_receiver')
subject = models.CharField(max_length=200)
message = RichTextUploadingField()
date = models.DateTimeField(auto_now=True, null=False, blank=False)
class Meta():
ordering = ['-date']
def __str__(self):
return self.subject
Here is my forms.py:
class NewMailForm(forms.ModelForm):
class Meta:
model = Mail
fields = (
'sender',
'receiver',
'subject',
'message',
)
widgets = {'receiver': forms.CheckboxSelectMultiple()}
You have to pass user instances to your views.py.
Change your views.py as showed below,
views.py:
#login_required()
def userinfo(request):
user = request.user
form = NewMailForm(request.POST or None)
if request.method == 'POST':
if not form.is_valid():
print form.errors
return render(request,'')
else:
sender = user
receiver = form.cleaned_data.get("receiver")
subject = form.cleaned_data.get("subject")
message = form.cleaned_data.get("message")
b = Mail.objects.create_user(
sender=sender,
receiver=receiver,
subject=subject,
message=message)
b.save()
return render(request, 'account/userinfo.html')
and forms.py:
<form action="." method="POST">{% csrf_token %}
{{ form.as_p }}
</form>
This will create a new mail objects with requested user.
In your views.py create an instance of your model
for example m = Mail()
then post each of the field using the instance for example
m.receiver = request.POST.get('receiver')
then save with
m.save()
Before a Many2many field can be linked Django needs the id of the record on the other side of the relationship (in this case your Mail) model.
So you have to actually create it before setting the receiver like this:
b = Mail.objects.create(sender=sender, subject=subject, message=message)
b.receiver = receiver
b.save()
You have made several mistakes:
forms.py is not required if you have made an HTML form and linked to project.
You have not defined b. Just written b.save
Just debug these errors and you are Done!
i want to create an application that admin can make user with a new messages that encrypted into database. I have the core function and all can work properly. But, i still can't encrypt the message from text to md5/sha1. I have read and try this and this. But, i still can't do it. I'm new in django, and I'm very grateful for your response. Thank you
This is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User) #digunakan untuk relasi ke model User (default) alias UserProfile adalah sebagai extending model
CATEGORY_CHOICES = (
('admin','Admin'),
('user','User'),
)
hak_akses = models.CharField(max_length=100, choices = CATEGORY_CHOICES)
messages = models.CharField(max_length=100, blank=True)
# password_pckelas = models.CharField(max_length=100, blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
This is my view function:
def tambah_user(request, template_name='form_user.html'):
#cek session
if 'username' in request.session and request.session['hak_akses'] == 'admin':
#ambil dari database untuk mengaktifkan ubah_password_admin
users = User.objects.all()
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
messages = profile_form.data['messages'] #ambil messages
if request.method == 'POST':
if user_form.is_valid() and profile_form.is_valid():
#i want hash messages in here and then save into database
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('manajemen_user')
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
data = {
'user_form': user_form,
'profile_form': profile_form,
'object_list': users
}
return render(request, template_name, data)
#jika session tidak ada
else:
return HttpResponseRedirect('/simofa/logout')
This is my html templates:
<form name="tambah_user" class="form-horizontal style-form" method="POST">{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Nama User</label>
<div class="col-sm-10">
<!-- <input type="text" class='form-control'> -->
{{ user_form.username }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Password</label>
<div class="col-sm-10">
{{ user_form.password }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Messages</label>
<div class="col-sm-10">
{{ profile_form.messages }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Hak Akses</label>
<div class="col-sm-10">
{{ profile_form.hak_akses }}
<br><br><br>
<button type="submit" class="btn btn-theme">Submit</button>
</div>
</div>
</form>
Hashing is not encrypting!
A hash is a function that converts one message to another. Consider a hash function (LAME_HASH) that just takes the count of the number of characters in a string.
LAME_HASH("TOOMANYSECRETS")
>>> 13
LAME_HASH("SETECASTRONOMY")
>>> 13
If I tell you my string is "TOOMANYSECRETS" and the hash was 10, you can immediately tell I am lying. But, if I tell you the hash is 13, you can't verify what the message is, it could be "TOOMANYSECRETS" or "SETECASTRONOMY". While this all seems trivial, this is essentially how hashing mechanisms like MD5 and SHA work.
There is no "decryption" of hashes, and if anyone tells you otherwise they are lying, or the entire security world would collective explode.
i can encrypt plain text to the md5 / sha1 with this
import hashlib
print hashlib.md5('test').hexdigest()
and that is the answer I was looking for