def Scan(request):
form = SubmitDomain(request.POST or None) # A form bound to the POST data
if request.method == 'POST': # If the form has been submitted...
if form.is_valid(): # If form input passes initial validation...
domainNmCleaned = form.cleaned_data['domainNm'] ## clean data in dictionary
form.save() #save cleaned data to the db from dictionary
try:
return HttpResponseRedirect('/Processscan/?domainNm=' + domainNmCleaned)
except:
raise ValidationError(('Invalid request'), code='invalid') ## [ TODO ]: add a custom error page here.
else:
form = SubmitDomain()
return render(request, 'VA/index.html', {
'form' : form
})
def Processscan(request):
EnteredDomain = request.get('domainNm', '')
return HttpResponse("We got to the processor with domain: " + EnteredDomain)
Please go easy on me - I'm still learning :)
I'm having an issue now with GET, when im using POST, on my initial request for a domain name - I'm getting:
'WSGIRequest' object has no attribute 'get'
on:
EnteredDomain = request.get('domainNm', '')
You could call scanprocess directly or simply just pass it by GET:
if form.is_valid(): # If form input passes initial validation...
domainNm = form.cleaned_data['domainNm'] ## clean data in dictionary
form.save() #save cleaned data to the db from dictionary
try:
return HttpResponseRedirect('/Scanprocess/?domainNm=' + domainNm)
except:
raise ValidationError(_('Invalid domain name'), code='invalid')
Then in your view you can just get it through request.GET.get('domainNm', '')
And so far as I know all you need is in the urls.py is:
url(r'^Scanprocess/$', name_of_view),
Related
OK im probably doing this all wrong!
I am trying to run a function in a view which calls another view.
This seems to pass my request into the next function as a POST method before loading the form from the second function.
my views.py
''' This section of hte code seems to function correctly '''
#login_required()
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = int(league.id) # displays id of model, JoinLeagueQueue
return HttpResponseRedirect(confirmLeague(request, context))
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
This section of the views file is not working correctly.
it seems to run the POST request without displaying the GET request with the form first.
#login_required()
def confirmLeague(request, league):
# gets ID of application to join league
joinleagueid=JoinLeagueQueue.objects.get(id=league)
pin = joinleagueid.pin # gets pin from application
user = joinleagueid.user # get user from application
leagueinquestion=League.objects.get(leaguePin=pin) # gets the league record for applied league
manager=leagueinquestion.leagueManager # Gets the league manager for league applied for
leaguename=leagueinquestion.leagueName # Gets the league name for league applied for
if request.method == 'POST':
if 'accept' in request.POST:
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = user,
)
return redirect('punterDashboard')# user homepage
else:
print("Error in POST request")
else:
context = {'leaguename':leaguename, 'pin':pin, 'manager':manager}
return render(request, 'userteams/confirmleague.html', context)
I now get an error saying Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/userteams/None
Using the URLconf defined in fanfoo_proj.urls, Django tried these URL patterns, in this order:
... im skipping a list of the patterns.
10. userteams/ confirmLeague [name='confirmLeague']
Ok i think the better way would be a HttpRedirect to the second view:
return confirmLeague(request, context)
should change to something like:
return redirect(confirmLeague,args=league)
django doc to urlresolvers: https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
def joinLeague(request):
if request.method == 'POST':
league = JoinLeagueQueue(user=request.user)
form = JoinLeagueForm(instance=league, data=request.POST)
if form.is_valid():
form.save()
context = league.id
return HttpResponseRedirect( reverse("your_confirmLeague_url",kwargs={'league':context}) )
else:
form = JoinLeagueForm()
context = {'form':form}
return render(request, 'userteams/joinleagueform.html', context)
def confirmLeague(request, league):
league = get_object_or_404(JoinLeagueQueue, pk=league)
pin = league.pin
if request.method == 'POST':
if 'accept' in request.POST: # This refers to the action from my form which is waiting for a button press in a html form.
LeaguesJoinedTo.objects.create(
leaguePin = pin,
playerjoined = request.user.id,
)
return redirect('punterDashboard')
else:
context = {'league':league}
return render(request, 'userteams/confirmleague.html', context)
I have a context_processor.py file with the following function
def include_user_create(request):
if 'form' not in request.session:
form = CreateUserForm()
else:
form = request.session['form']
return { 'create_user_form' : form }
I use this to display my register in my base.html template, so that I may reuse it for all pages. A function create_user handles the form submit
def create_user(request):
form = CreateUserForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(username=user.email, password=user.password)
else:
request.session['form'] = form #<--- save
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
If the form is invalid I'd like to save the form so that the context_processor may reuse the form, for the purpose of saving the errors so they may be displayed in the template.
Doing this gives me a error:
TypeError: <CreateUserForm bound=True, valid=False, fields=(email;password;confirm_password)> is not JSON serializable
Is it possible to get this to work somehow?
You have this error because a form object is not JSON serializable, and the default session serializer is serializers.JSONSerializer.
Try to change it to a pickle serializer in your settings.py:
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
EDIT:
With this setting, you don't have to care about pickle serialization, you just have to write:
request.session['form'] = form
when i use the id parameter from the url to edit a record, and the "elif 'id' in request.GET:" is being used, it doesn't update the record but it creates a new row
#login_required
def login_save_page(request):
if request.method == 'POST':
form = LoginSaveForm(request.POST)
if form.is_valid():
# Create or get login.
login1 = _login_save(request, form)
return HttpResponseRedirect(
'/user/%s/' % request.user.username
)
elif 'id' in request.GET:
id2 = request.GET['id']
name=''
url=''
Login_username =''
notes= ''
password=''
try:
login1 = login.objects.get(
id = id2,
username=request.user
)
name = login1.name
url = login1.loginUrl
Login_username = login1.login_username
notes = login1.notes
password = login1.password
except (login.DoesNotExist):
pass
form = LoginSaveForm({
'id': id2,
'name': name,
'url': url,
'Login_username': Login_username,
'notes': notes,
'password': password
})
else:
form = LoginSaveForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('login_save_page.html', variables)
I'm assuming your form is submitting via POST thus the elif "get" will never fire when you need it to (when the user submits the form).
You'll need to put that logic inside of the if request.method == 'POST' block.
Think about when that "elif" block will trigger. Only when the request method is not POST, which means only on page load.
I have created a form in my app where I can take details of a suer. Now I want to create a form which can allow me to edit a form.
My urls.py:
url(r'^home/editform/(?P<userpk>[^/]+)/$', 'lexuseditform', name='lexuseditform'),)
My view.py:
#login_required
def lexuseditform(request,userpk):
if int(userpk) != request.user.pk:
return HttpResponseForbidden()
else:
form = AdultForm()
if request.method == 'POST': # If the form has been submitted...
form = AdultForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
redirect_url = reverse('lexus/lexusedited.html')
return HttpResponseRedirect(redirect_url) # Redirect after POST
else:
form = AdultForm() # An unbound form
return render('lexus/lexuseditform.html', {'form': form})
My models.py:
class AdultForm(ModelForm):
"""
Edit Profile Information
"""
class Meta:
model = Adult
fields = ('user', 'email','fullname','created')
But i am getting an error msg:
No ReverseMatch: Reverse for 'lexuseditform' with arguments '()' and keyword arguments '{}' not found
Can't seem to solve this error. Need some help...
In you POST handling, reverse should be passed URL name not the pattern. So correct it whatever name you have given to that url.
redirect_url = reverse('lexus/lexusedited.html') <----- Incorrect.
If your urlname is 'lexusedited'
redirect_url = reverse('lexusedited')
Tip: you can directly do:
return HttpResponseRedirect(reverse('lexusedited'))
I have a form which contains an imagefield and some other fields.
my view looks like this:
def post_view(request):
def errorHandle(errors,form):
return render_to_response('post_form.html', {
'errors':errors,
'form' : form,
},context_instance=RequestContext(request))
if request.method == 'POST': # If the form has been submitted...
form = PostForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
#save
else:
errors = form.errors
return errorHandle(errors,form)
else:
form = PostForm() # An unbound form
sucess = ''
return render_to_response('post_form.html', {
'form': form,
}, context_instance=RequestContext(request))
When errorHandle is called, it returns to the page with the form, errors and the values entered except for the value entered on an ImageField.
tell me if you need to look at my form and model. thanks in advance.
I think it's normal.
Path of a client image is secure for a backend, so, it was not sent. It's an official HTTP feature.