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'),
...
Related
I have a Django Form (ModelForm) which has a number of fields. When the user presses submit these are then saved to a database. What I am struggling to work out is, how do I then output/render these results in some other HTML page.
Models.py
from django.db import models
# Create your models here.
class Contract(models.Model):
name = models.CharField(max_length=200)
doorNo = models.SlugField(max_length=200)
Address = models.TextField(blank=True)
Forms.py
from django import forms
from contracts.models import Contract
class GenerateContract(forms.ModelForm):
class Meta():
model = Contract
fields = '__all__'
Views.py
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
At the moment, I am returning the 'Index' Home page of the app as a placeholder.
After validation, the form data is found in form.cleaned_data dictionary. So you can pass that back to the template and display it as you see fit.
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return render(request,'contracts/contracts.html',{'form_data': form.cleaned_data})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
If you want to show the form with the saved values, you can render the template with form and fill the instance input . like this:
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
saved_instance = form.save(commit=True)
return render(request,'contracts/contracts.html',{'form':GenerateContract(instance=saved_instance)})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
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())
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})
My goal is to let users upload files to user-specific folders.
The error I get is
no such column: notendur_document.user_id
Here is the relevant part of my views.py file. This is where the upload happens.
#login_required
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('notendur.views.list'))
else:
form = DocumentForm() # An empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'notendur/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
This is my models.py file:
def _upload_path(instance,filename):
return instance.get_upload_path(filename)
class Document(models.Model):
docfile = models.FileField(upload_to=_upload_path)
user = models.ForeignKey(User)
def get_upload_path(self,filename):
return "media/uploads/"+str(self.user.id) + "/" + '%Y.%m.%d' + filename
According to the relevant .html file, the error happens in the documents variable in list().
register user method in views.py:
def register_user(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('register.html', args)
Just pass pk=True in your foreingkey
ex. user = models.ForeignKey(User,pk=True)
this will solve the issue