Reputation: 1943
I have an app that let you create a profile. One of my app feature is it's let you edit your name and upload a image.
The problem is the user cannot submit the image unless he type his name.How can I fix this page to make it so If the user submit an image but doesn't submit a name . He will still have his old name or if he doesn't submit an image and changes his name . He will still have his old picture?
I tried adding blank=True and null = False , null = True but doesn't seem to do the job
My models.py
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100,null=True,blank=False)
image = models.FileField(upload_to="images/")
def __unicode__(self):
return self.name
My forms.py
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('image','name',)
My views.py
def Display(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
if request.method == 'POST':
form = PersonForm(request.POST, request.FILES)
if form.is_valid():
person = Person.objects.get(user=request.user)
person.image = form.cleaned_data['image']
person.name = form.cleaned_data['name']
person.save()
return render(request,'edit.html',{'form': PersonForm()})
Upvotes: 1
Views: 121
Reputation: 379
django forms does validation on the users data
validation is done on two levels:
the field level:
clean_fieldname
form.field.errors
the form level:
clean
method form.non_field_errors
from your models:
image is not allowed to be blank which means it is required. not entering an image will raise an error
let blank=True for both name and image
also I recommend using form.save() over saving models from the views
also there is a built in ImageField for saving images
Upvotes: 1
Reputation: 22808
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100, blank=True)
image = models.FileField(upload_to="images/", blank=True)
def __unicode__(self):
return self.name
def Display(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
if request.method == 'POST':
form = PersonForm(request.POST, request.FILES)
if form.is_valid():
image = form.cleaned_data['image']
name = form.cleaned_data['name']
person = Person.objects.get(user=request.user)
if image:
person.image = form.cleaned_data['image']
if name:
person.name = form.cleaned_data['name']
person.save()
return render(request,'edit.html',{'form': PersonForm()})
Upvotes: 2