Profile picture does not update after form submitted in django - python

I also created UserUpdateForm class which i did not include here and if i try to change my name and email through UserUpdateForm class it works but if try for profile picture it did not works
views.py
from django.shortcuts import render, redirect
from .forms import ProfileUpdateForm
def editprofile(request):
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid():
p_form.save()
return redirect('profile')
else:
p_form = UserRegisterForm(instance=request.user.profile)
context = {
'p_form': p_form,
}
return render(request, 'users/editprofile.html', context)
forms.py
from django import forms
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
html template
<form class="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form__group form__avatar">
<label for="avatar">Upload Avatar</label>
<input class="form__hide" required type="file" name="avatar" id="avatar" accept="image/png, image/gif, image/jpeg, image/jpg"/>
</div>
</form>

Related

How to save form data from base.html in django?

In my app, I have created a context_proccessors.py to show the form to base.html file.
I am able to show the form in the base.html file. But the problem I am facing is I have no idea how to save that form data from base.html since there is no view for the base.html. Below is my code:
models.py
class Posts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts')
post_pic = models.ImageField(upload_to='post_pic', verbose_name="Image")
post_caption = models.TextField(max_length=264, verbose_name="Caption")
created_date = models.DateTimeField(auto_now_add=True)
edited_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.user.username}"
forms.py
from django import forms
from post_app.models import Posts
class PostForm(forms.ModelForm):
class Meta:
model = Posts
exclude = ('user',)
context_proccessors.py
from post_app.forms import PostForm
def post_form(request):
form = PostForm
return {
'post_form': form,
}
base.html
<form method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>
I want the form to be displayed on every page so that the user can submit data from anywhere
def PostView(request):
form = PostForm()
if request.method == 'GET':
return render(request, 'base.html', {form:form})
elif request.method == 'POST':
form.save(request.data)
In the views.py of your app you can define this view, and the you have to provide it an url in the urls.py of the root directory. So evere time there is a request on that url, if the method is GET, the form will be rendered on base.html file, if the method is POST, the post will be saved.
By following the answer by N T I have implemented this. So, I had to make a URL pattern for the view and use that URL pattern in the action in the form of base.html.
view.py
#login_required
def postsaveview(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
user_obj = form.save(commit=False)
user_obj.user = request.user
user_obj.slug = str(request.user) + str(uuid.uuid4())
user_obj.save()
return HttpResponseRedirect(reverse('profile_app:profile'))
urls.py
urlpatterns = [
path('post-save/', views.postsaveview, name='post-save'),
]
base.html
<form action="{% url "post-save" %}" method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>

Updating profile pic of user but its not requesting user to upload the pic

I want to update the profile pic of the user in the database, But its not requesting the user to upload the pic, on clicking the upload button its simply redirecting me to the page.
models.py
from django.db import models
from django.contrib.auth.models import User
class userprofile(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import userprofile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = userprofile
fields = ['profilepic',]
views.py
#login_required
def profile(request):
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile)
if p_form.is_valid():
p_form.save()
return render(request,'profile.html')
else:
p_form = ProfileUpdateForm(instance=request.user.userprofile)
context = {
'p_form': p_form
}
return render(request,'profile.html',context)
profile.html
<form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" >
{% csrf_token %}
{{ p_form|crispy }}
<input style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload">
</form>
<img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}">
you forget to add the context when rendering
return render(request,'profile.html', context)

Django form not visible

Only the button is visible and headings are visible cannot see CharField
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
index.htm
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
You should give the if form.is_valid() part, one more tab.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
I'm not yet allowed to add comments to your question, but you did notice, that your view renders name.html while you're providing the code for index.htm.
Basically your code seems valid, while it can be further optimized:
def get_name(request):
form = NameForm(request.POST or None)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render(request, 'name.html', {'form': form})
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
This should work by adding editing {{form.as_p}}

working with forms in django

I want to write form and when submit it write "welcome!" in my page.But after I submit form method still is GET!!what's wrong?
this is my models:
from django.db import models
import django_tables2 as tables
from django import forms
class Form1(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
this is my view:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the previous section
form = Form1(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return render(request, 'student/Home.html',{'message':'welcome'})
else:
form = Form1() # An unbound form
return render(request, 'student/Home.html', {'form': form})
this is my template(Home.html):
<!DOCTYPE html>
<html>
<body>
<form action="{% url 'student:contact' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
<p>{{message}}<p>
</body>
</html>

Uploading csv file from url using django forms

So I am trying to upload and save a csv file to a variable via a POST to a url. I have looked through the django documentation on file uploads found here. I just don't understand the use of a form? What's the purpose in this situation?
They use an example with a form:
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Upload html:
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
<input id="file" type="file" name="test" />
<input id="signUpSubmit" type="submit" value="Submit">
</form>
models.py
from django.db import models
class Upload(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to="images")
forms.py
from django import forms
from app_name.models import Upload
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
views.py
def upload_file(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
upload.html
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
{% csrf_token %}
{{form.as_p}}
<input id="signUpSubmit" type="submit" value="Submit">
</form>

Categories