I have this view:
#login_required
def newAnswer(request, id):
post = Post.objects.get(id=id)
form = AnswerForm(request.POST)
if request.method == 'POST':
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.post = post
obj.save()
form.save_m2m()
return redirect('main:post', id=post.id)
else:
return render(request, 'main/newAnswer.html', { 'form': form, 'formErrors': form.errors, 'userAvatar': getAvatar(request.user)})
else:
return render(request, 'main/newAnswer.html', {'form': form, 'post': post, 'userAvatar': getAvatar(request.user)})
When i try to post without loging in, it redirects me to "/accounts/login?next=/post/answer/new/81".
My question is how can i get the "next" param in my login view
thanks!
Everything arguments (params) you can see in url mean that request is done with GET method. Use request.GET.get('next', None).
Related
I have default Django registration form. It is sent to render to the page based on type of request and user login status. This logic is implemented in views.py file. Somehow, if user is not logged in and GET request is sent to the page, my view returns UnboundLocalError: local variable 'form' is referenced before assignment. How could this happen?
P.S. Here's my view.
def EmplRegisterView(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
else:
if request.user.is_authenticated:
logout(request)
form = UserCreationForm()
else:
form = UserCreationForm()
context = {
'form':form,
}
return render(request, "registerPage.html", context)
Try this way
def EmplRegisterView(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
group = Group.objects.get(name = 'Employers')
user.groups.add(group)
login(request, user)
return redirect('ProfileSetup')
if request.user.is_authenticated:
logout(request)
context = {
'form':form,
}
return render(request, "registerPage.html", context)
In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist".
This is what I'm trying (I've commented the code in view2 to indicate where im getting the error).
views.py
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('view2')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
...
reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id
Something like this:
from django.urls import reverse
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
obj = form.save()
reference_id = request.POST.get('reference') or obj.reference.id
return redirect(reverse('view2')+f'?reference={reference_id}')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
...
data = getattr(request, 'POST', None) or getattr(request, 'GET', {})
reference_id = data.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
I'm trying to validate a form from backend itself. I've made a dictionary of error message:
error_messages = {
'error': form.errors,
}
and passed it to HttpResponse:
return HttpResponse(json.dumps(error_messages))
i want to show the error message when the form is invalid.
This is my updaterow view:
def updaterow(request, id):
item = get_object_or_404(Studentapp, id=id)
if request.method == "POST":
form = EntryForm(request.POST, instance=item)
error_messages = {
'error': form.errors,
}
if form.is_valid():
post = form.save(commit=False)
post.save()
return HttpResponse(json.dumps(error_messages))
else:
form = EntryForm()
return HttpResponseRedirect(reverse('studentapp:index'), id)
return render(request, 'index.html',{'form':form})
I have to make changes in else part also so kindly help me with that too.
You have your code the wrong way around. If the form is valid there are no error messages.
if form.is_valid():
post = form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('studentapp:index'), id)
else:
form = EntryForm()
return HttpResponse(json.dumps(error_messages))
Note that if you are making an ajax request, then your JavaScript will have to check the status code for the redirect response and take the appropriate action.
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)
I use django-nocaptcha-recaptcha and followed the exact steps in the documantation: https://github.com/ImaginaryLandscape/django-nocaptcha-recaptcha
This is my view:
def home(request):
if request.method == 'POST':
form = PostForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return HttpResponseRedirect(reverse(view, args=(save_it.pk,)))
else:
form = PostForm(request.POST or None)
return render(request, "home.html", locals())
I get this error message when I submit the form and the recaptcha remains unchecked:
The view posts.views.home didn't return an HttpResponse object. It returned None instead.
I hope there is no necessary information that I forgot. Any help would be appreciated
You don't return a response when your form.is_valid() is False.
Try adding this:
def home(request):
if request.method == 'POST':
form = PostForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return HttpResponseRedirect(reverse(view, args=(save_it.pk,)))
else:
return render(request, "home.html", locals()) # new line
else:
form = PostForm(request.POST or None)
return render(request, "home.html", locals())
Right after I clicked send the solution occurred to me. I just needed to return the render of home.html in case the form is not valid. Sorry for the unnecessary post!