local variable 'context' referenced before assignment - django

I need get data from my form and treat them
def parsurl(request):
if request.method == 'POST':
form = DomainForm(request.POST)
context = { 'form': form, }
if form.is_valid():
r = form.cleaned_data.get('url_text')
masall =parser_d(r)
for mas1 in masall:
try:
Events.objects.create(events_title=mas1[1], events_text = mas1[2],events_img = mas1[0], events_is_pars=1, events_seourl = "132")
except:
print ("lololo")
else:
form = DomainForm()
return render_to_response(request, 'form.html', context)
Exception Value:
local variable 'context' referenced before assignment

You have defined context in the if request.method == 'POST' branch, but not in the else branch. Therefore you get an error for GET requests.
You could fix it by moving the line outside of the if statement as follows:
if request.method == 'POST':
...
else:
...
context = {'form': form}

Related

Form values are not overwritten when changed - they are stuck at their default values

I have the following view:
#login_required
def my_view(request):
instance = my_model(user=request.user)
form = my_model_form(request.POST,instance = instance)
if request.method == "POST":
if form.is_valid():
form.save(commit=False)
#Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
form.field3 = df["field3"]
form.field4 = df["field4"]
form.field5= df["field5"]
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
"form":form
}
return render(request, "discounttracker/my_html.html",context=context)
and the problem is that field3,field4,field5 are not changed. I have even tried to hard-code them to 1000, 2000,3000 (they are FloatField(default=0)) but they remain at their default value when written to the DB.
What am I doing wrong here?
You are setting the attributes of the form, not of the instance wrapped in the form. You should alter this to:
#login_required
def my_view(request):
instance = my_model(user=request.user)
if request.method == 'POST':
form = my_model_form(request.POST, instance = instance)
if form.is_valid():
# Field1 and field2 is already in the form (its the input)
# Do some back-end operations to get values for the remaining fields
df = some_util_function()
# ↓ the instance of the form
form.instance.field3 = df['field3']
form.instance.field4 = df['field4']
form.instance.field5 = df['field5']
form.save()
return redirect("my_html")
else:
form = my_model_form()
context = {
'form': form
}
return render(request, 'discounttracker/my_html.html', context=context)

Edit an object based on an attribute's value in Django

I have a view called Edit, that edits an object. I want the user to only be able to edit it if it's unlocked, meaning, an attribute is called locked = BooleanField() and in the view, you first check whether the object is locked or not before proceeding.
This is the edit function so far:
#login_required
def editdossier(request, pk):
dossier = get_object_or_404(Dossier, id=pk)
form = AddDossierForm(request.POST or None, instance = dossier)
context = {'form': form}
if form.is_valid():
dossier = form.save(commit= False)
dossier.save()
context = {
'form': form,
'dossiers': Dossier.objects.all()
}
return render(request, 'dashboard/home.html', context)
else:
context= {'form': form}
return render(request,'dashboard/modifier_dossier.html' , context)
And this is what I want to do:
#login_required
def editdossier(request, pk):
dossier = get_object_or_404(Dossier, id=pk)
# CHECK IF DOSSIER.LOCKED == FALSE:
form = AddDossierForm(request.POST or None, instance = dossier)
context = {'form': form}
if form.is_valid():
dossier = form.save(commit= False)
dossier.save()
context = {
'form': form,
'dossiers': Dossier.objects.all()
}
return render(request, 'dashboard/home.html', context)
else:
context= {'form': form}
return render(request,'dashboard/modifier_dossier.html' , context)
I did the following check:
if dossier.locked == false:
proceed
but the condition is not checked. I tried if dossier[0].locked == false but it shows an error saying the object is not indexable.

I'm getting error "local variable 'form1' referenced before assignment"

I'm getting an error
local variable 'form1' referenced before assignment
This is my views.py and I'm unable to figure this out. I am new to Django so can anyone help me with providing a solution and explaining what I am doing wrong.
def getview(request):
formObject = form_input()
formObject.orign = None
formObject.destinations = None
formObject.timeWindow = None
if request.method == 'POST':
formData = ro_input_form(request.POST)
if formData.is_valid():
formObject.orign = request.POST.get('orign')
formObject.destinations = request.POST.get('destinations')
formObject.timeWindow = request.POST.get('timeWindow')
formObject.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
This is my models.py:
class form_input(models.Model):
orign = models.TextField(max_length=245,null=True,default='No data')
destinations = models.TextField(max_length=255,null=True,default='No data')
timeWindow = models.DateField(max_length=255,null=True,default='No data')
This is my forms.py
class ro_input_form(forms.ModelForm):
class Meta:
model = form_input
fields = ['orign',
'destinations',
'timeWindow',
]
The problem is that you have passed the form as form1 as a context in your line:
return render(request, 'inputform.html', {'form1': form1})
But missed to declare the form with name form1 inside your if request.method == 'POST': block. The solution can be either replace:
formData = ro_input_form(request.POST)
as
form1 = ro_input_form(request.POST)
and other places where formData is specified.
Else replace:
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
As:
else:
formData = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': formData})
This causes consistency in the form names.
Edit: Trying to fix data not being saved error.
views.py
def getview(request):
if request.method == 'POST':
form1 = ro_input_form(request.POST)
if form1.is_valid():
form1.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})
Recommendation:
As you are using all the fields of your model while declaring the form ro_input_form, you can just declare the fields in your form as:
fields = '__all__'
instead of
fields = ['orign',
'destinations',
'timeWindow',
]
This is just for easiness. But if you want only specific fields then specifying the fields individually is fine.
you are passing the form1 in html while it's not declared before so you have to declare it before.
You might like to declare form1 at the starting of view and change your form name as form1:
def getview(request):
formObject = form_input()
formObject.orign = None
formObject.destinations = None
formObject.timeWindow = None
form1 = ro_input_form(request.POST)
if request.method == 'POST':
form1 = ro_input_form(request.POST)
if form1.is_valid():
form1.save()
return HttpResponse(status=200)
else:
form1 = ro_input_form() ## this should be forminput
return render(request, 'inputform.html', {'form1': form1})

Django didn't return an HttpResponse object

I made a simple pet store app and just added search box feature and I received this error
ValueError at /pet/search/
The view mysite.pet.views.search_page didn't return an HttpResponse object.
I tried to change render_to_response into HttpResponseRedirect but still got the same error.
Linking back to my search_page function in views.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
I did some research and I understand a view has to return a HttpResponse when a HttpRequest is made and render_to_response is just a shortcut.Can someone help explain why this function won't work.Thank you
You are getting this problem because you havn't written a HttpResponse object if request type is not POST
To overcome this in your view write somthing which will process if request type is not post
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
Hope this will help you thanks
The error is because when the function is called the method type is not POST and it does not find the corresponding HttpResponse object.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
return render_to_response("any.html",{} , context_instance = RequestContext(request))
def addsponser(request):
if request.method == 'POST':
# return HttpResponse(request,'error is here')
if (request.POST.get('firstname') and
request.POST.get('lastname') and
request.POST.get(' email') and
request.POST.get('phone_Number') and
request.POST.get('gender') and
request.POST.get('state') and
request.POST.get('adress') and
request.POST.get('postal_code') and
request.POST.get('town')
):
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
em = request.POST.get(' email')
phn = request.POST.get('phone_Number')
gnd = request.POST.get('gender')
stt = request.POST.get('state')
add = request.POST.get('adress')
pstc = request.POST.get('postal_code')
twn = request.POST.get('town')
try:
sponser = Sponsers()
sponser.firstname = fname
sponser.lastname = lname
sponser.email = em
sponser.Phone_Number = phn
sponser.gender = gnd
sponser.state = stt
sponser.adress = add
sponser.postal_code = pstc
sponser.town = twn
sponser.save()
messages.success(request, "sponser Added")
return redirect('sponsers')
except Exception:
messages.error(request, "Failed to add sponser")
return redirect('sponsers')
else:
pass
else:
return redirect('sponsers')

Why my code does not show validation form error message?

Why my code does not show validation form error message?
I try something like this:
def index(request):
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
form = AngebotForm()
else:
form = MessageForm(request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
else:
form = MessageForm()
return render_to_response('index.html',{'a_form':AngebotForm(), 'm_form':MessageForm()},context_instance=RequestContext(request))
What am I doing wrong?
Because in else part you are re-initializing the form which will loose the current state of form.
Just remove these lines:
else:
form = MessageForm()
In the end your view should look like this:
def index(request):
form = AngebotForm()
m_form = MessageForm()
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
m_form = MessageForm(request.POST)
if m_form.is_valid():
m_form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
return render_to_response('index.html',{'a_form':form, 'm_form':m_form},context_instance=RequestContext(request))