I'm doing something wrong here, but I can't find it.
I'm using a model form:
class ArtistInfo(ModelForm):
class Meta:
model = Onesheet
fields = (
'name',
'genre',
'location',
'biography',
)
And trying to save the data entered for an existing record.
def edit_artist_info(request, onesheet):
onesheet = Onesheet.objects.get(id = onesheet)
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
test = form.save(commit=False)
test.save()
HttpResponseRedirect('/')
form = ArtistInfo(instance=onesheet, label_suffix='')
variables = RequestContext(request, {
'onesheet':onesheet,
'form': form,
})
return render_to_response('edit_artist_info.html', variables)
But it's not saving. It just reloads the page with whatever the user changed, but if you actually refresh the page (grabbing the value from the DB), it's the old value.
Any ideas? If it's because the form isn't actually validating, I dont know why it's not validating.
try just
if request.method == 'POST':
form = ArtistInfo(request.POST, instance=onesheet)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
You were missing the return statement in your code, and the extra save() was unnecessary
Related
In my Django project, I have this view:
def create_format(request, **kwargs):
if request.method == 'POST':
form = FormatUpdateForm(request.POST)
if form.is_valid():
business_type = int(request.POST.get('business_type'))
... more fields ...
constitutive_act_copy = clean_str(request.POST.get('constitutive_act_copy'))
return HttpResponseRedirect(reverse('formats:formats'))
elif request.method == 'GET':
form = FormatUpdateForm()
return render(request, 'format_form.html', context={'form': form, 'autocomplete': SearchableData.objects.all()})
I have many fields, some of which are FileFields. I want to create an object with the data obtained from the form, and I can do that for all fields except the FileFields. What is the correct way to obtain the Files uploaded in the form and use them as attributes when creating an object?
I've a problem with my formset. When I submit the formset, the models are not saved and displayed as None. I don't understand why, can somebody light me ?
There is no problem in the template nor the urls.py. I get this within my log console:
See image
Here is my code:
// views.py
def classroom_call_the_roll(request, class_id):
classroom = Classroom.objects.get(pk=class_id)
students = classroom.students.all()
queryset = Attendance.objects.none()
AttendanceFormset = modelformset_factory(
model=Attendance,
form=AttendanceForm,
can_delete=False,
extra=len(students)
)
if request.method == 'POST':
formset = AttendanceFormset(
request.POST,
queryset=queryset,
initial=[{'student': student} for student in students]
)
for form in formset.forms:
instance = form.save(commit=False)
print(instance)
else:
formset = AttendanceFormset(
queryset=queryset,
initial=[{'student': student} for student in students]
)
return render(
request,
'highschool/attendance/classroom_attendance_create.html',
{
'formset': formset
}
)
i see you have set commit=False in form.save call. If you do this, you have to save the instance yourself by calling
instance.save()
You should save the model manually. To do that, you should add instance.save()
i stuck when trying to send data or save data with django form by user it self (logged).
When i test why form "From" user must be selectable not automatic selected by user it self.
class ValidationCreate(forms.ModelForm):
class Meta:
model = About
fields = '__all__'
def upload(request):
upload = ValidationCreate()
if request.method == 'POST':
upload = ValidationCreate(request.POST, request.FILES)
if upload.is_valid():
upload.save()
return redirect('validation')
else:
return HttpResponse("""your form is wrong, reload on reload""")
else:
return render(request, 'upload_form.html', {'about_form': upload})
sample
this way you can assign the request.user
if upload.is_valid():
instance = upload.save(commit=False)
instance.profile = Profile.objects.get(user=request.user) # you can change the user if field name is different
instance.save()
return redirect('validation')
else:
in forms
fields = ['field_1', 'field_2',] # except user field
I am trying to use a ModelForm to save a model.
forms.py
class PurchaseForm(forms.ModelForm):
weight = forms.IntegerField()
class Meta:
model = Purchase
fields = ["number", "pieces"]
views.py
if request.method == "POST":
form = PurchaseForm(request.POST)
if form.is_valid():
purchase = form.save(commit=False)
purchase.contract = Contract.objects.get(number=slug)
weight = form.cleaned_data.get('weight')
if check_weight(weight, purchase.contract):
weight_type = purchase.contract.supplier.market.weights
purchase.lbs, purchase.kgs = generate_weights(weight, weight_type)
purchase.save()
In the view above, I need to prevent the model from saving if the check_weight function returns False.
This function requires some data from the related object. I'm having some trouble figuring this out. What should I do?
If I'm understood your question correctly, this would work,
from django.http import HttpResponse
def my_form_view(request):
if request.method == "POST":
form = PurchaseForm(request.POST)
if form.is_valid():
purchase = form.save(commit=False)
purchase.contract = Contract.objects.get(number=slug)
weight = form.cleaned_data.get('weight')
if check_weight(weight, purchase.contract):
weight_type = purchase.contract.supplier.market.weights
purchase.lbs, purchase.kgs = generate_weights(weight, weight_type)
purchase.save()
return HttpResponse("save success")
return HttpResponse("'check_weight' returned False")
else: # if a GET (or any other method) we'll create a blank form
form = PurchaseForm()
return render(request, 'some_html_template.html', {'form': form})
I have this error:
appname_mymodel.user_id may not be NULL
def form_view(request):
user = request.user
f_form = FForm(request.POST or None, request.FILES or None)
if request.method == "POST":
if f_form.is_valid():
f_form.user = user
f_form.save()
return HttpResponseRedirect('/thanks/')
return render_to_response('upload.html', {'f_form': f_form}, context_instance=RequestContext(request))
forms.py:
class FForm(ModelForm):
class Meta:
model = MyModel
exclude =['user']
How to save current login user?
The form doesn't have a user attribute so it is useless to assign to it. What you should do instead is:
if f_form.is_valid():
my_model = f_form.save(commit=False)
my_model.user = user
my_model.save()
This way the form will construct a MyModel instance, but will not attempt to save it to the database. Then you can fill the user field and save it.
You can also provide the necessary data as an instance argument:
f_form = FForm(request.POST or None, request.FILES or None, \
instance = MyModel(user=user))
if request.method == "POST":
if f_form.is_valid():
f_form.save()
return HttpResponseRedirect('/thanks/')