Still getting validation error despite using save(commit=False) - django

Model form:
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'slug', 'category', 'description', 'thumbnail', 'status', 'author']
view:
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES)
if not request.user.is_superuser:
art = form.save(commit=False) # Error line
art.author = request.user
art.status = 'd'
art.save()
return HttpResponseRedirect(reverse('account:home'))
elif form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:home'))
return render(request, 'registration/add-update-article.html', {
'form': form
})
If the user is not a superuser, they can not fill some fields in the form so I want to set their values in this view. Isn't commit=False supposed to prevent raising validation errors? Why do I still get an error?

When you set the commit option to False, save() constructs the Model object, but does not save it to the database. It still preforms validation; see https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#the-save-method. You shouldn't try to suppress validation. Instead, figure out what's wrong with the form and set attributes to being not required, having a different maximum value, etc.
However, if what you want is to modify the form fields before saving, you can do this:
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES)
if not request.user.is_superuser:
Article.create(**form.cleaned_data, author=request.user, status="d")
return HttpResponseRedirect(reverse('account:home'))
elif form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:home'))
return render(request, 'registration/add-update-article.html', {
'form': form
})

Related

How to set value of a model form's readonly (disabled) field to its initialized value when the form is posted?

I'm creating a form for authors to write articles. The form contains an author and a status field. I want these two fields, allowed to be changed only if the user is a superuser. If they are not a superuser, it is initialized with their username as author and draft, as status. I managed to do that but when I submit the form, It is considered to be invalid and returns the form page with errors that say status and author fields are required and they are also not disabled anymore! Does Django ignore the values of read only fields in this case or... ? How can I fix it?
Model form:
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'slug', 'category', 'description', 'thumbnail', 'status', 'author']
view:
def add_update_article(request):
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:home'))
return render(request, 'registration/add-update-article.html', {
'form': form
})
else:
if not (request.user.is_author or request.user.is_superuser):
raise Http404
form = ArticleForm(initial={'author': request.user, 'status': 'd'})
if not request.user.is_superuser:
form.fields['author'].disabled = True
form.fields['status'].disabled = True
return render(request, 'registration/add-update-article.html', {
'form': form
})
Pass the initial values to the ArticleForm after POST request.
They are not disabled anymore because you are in the other branch of the if statement.
def add_update_article(request):
if not (request.user.is_author or request.user.is_superuser):
raise Http404
initial_fields = {'author': request.user, 'status': 'd'}
if request.method == 'POST':
form = ArticleForm(request.POST, request.FILES, initial=initial_fields)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:home'))
else:
form = ArticleForm(initial=initial_fields )
if not request.user.is_superuser:
form.fields['author'].disabled = True
form.fields['status'].disabled = True
return render(request, 'registration/add-update-article.html', {
'form': form
})

Django how to assign posts to user

I need to assign posts to user in Django. I created
user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)
and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :
def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
ogloszenie = form.save(commit=False)
ogloszenie.user = request.user
ogloszenie.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {
'form': form,}
return render(request, 'formularz.html', context)
Can i please know how to resolve it?
Rewrite the form to exclude the user field:
class DodajForm(forms.ModelForm):
class Meta:
model = Dodaj
exclude = ['user']
In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:
def formularz(request):
if request.method == 'POST':
form = DodajForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {'form': form}
return render(request, 'formularz.html', context)

I am trying to edit the Django database but this error keeps happening:The view social.views.edit didn't return an HttpResponse object

This is my code for my view:
def edit(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
else:
if form.is_valid():
user = form.save()
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
And here is the code for the form:
class EditProfileForm(UserChangeForm):
edit ='social/edit.html'
class Meta:
model = UserProfile
fields = ('description', 'image')
Here is the model:
class UserProfile(models.Model):
description = models.CharField(max_length=300, default=' ', blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
if you need any more information to help I would be more than gladly to give it to you
The problem is with the view function.
Every View must return some sort of response (HTTP Response in General)
you have an if else statement in your view if its a post it will just execute
form = EditProfileForm(request.POST, instance=request.user)
and then it doesn't return anything.
I think you have to do is,
For GET Request (when you visit the url, it has to render the form)
if request.method == 'GET':
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
For POST request (when you send POST to this view or different one)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
user = form.save()
# use render/redirect as needed. make sure it returns an HTTP Response
# note that render method also return HTTP Response
return HttpResponse('Done')
Make sure Form class is simply this
class EditProfileForm(UserChangeForm):
class Meta:
model = UserProfile
fields = ('description', 'image')

How to let the user to edit the custom user model details in the user dashboard and update it in the model in django?

I am having edit profile template and I wrote view for letting the user to edit the account but I am not getting the form even I wrote the url and view correctly can you please help me out how to let the user edit user model in the front end
my views.py:
def edit_profile(request):
if request.method == 'POST':
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('modsy:account'))
Forms.py:
class EditProfileForm(UserChangeForm):
template_name='edit_profile'
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'password'
)
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request,'edit_profile.html')
I am only getting the submit button in editprofile page but form is not coming can you please say what mistake I had did
You are handling only for POST request only but not for GET.Also here your form name is EditProfileForm not UserChangeForm so change your view like this:
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('modsy:account'))
else:
form = EditProfileForm()
return render(request,'Your_template',{'form':form})

Saved model is None

So i have a model that i'm trying to save using a form which submits successfully, but in the Admin the object value None. I know the problem is in the views but i can't figure it out. Here's my code:
Views.py
def profilecreate(request):
if request.method == 'GET':
form = ProfileForm()
else:
form = ProfileForm(request.POST)
if form.is_valid():
description = form.cleaned_data['description']
caption= form.cleaned_data['caption']
photo = form.cleaned_data['photo']
profile = Profile.objects.create(description=description, caption=caption, photo=photo)
return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id}))
return render(request, 'profile_form.html', {'form': form})
Someone please assist
Second view attempt
def profilecreate(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProfileForm(request.POST)
# check whether it's valid:
if form.is_valid():
photo = form.cleaned_data['photo']
description = form.cleaned_data['description']
caption = form.cleaned_data['caption']
form.save(commit=True)
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = ProfileForm()
return render(request, 'profile_form.html', {'form': form})