I want the user to upload the profile picture on the profile page but it is not storing it in the media/documents folder, and yes, I have put enctype="multipart/form-data" in the html form and the method is post. I'm new to django so please provide a simple solution
models.py
class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',height_field=200,width_field=200,default='')
forms.py
class ProfilePicForm(forms.ModelForm):
class Meta:
model=User
fields=['username','profile_pic']
views.py
def upload(request):
if request.method == 'POST':
username=request.POST['username']
m=User(username=username)
m.profile_pic=request.FILES['profile_pic']
m.save()
return render(request,'LoginPage/done.html')
else:
pic=ProfilePicForm()
return render(request,'AfterLogin/profile.html')
html file
<form method="POST" enctype="multipart/form-data" action="{% url 'LoginPage:upload' %}">
{% csrf_token %}
<p>Upload your profile photo</p><br>
<input id="id_image" type="file" class="" name="image">
<input type="hidden" name="username" value="{{ username }}">
<input type="submit" value="Submit"/>
</form>
Have a look at this:
Need a minimal Django file upload example
Also, try sharing the error you are getting when trying to upload picture.
I think it would be better for you to use the standard User model created by Django which already has the fields first_name, last_name, username, password and email. Then you create a new model with a OneToOneField with the model user.
If the image uploads and if you get a 404 when going directly to the image url when running the server, then you have forgotten to serve the image, which you have to do when you are in production phase.
urlpatterns = [
...patterns...
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Something like this should work:
modles.py
from django.contrib.auth.models import User
class UserPicture(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
picture = models.ImageField(upload_to='...')
forms.py
class ProfilePicForm(forms.ModelForm):
class Meta:
model = UserPicture
fields=['profile_pic']
views.py
def your_view(request):
...
if request.method == 'POST':
form = UserPicture(request.POST, request.FILES)
if form.is_valid():
userprofile = form.save()
userprofile.user = request.user
userprofile.save()
...
You don't have to define own User model since Django has it's own: https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#user-model
And as Jonatan suggested - post error code. If there's none, remove this try ... except: pass.
Related
I am really new to django and I am building a website for internal use in my company. I have extended the user model with another model called "profile" in order to store extra information about each user, including a profile picture.
I have set up a form.py class with the data i'd like to be able to modify:
class UserForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['office','role', 'userImage']
The form in the html is as follows:
<form class="form" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form__group">
<label for="Profile.userImage">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<div class="form__action">
<a class="btn btn--dark" href="{% url 'user-profile' request.user.id%}">Cancel</a>
<button class="btn btn--main" type="submit">Update</button>
</div>
</form>
And in the views.py, here is the function that takes care of this:
def update_user(request):
user = request.user
profile = request.user.profile
if request.method == 'POST':
form = UserForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return redirect('user-profile', pk=user.id)
else:
form = UserForm(instance = profile)
return render(request, 'base/update-user.html', {'form': form})
And the profile model is:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
job= models.TextField(max_length=50, blank=True, verbose_name="Centro")
role= models.TextField(null=True, max_length=50, blank=True, verbose_name="Cargo")
userImage = models.ImageField(upload_to='profileImages/', default='profileImages/happy.jpg', verbose_name="Profile Image")
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
in addition, the MEDIA_ROOT and MEDIA_URL are as follows:
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/'
The form works fine for all fields, they both dispplay and update all the information regarding the "office" and "job" fields, but not the profile image.. It neither uploads a file to the folder I have assigned it to upload to. Even when I manually insert another image in the folder, it doesn't change it. Everything works through django admin though. Images are uploaded and changed correctly. It just wont do it via the form, no errors come up and the terminal doesn't display any issues, neither does the console in the browser.
I don't know what to do, please let me know if you need any extra information in order to diagnose the problem.
I appreciate any help provided!
I am trying to save a file and some other details in django using forms.
And I only want it to save a CharField and a FileField but not the country field.
For country field I want it to take its value through a post request.
But the form isn't saving. The errors says "data didn't validate".
Also this method works fine if I don't use a FileField.
models.py
class Simple(models.Model):
name = models.CharField(max_length=100)
city = models.FileField(upload_to='marksheet')
country = models.CharField(max_length=100)
forms.py
class SimpForm(forms.ModelForm):
class Meta:
model = Simple
fields = ['name','city']
A snippet from upload.html
<form action="upload" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Test input</label>
<input type="text" name="country">
{{form.name}}
{{form.city}}
<button type="submit">Submit</button>
</form>
views.py
def upload(request):
if request.method == 'POST':
a = request.POST.get('country')
form = SimpForm(request.POST,request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.country = a
post.save()
return HttpResponse('saved')
else:
return HttpResponse('ERROR SAVING')
else:
form = SimpForm()
return render(request,'upload.html',{'form':form})
You are not passing request.FILES in your form. You should pass it like this:
form = SimpForm(request.POST, request.FILES)
More information on file uploads can be found in documentation.
I'm trying to upload image using django forms, and then assign it to my model object image field.
forms.py
class MemberRegistrationForm(forms.ModelForm):
birthday=forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)
class Meta:
model=Member
fields=('birthday','photo',)
models.py
class Member(models.Model):
user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
birthday=models.DateField(blank=True,null=True)
photo=models.ImageField(upload_to='account/%Y/%m/%d',blank=True)
def __str__(self):
return "{} /'s profile ".format(self.user.username)
urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Parsing form page
<form class="" action="." method="post">
{{form.as_p}}
{{form_member.as_p}}
{% csrf_token %}
<input type="submit" name="" value="Create my account">
</form>
Display page
<img width="90px;" height="180px;"src="{{member.photo.url}}" alt="">
views.py
I guess problem is here.I can not extract the uploaded image from form and assign it to my model object field
def user_signup(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
form_member=MemberRegistrationForm(request.POST,request.FILES)
if form.is_valid() and form_member.is_valid():
user=form.save(commit=False)
user.set_password(
form.cleaned_data['password']
)
user.save()
member=Member.objects.create(user=user,
photo=request.FILES['photo'], #HERE I'M NOT SURE IF THIS THE RIGHT WAY OR NOT
birthday=form_member.cleaned_data['birthday'])
return render(request,
'account/registeration_done.html',
{'user':user,
'member':member,
'form':form,
'form_member':form_member,
})
You have to specify enctype="multipart/form-data" in your html markup.
Also, you can find the work example upload form here
https://github.com/miletskiy/FortyTwoTestTask/blob/master/apps/hello/templates/edit_applicant.html#L20
I'm trying to get a simple form working. Oddly, other forms I wrote in this app are working fine, but this one wont show the fields. Can anyone tell me what I'm missing? Here are the files
views.py:
def newnote(request, record_id):
if request.method == 'POST':
form = NoteForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/tracker/all/')
else:
form = NoteForm()
return render(request, 'tracker/noteform.html', {'form': form})
models.py
class Note(models.Model):
record = models.ForeignKey(Record, on_delete=models.CASCADE)
note_text = models.CharField('Notes', max_length=2000)
note_date = models.DateField('Date Entered')
forms.py
class NoteForm(forms.Form):
class Meta:
model = Note
fields = ['note_text',
'note_date'
]
template (noteform.html)
<form action="/tracker/newnote/" method="post">
<div id="fields">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</div>
</form>
One other note, I have commented out the div id called "fields", to rule out CSS as the issue.
Your form is based on form.Form, which doesn't know anything about models, doesn't expect a Meta class, and expects all its fields to be declared manually - since you have not declared any fields, nothing will show on the template.
It should inherit forms.ModelForm instead.
I have a form where user just uploads an image,but problem is when I choose an image and press button to submit. It says This field is required.on the page although I have already pointed the image. And that's all it does.I checked if it was actually submitted but no, it was not.What could be the problem ?
Models.py
class pic(models.Model):
username = "anonymous"
picpost = models.ImageField(upload_to='anon_pics')
creation_date = models.DateTimeField(auto_now_add=True)
forms.py
from django import forms
from .models import pic
class PicForm(forms.ModelForm):
class Meta:
model = pic
fields = [
"picpost"
]
view.py
def pic_create(request):
form = PicForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
context = {
"form" : form,
}
return render(request, "create_pic.html", context)
create_pic.html
<body>
<form method='POST' action=''>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Upload Picture' />
</form>
</body>
Any help is highly appreciated.Thank you very much!
There are two issues here.
Firstly, your view needs to pass request.FILES as well as request.POST to the form.
Secondly, your form element in the template needs to include enctype="multipart/form-data".