Im trying to get a form to validate with a Charfield but using the Select widget.
Here is my view.py code:
def mpld3plot(request):
form = PlotlyPlotForm()
form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False)
if request.method == 'POST':
print(form.is_valid())
if form.is_valid():
return HttpResponseRedirect('/mpld3')
else:
pass
else:
pass
return render(request, 'evert/plot.html', {'plottype': 'MPLD3',
'form': form})
Below is my forms.py code:
class Mpld3PlotForm(forms.Form):
plot_file = forms.CharField(widget=forms.Select(choices=[('', 'a'), ('', 'b')]))
The form does not validate on submit. I update the choices dynamically based on uploaded files. Any help would be appreciated.
Turns out I did not pass the request object to the form.
The view.py file should look like the following:
def mpld3plot(request):
form = PlotlyPlotForm(request.POST)
form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False)
if request.method == 'POST':
print(form.is_valid())
if form.is_valid():
return HttpResponseRedirect('/mpld3')
else:
pass
else:
pass
return render(request, 'evert/plot.html', {'plottype': 'MPLD3',
'form': form})
Related
This is my update views:
def EditDoctor(request,slug=None):
if request.method == "POST":
obj = get_object_or_404(Doctor,slug=slug)
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom()
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms.
You need to pass the instance to the form in case of a GET request as well:
def EditDoctor(request,slug=None):
obj = get_object_or_404(Doctor,slug=slug) # 🖘 fetch the object for both paths
if request.method == "POST":
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom(instance=obj) # 🖘 pass the instance to edit
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
I defined an initial value to my title field, but once I execute it, it shows no error and the initial value is not showing in my field how do I solve it? Thanks
def form_view(request):
if request.method == "POST":
initial_data = {
'title': 'default title'
}
form = ProductForm(request.POST, initial=initial_data)
if form.is_valid():
form.save()
form = ProductForm()
else:
form = ProductForm()
return render(request, "form.html", {"form": form})
You've put it in the wrong place. If you want it to show when the form is first rendered, you shouldn't put it in the POST block - which is called when the form is submitted - but the else block.
if request.method == 'POST':
form = ProductForm(request.POST)
...
else:
form = ProductForm(initial=initial_data)
In general, I make a page on the site. The meaning is this: a person comes in, loads an xml file, selects several parameters, and outputs the result. I did not find how to handle the xml file at once. So I upload its file with the parameters to the database, and then redirect us to the page with the result. Everything works fine, but there is a problem. I have not figured out how to create a unique link for the result each time. Now I have one link for the results and it just shows the last one ...
views.py of uploader
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index')
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
downloader
views.py of handler
def lessons_view(request):
a = keker()
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
keker if handler function
Try code like this (python 3.6):
# models.py
class Document(Model):
...
reference = CharField(max_length=128, db_index=True, null=False)
...
# forms.py
import secrets
...
class DocumentForm(ModelForm):
...
def save(self, commit=True):
self.instance.reference = secrets.token_hex(128)
return super().save(commit)
# views.py
...
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index', kwargs=dict(reference=form.instance.reference))
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
...
def lessons_view(request, reference):
a = keker(reference)
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
# urls.py
...
url(r'^/(?P<reference>\w+)/$', 'index', name='index'),
...
I want to redirtect page, after saving modelform. when i pushed save button, page redirecte, but no any things saved.
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args=[channelid]))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
This will get you closer to the solution. I'm not positive if you have 'updateChannelInfo' as the name in urls.py (so please double-check that). I think the complexity here is getting the correct channelId to be sent
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args = [self.object.id])))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
If you are willing to share your urls.py and forms.py files, this would help with getting the correct names into arguments
Another way I have had success with the dynamic direct after form submission is to use
def add_channel (request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channel.save()
return HttpResponseRedirect(reverse('channel_detail', args=[channel.id]))
else:
form = ChannelForm()
return render(request, 'channel_example.html', {'form': form})
Edit your view like this,
if form.is_valid():
form.save()
return redirect('updateChannelInfo', channelId=self.object.id)
In my previous question, I recently asked how to make forms.py in Django 1.9 show in HTML. now that this is done im trying to make a button which when the selection has been made (in this case it's radiobuttons) it will post to the database and move on with the questionaire.
Currently im attempting to make it post in my views.py but im having no luck in making it send the data.
def question1(request):
question_form = QuestionForm()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
return render(request, 'music.questions2,html')
return render(request, 'music/question1.html', locals())
Would really appreciate the help in making this happen.
def question1(request):
question_form = QuestionForm()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save() # save to db!
return render(request, 'music.questions2,html')
return render(request, 'music/question1.html', locals())
# models.py
class Question(models.Model):
# Q_CHOICES is the previous declared one
question = models.CharField(max_length=20, choices=Q_CHOICES)
# forms.py
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['question']
widgets = {
'question': forms.RadioSelect()
}
Use: form.save()
def question1(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'music.questions2,html')
else:
form = QuestionForm()
return render(request, 'music/question1.html', locals())