Django: ModelForms: ImageField is always empty and rejected by ModelForm - python

I created a form based on several ModelForm elements. All fields work fine excluding the
ImageField. Due to the missing ImageField form.is_valid() always returns False - even though I pass request.FILES to form.
Why the form with the ImageField is always invalid / empty?
Forms
class UserProfileForm2(forms.ModelForm):
class Meta:
model = models.UserProfile
fields = ['description', 'picture']
class LocationForm(forms.ModelForm):
class Meta:
model = models.Location
fields = ['city', 'state', 'country']
class UserForm(forms.ModelForm):
class Meta:
model = registration_models.User
fields = ['first_name', 'last_name']
Models
class Location(models.Model):
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __unicode__(self):
return ' - '.join([self.city, self.state, self.country])
class UserProfile(models.Model):
authenticationuser = fields.AutoOneToOneField(AuthUser)
description = models.TextField()
picture = models.ImageField(upload_to='uploaded_files/', null=True)
location = models.ForeignKey(Location, null=True)
appear_in_public_ranking = models.BooleanField(default=True)
def __unicode__(self):
return self.authenticationuser.username
View
#login_required
def changeprofile(request):
form = None
# user posted his new profile settings
if request.method == 'POST':
user_form = myforms.UserForm(request.POST)
user_profile_form = myforms.UserProfileForm2(request.POST, request.FILES)
location_form = myforms.LocationForm(request.POST)
forms_are_invalid = not (user_form.is_valid() and user_profile_form.is_valid() and not location_form.is_valid())
if forms_are_invalid:
forms = {'user_form':user_form,
'user_profile_form':user_profile_form,
'location_form':location_form}
return shortcuts.render(request, 'changeprofile.html', forms)
location_form.save()
user_form.save()
user_profile_form.save()
return HttpResponseRedirect('/profile')
else:
forms = {'user_form':user_form,
'user_profile_form':user_profile_form,
'location_form':location_form}
return shortcuts.render(request, 'changeprofile.html', forms)
Template
<form action="{% url 'changeprofile' %}" method="post">
{% csrf_token %}
{{ user_form }}
{{ location_form }}
{{ user_profile_form }}
<input type="submit" value="Submit" />
</form>

If your form contains file input then you must set enctype in your form as:
<form action="{% url 'changeprofile' %}" method="post" enctype="multipart/form-data">
Otherwise request.FILES will always be empty.

Related

Form is not saving in database when submitted

I am working on a project on Django, where user can input values on form and submit using POST request. When form is submitted, datas are not saved in database. How do I implement save data when form is submitted.
Models:
class DataInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
beneficiary_name = models.CharField(max_length=250, blank=True)
beneficiary_bank_name = models.CharField(max_length=250, blank=True)
beneficiary_account_no = models.CharField(max_length=250, blank=True)
beneficiary_iban = models.CharField(max_length=250, blank=True)
beneficiary_routing_no = models.CharField(max_length=250, blank=True)
amount = models.IntegerField(blank=True)
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'DataInfo'
verbose_name_plural = 'DataInfo'
ordering = ['-date']
'''Method to filter database results'''
def __str__(self):
return self.user.username
Views:
#login_required
def TransferView(request):
form = DataForm(request.POST)
if request.method == "POST":
if form.is_valid():
pp = form.save(commit=False)
pp.user = request.user
pp.save()
return redirect('site:transfer_cot')
else:
form = DataForm()
context = {
'form':form
}
return render(request, 'transfer.html', context)
Forms:
class DataForm(forms.ModelForm):
class Meta:
model = DataInfo
fields = ('beneficiary_name', 'beneficiary_bank_name', 'beneficiary_account_no', 'beneficiary_iban', 'beneficiary_routing_no', 'amount')
Template:
<form method="POST" action="{% url 'site:transfer_cot' %}">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-secondary">Submit</button>
</form>

FOREIGN KEY constraint failed , django

I have to insert the post through a form but when i submit i got this error FOREIGN KEY constraint failed, the problem is with the author field
models.py
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=120)
author = models.ForeignKey('auth.User',related_name='blog_posts',on_delete=models.CASCADE,blank=True, null=True)
body = RichTextField()
created = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
tag = models.OneToOneField(Tag,related_name="blog_tag",on_delete=models.CASCADE,default=0)
def __str__(self):
return self.title
views.py
def tagView(request,name):
tag = Tag.objects.get(name=name)
post_form = PostForm(request.POST or None)
if request.method == 'POST':
post_form = PostForm(request.POST)
if post_form.is_valid():
item = post_form.save(commit=False)
item.author = request.user
item.save()
return HttpResponseRedirect(request.path_info)
context = {
'post_form' : post_form,
'tag' : tag,
}
return render(request,'blog/tagPage.html',context)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','body']
template
<form class="post-form" method="POST" enctype="multipart/form-data" action="">
{% csrf_token %}
{{ post_form }}
<input class="post-form-submit submit" type="submit" value="Save">
</form>
If the author field is the problem, be sure to import auth.User
My guess is that you are trying to add the post as anonymous but anonymous user is not null (id is though). Also don't use 'auth.User' and follow the instructions from the documentation.

Update only ForeignKey field in Django form

I try to update a ForeignKey field of a model in django form. I want a user not to write his name into a input field as an author of the article that he wrote but his idmust be saved in the field in Article model. In my html-form I display only a button with hidden input. But in my views.py I write that the form should take user.id and put it in the 'article_author' field.
Unfortunately, I've got no updates into table. What am I doing wrong?
my model:
class Article(models.Model):
article_pub_date = models.DateField(default=None,null=True,verbose_name="Дата публикации")
article_title = models.CharField(max_length=70, verbose_name="Заголовок", null=True)
article_text = models.TextField(verbose_name="Текст", null=True)
article_author = models.ForeignKey(User, verbose_name='Автор', blank=True, null=True)
my views.py
def article_detail(request, article_id):
user = request.user
article = get_object_or_404(Article, pk=article_id)
author_form = ArticleForm(request.POST or None, instance=article, initial={'article_author': user.id})
if author_form.is_valid():
author_form.save()
else:
return redirect('/')
my forms.py
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ('article_author',)
widgets = {'article_author': forms.HiddenInput()}
and my template:
<form method="POST" action="">
{% csrf_token %}
{{ author_form.as_p }}
<input type="submit" value="BIND" class="btn">
</form>
Try one of the following:
if author_form.is_valid():
article = author_form.save(commit=False)
article.article_author = user
# article.article_author_id = user.id #w ill work as well
article.save()
else:
return redirect('/')
or in the form instantiation:
initial={'article_author_id': user.id}

null value in column violates not-null constraint while saving ModelForm

I have a model which extends the User model of django like this:
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name="user details")
rewardpoints = models.IntegerField("rewardpoints")
def __str__(self):
return "%s's profile" % self.user.username
my forms.py
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['rewardpoints']
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
my view.py
class UserProfileFormView(View):
def post(self, request, *args, **kwargs):
userform = UserForm(request.POST, prefix='users')
userprofileform = UserProfileForm(request.POST, prefix='userprofiles')
if userform.is_valid() and userprofileform.is_valid():
new_user = userform.save() #### Error over here.
new_userprofile = userprofileform.save(commit=False)
new_userprofile.user = new_user
new_userprofile.save()
return HttpResponseRedirect(reverse('users:welcome'))
else:
userform = UserForm(prefix='users')
userprofileform = UserProfileForm(prefix='userprofiles')
return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
def get(self, request, *args, **kwargs):
userform = UserForm(prefix='users')
userprofileform = UserProfileForm(prefix='userprofiles')
return render(request, 'users/signup.html', {'user_form': userform, 'userprofile_form': userprofileform})
my signup.html
<p> Hello Signup!! </p>
<form action="{% url 'users:signup' %}" method="post">
{% csrf_token %}
{{ user_form.username.label_tag }}
{{ user_form.username }}
{{ user_form.password.label_tag }}
{{ user_form.password }}
{{ userprofile_form }}
<input type="submit" value="Submit" />
</form>
</html>
But while making the post request, there is this error: null value in column "rewardpoints" violates not-null constraint
Please show me a way out of this.
The error is because your field rewardpoints needs some value, it can't be null, so, or pass a value to rewardpoint through your form or you can set a default value to it(Recommended). Then when you create a userprofile, form will set 0 as initial value.
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name="user details")
rewardpoints = models.IntegerField(default=0)

django image upload forms

I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files
my models
class UserProfile(User):
"""user with app settings. """
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
fbCom = models.BooleanField()
objects = UserManager()
#def __unicode__(self):
# return '%s %s ' % (User.Username, User.is_staff)
def get_absolute_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
...
class reports(models.Model):
repID = models.AutoField(primary_key=True)
repSubject = models.CharField(max_length=100)
repRecepients = models.ManyToManyField(UserProfile)
repPoster = models.ForeignKey(UserProfile,related_name='repposter')
repDescription = models.TextField()
repPubAccess = models.BooleanField()
repDate = models.DateField()
report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' )
deleted = models.BooleanField()
def __unicode__(self):
return u'%s ' % (self.repSubject)
my forms
from django import forms
from django.http import HttpResponse
from cms.models import *
from django.contrib.sessions.models import Session
from django.forms.extras.widgets import SelectDateWidget
class UserProfileForm(forms.ModelForm):
class Meta:
model= UserProfile
exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups')
...
class reportsForm(forms.ModelForm):
repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here')
repDate = forms.DateField(widget=SelectDateWidget())
class Meta:
model = reports
exclude = ('deleted')
my views
#login_required
def reports_media(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
if request.user.is_staff== True:
repmedform = reportsForm(request.POST, request.FILES)
if repmedform.is_valid():
repmedform.save()
repmedform = reportsForm(initial = {'repPoster':user.id,})
else:
repmedform = reportsForm(initial = {'repPoster':user.id,})
return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()})
else:
return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()})
...
#login_required
def settingchng(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
form = UserProfileForm(instance = user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance = user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/settings/')
else:
form = UserProfileForm(instance = user)
if request.user.is_staff== True:
return render_to_response('staffsettingschange.html', {'form': form})
else:
return render_to_response('settingschange.html', {'form': form})
...
#login_required
def useradd(request):
if request.method == 'POST':
form = UserAddForm(request.POST,request.FILES )
if form.is_valid():
password = request.POST['password']
request.POST['password'] = set_password(password)
form.save()
else:
form = UserAddForm()
return render_to_response('staffadduser.html', {'form':form})
Example of my templates
{% if form.errors %}
<ol>
{% for field in form %}
<H3 class="title">
<p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p>
</H3>
{% endfor %}
</ol>
{% endif %}
<form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
{{ repfrm.as_p }}
<input type="submit" value="Submit" />
</form>
the issue was actually that this line
<form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
appeared as
<form method="post" id="form" action="" enctype="multipart/form
-data" class="infotabs accfrm">
hence the forms were not uploading. And to think I have had this issue for 2 weeks. If its ok with you guys, i will delete this question.

Categories