local variable 'instance' referenced before assignment error - django

Now I've read all the posts on SO regarding this error, and I can conclude that my error is quite a different case.
The error:
Local variable 'instance' referenced before assignment
[21/Jun/2018 09:05:58] "POST /details/create/ HTTP/1.1" 400 54
Now here's the code where I initialize instance:
def create(request):
if request.method == "POST":
try:
params = post_data(request)
try:
instance = Sales_detail.objects.get(id = params.get("id",None))
params["item"] = instance.item.pk
params["price"] = instance.price.pk
params["sales"] = instance.sales.pk
detail_form = Detail_form(params, instance = instance)
except Sales_detail.DoesNotExist:
params["item"] = instance.item.pk
params["price"] = instance.price.pk
params["sales"] = instance.sales.pk
detail_form = Detail_form(params)
if detail_form.is_valid():
detail_form.save()
else:
raise_error(detail_form.errors,True)
return success("Details successfully saved.")
except Exception as e:
return error(e)
else:
return redirect("dashboard")
I have no idea what I'm missing, clearly instance is initialized before doing anything with it.

An error occurs when this line
instance = Sales_detail.objects.get(id = params.get("id",None))
is executed. The code isn't enecuted completely. So the instance hasn't been definited. And then the code goes to
params["item"] = instance.item.pk
Since the instance hasn't been definited, the Error
The error: Local variable 'instance' referenced before assignment
occurs.

Related

inserting a data in a formset passed by a form

hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser:
NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id
it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me
schedaName = schede_form.cleaned_data['nome_scheda']
scheda = schede_form.save(commit = False)
scheda.utente = request.user
scheda.save()
#gruppi
if gruppi_formset.is_valid():
for gruppi in gruppi_formset:
gruppi.save(commit = False)
gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
//print(gruppi.gruppi_scheda)
gruppi.save()
You have to assign the return value of gruppi.save(commit=False) into a variable and update the gruppi_scheda property there:
gruppi_instance = gruppi.save(commit=False)
gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
gruppi_instance.save()

Browser shows variable refered before assign

here is the image of error that i am getting in the browser
I am new to python and hardly tried to figure out the problem of usese of variable from another if statement in the same function
here is my code:
def post(self, request, **kwargs):
selected_membership_type = request.POST.get('membership_type')
user_membership = get_user_membership(request)
user_subscription = get_user_subscription(request)
selected_membership_qs = Membership.objects.filter(
membership_type=selected_membership_type)
if selected_membership_qs.exists():
selected_membership = selected_membership_qs.first()
'''
==========
VALIDATION
==========
'''
# selected_membership = selected_membership_qs.first()
if user_membership.membership == selected_membership:
if user_subscription == None:
messages.info(request,"You already have this membership.Your \
next payment is due {}".format('get this value from stripe'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
The problem is the following:
if selected_membership_qs.exists():
selected_membership = selected_membership_qs.first()
You are only assigning selected_membership if the if is True.
So in your case you are getting the Variable referenced before assignment error because the if is False.
Therefore selected_membership is never assigned.
If you do something like this
selected_membership = None
if selected_membership_qs.exists():
selected_membership = selected_membership_qs.first()
it should work.

UnboundLocalError: local variable 'team_members' referenced before assignment

I am getting the following error:
UnboundLocalError: local variable 'team_members' referenced before
assignment
Slug values in my model by default are 1.
This is the function:
def single_slug(request, single_slug):
team = [c.infraTeam_slug for c in infraTeam.objects.all()]
if single_slug in team:
team_members = TeamMember.objects.filter(infra_team__infraTeam_slug=single_slug)
series_urls = {}
for m in team_members.all():
part_one = vulnerability.objects.filter(member_name__member_name=m.member_name).earliest("vulnerabilty_date")
series_urls[m] = part_one.vulnerability_slug
return render(request=request,
template_name='main/category.html',
context={"member_name": team_members, "part_ones": series_urls})
Please help me to solve this problem.

Django 'int' object has no attribute 'status_code'

I start with def start method, it calls go_adder to add the num value 5 times in the adder.html until num equals 5. After that, the adder method should return ready=1
In views.py
def start(request):
num=0
ready_or_not=go_adder(num)
return HttpResponse("Ready: %s "%str(ready_or_not))
def go_adder(num):
ready=0
if num<5:
return render_to_response('adder.html',{'num':num})
elif num==5:
ready=1
return ready
def check_post(request,num):
if request.method == 'POST':
num+=1
return adder(num)
When I try to run this snippet code, it works until my "num=5", Then I get that error :
'int' object has no attribute 'status_code'
Exception Location: C:\Python27\lib\site-packages\django\middleware\common.py in process_response, line 94
and Traceback says:
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
response = middleware_method(request, response) ...
▶ Local vars
C:\Python27\lib\site-packages\django\middleware\common.py in process_response
if response.status_code == 404: ...
▶ Local vars
How can I fix that error ? Could you please help me ?
The django views need to return an HttpResponse object. You are doing that while num < 5, but then you return an int when num == 5:
def adder(num):
ready=0
if num<5:
num+=1
# This renders the template and returns and HttpResponse; good
return render_to_response('adder.html',{'num':num})
elif num==5:
ready=1
# DONT RETURN AN INT HERE. RETURN AN HttpResponse
return ready
If all you want for when num==5 is to return a plain text response of the number 1, then you can return an HttpResponse and set the content type:
elif num==5:
ready=1
return HttpResponse(str(ready), content_type="text/plain")
Update 1
Based on our conversation, you have suggested that you want the view to constantly pass along the count value no matter what, and that you are POST-ing the num value in the actual form. If the number is less than 5 it should return one kind of template, otherwise it should return another kind of template.
You can combine your two different views into one that will handle both the original GET request when the page is first loaded, and the POST request submitted by your form. Just make sure to point your form at that same page.
def check(request):
num = 0
if request.method == 'POST':
num = int(request.POST.get('num'))
return adder(num)
def adder(num):
if num < 5:
num += 1
tpl_name = 'adder.html'
else:
tpl_name = 'print.html'
return render_to_response(tpl_name, {'num':num})
check() is your single view.
adder() is the helper function that will add the value, check it, and return an HttpResponse object based on that value. You must always return this from your view to the client.
Both templates will be passed the context containing the value of num
Update 2
You said that you are actually passing in your num through the url and not through the POST form. Small adjustment to the last example. You don't even need an adder() anymore. You only need a single view.
Set your url to have an optional num pattern:
urls.py
(r'^checker/(?P<num>\d+)$', 'myapp.views.check')
views.py
def check(request, num=0):
num = int(num)
if num < 5:
num += 1
tpl_name = 'adder.html'
else:
tpl_name = 'print.html'
return render_to_response(tpl_name, {'num':num})
Your "checker" url now has an optional number. If it is not passed in the url, it will be a value of 0 in the view. If you send it as a POST request, it will add and return a different template.

coercing to Unicode: need string or buffer, NoneType found

I am making an Ajax request into views as follows:
def all_json_models(request):
data = {}
try:
isp = request.GET['status']
present_isp = Priority.objects.filter(ispname = isp)
isp_count = MultiWAN.objects.all()
# data['latest_no_rules'] = latest_no_rules
#data['present_isp'] = present_isp
data['isp_count'] = isp_count
return HttpResponse(simplejson.dumps(data))
my models.py is like
class MultiWAN(models.Model):
isp_name = models.CharField(max_length=10)
description = models.TextField(null=True)
ip_address = models.IPAddressField(null=True)
subnet = models.IPAddressField(null=True)
gateway = models.IPAddressField(null=True)
nameserver = models.ForeignKey('NameServer')
weight = models.IntegerField(null=False)
interface = models.CharField(max_length=5)
def __unicode__(self):
"""
This function is to return the values we required.
Arguments:
- `self`:
"""
# return u'%s ' % (self.isp_name)
class NameServer(models.Model):
""" A Isp can have more than one nameserver so far we are declearing a seperate table
"""
name = models.IPAddressField(null=False)
class Priority(models.Model):
priority = models.IntegerField(null = True)
ispname = models.ForeignKey('MultiWAN')
rule = models.CharField(max_length=5,null=False)
From = models.IPAddressField(null=True)
To = models.IPAddressField(null=True)
def __unicode__(self):
return u'%s ' % (self.priority)
while making request i am getting the error:
"coercing to Unicode: need string or buffer, NoneType found"
What i am doing wrong here?
It's hard to tell without the full traceback (because it gives information about where in you code the exception is thrown).
The error message "coercing to Unicode: need string or buffer, NoneType found" means that, at some point, django tried to convert something to unicode and expected a string, but received None. This means that either you call a function passing None instead of a string, or one of you methods returns None instead of a string.
In the code you showed us, MultiWAN.__unicode__ seems ill-defined. Maybe the error stems from this ?