Below is my code, which receiving an error
'QuerySet' object has no attribute 'zipCode'
def feeds_view(request):
profile = Profile.objects.filter(id=request.COOKIES['id'])
zipCode = profile.zipCode
when changing code to below receiving
'UserRegistration' object is not iterable:
def feeds_view(request):
user = Profile.objects.get(id=request.COOKIES['id'])
zipCode = user.zipCode
content = {
'user': user
}
return render(request, 'pages/feeds.html', content)
HTML Code:
<input type="text" name="feededBy" id="feededBy" value="{{user.displayName}}" hidden>
<input type="email" name="byEmailID" id="byEmailID" value="{{user.emailID}}" hidden>
Profile.objects.filter(id=request.COOKIES['id']) returns a QuerySet. To access the actual object, use list indexing, like profile[0].zipcode after getting value in profile. Since you are just expecting a single object, it is better to use get method or get_object_or_404 if applicable.
See this for introductory tutorial on this. You have to include more code for second error.
Related
I have a form input inside my HTML page and want the figure ID that is entered inside the form to be passed into my django view to do a query, displaying info for the figure with the matching ID.
My form:
<form metohd="GET" id="figure_choice_form">
<label for="figure_id">Enter ID</label>
<input type="text" id="figure_id" name="figure_id">
<button> Submit </button>
</form>
My views.py
def from_DB(request):
#request being the ID entered from the form
figures_list = Figure.objects.filter(id=request)
context = {"figures_list":figures_list}
return render(request,"app1/data_from_DB.html",context)
Firstly , Update your html code snippet to correct form attribute "metohd" to "method" .
You are sending data via GET request . So you can access it via request.GET method .
Code snippet of django view.
def from_DB(request):
id = request.GET.get("figure_id")
figures_list = Figure.objects.filter(id=id)
context = {"figures_list":figures_list}
return render(request,"app1/data_from_DB.html",context)
This does your required work .
I am creating a single page blog site how can i get the post id to the comments form , I created django forms with necessary field but the problem is ,I have to select the post id from a drop down menu manually while commenting, for that I passed post object as an input value of a form to views.py file but django needs instance to save in database what should I do now
note :I am not using post_detail
models.py
class comments(models.Model):
name=models.CharField(max_length=255)
content=models.TextField()
post=models.ForeignKey(blog,related_name="comments",on_delete=models.CASCADE)
#blog is the model to which comment is related
date=models.DateTimeField(auto_now_add=True)
forms.py
class commentform(ModelForm):
class Meta:
model=comments
fields=('name','content','post')
widgets={
'name' : forms.TextInput(attrs={'class':'form-control','placeholder':'type your name here'}),
'content' : forms.Textarea(attrs={'class':'form-control'}),
'post' : forms.Select(attrs={'class':'form-control'})
}
Html
<form method='POST' action="comment_action" class='form-group'>
{%csrf_token%}
{{form.name}}
{{form.content}}
<input type="text" id="objid" name="objid" value="{{objs.id}}" hidden>
<button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button>
views.py
def comment_action(request):
name=request.POST.get('name')
content=request.POST.get('content')
objid=request.POST.get('objid')
to_db=comments.objects.create(name=name,content=content,post=objid)
print(name,content,objid)
return redirect('/homepage')
return render(request, 'index.html')
ERROR :
Exception Type: ValueError
Exception Value:
Cannot assign "'48'": "comments.post" must be a "blog" instance.
-->48 is my blog id
i know that database will only accept instance post field because that was a foreign key
my question is how to pass it ?
You assign it with post_id:
def comment_action(request):
name = request.POST.get('name')
content = request.POST.get('content')
objid = request.POST.get('objid')
to_db = comments.objects.create(name=name, content=content, post_id=objid)
print(name,content,objid)
return redirect('/homepage')
Note: It is better to use a Form [Django-doc]
than to perform manual validation and cleaning of the data. A Form will not
only simplify rendering a form in HTML, but it also makes it more convenient
to validate the input, and clean the data to a more convenient type.
Note: normally a Django model is given a singular name, so Comment instead of comments.
I tried looking at different resources on the internet regarding this request and request.data in django, but I couldn't fully understand it.
Why this request parameter is kept inside the function? What are we passing in this request parameter?? Also, what does this request. data do??
def index(request):
content = {
'Blogdata': Blog.objects.all(),
}
return render(request, 'index.html', content)
def somefunction (request):
data=request.data
As you can see I have two functions above both of them have request paramter inside the function. Also, I need the explanation on this request.data as this has to be used multiple times.
First, you should understand about HTTP Request(Header, Body). When you type in form and send to server, browser get data with name and add values into body request. In the backend server, we will get data from body with name.
Example:
I have form fill your name:
<form action="/signin" method="get" name="myForm">
<label for="name">Your name:</label>
<input type="text" id="name" name="name"><br><br>
<input type="button" value="Send form data!">
</form>
You type name : "Khoa", browser get values "Khoa" from input and add key:values with name in . Like this: "name": "Khoa"
In server django, you can get data with using request.data.get("name") = "Khoa"
request.data is body HTTP send to servere, "name" is key part of body have values is "Khoa"
I'm having my app on heroku.
I use timeme js to record user's active time spend on the page, and use a hidden form to store the value into the database. Additionally, I'm using otree package to write my app.
The following is the code I use:
models.py
class Active(ExtraModel):
active_duration = models.FloatField()
active_record = models.LongStringField()
views.py/pages.py in otree
class intro_instructions(Page):
def before_next_page(self):
data = self.form.data
p = self.player
active = Active.objects.create(active_duration=data['active_duration'],
active_record=data['active_record'])
active.save()
html
<form method="post" role="form" id="form" autocomplete="off">{% csrf_token %}
<input type="text" name="active_record" id="id_active_record" style="display: none" >
<input type="number" step='any' name="active_duration" id="id_active_duration" style="display: none">
</form>
The error
ValueError
could not convert string to float: ''
{
"csrfmiddlewaretoken": "vVhVRLrAUokmiNGRpzCaP78bnTOQyowf5VMfIDgKGglWGuEyQAU2wooWjQzXuBgD",
"active_duration": "",
"active_record": ""
}
Is it because active_duration is empty? Will it help if I set blank=true, null=true for the forms?
I was assuming that every use would have value for the input. Also any ideas about why the input is empty? Could it be that the user used scripts to skip the page without visible fields? From the sentry error message, this happened to one user twice.
It is because you cannot cast an empty string to a float. You can do this instead though:
active_duration=data.get('active_duration') or "0"
This will give you a "0" if data["active_duration"] is empty, False, or None.
>>> data = {"foo": ""}
>>> data.get("foo") or "bar"
'bar'
i want to update fields using ajax:
models.py
class EmployerInfo(models.Model):
employer = models.ForeignKey(Employer, unique=True)
address=models.CharField(max_length=100, blank=True)
city=models.CharField(max_length=40, blank=True)
contactinfo.html
<form id="ajax-form">
<fieldset>
<legend>Contact Information</legend>
<label>Address:</label>
<input type="text" id="address" value="{{ empinfo.address }}" />
<label>City:</label>
<input type="text" id="city" value="{{ empinfo.city }}" /> <i class="icon-ok"></i>
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax-form").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "/employer/contactinfo/save/",
dataType: "json",
data: params,
success: setResult
});
});
});
urls.py
.....other urls
url(r'^employer/contactinfo/save/$', 'save_employer_info_ajax'),
view.py
def save_employer_info_ajax(request):
emp=Employer.objects.get(user=request.user)
emp_info=EmployerInfo.objects.get(employer=emp)
f_name=request.GET['param1']
f_value=request.GET['param2']
return HttpResponse(json.dumps({"issuccess": 'yes'}), content_type="application/json")
f_name the name of the field i want to update. lets assume it be 'address'.
how can i access that attribute, (ie emp_info.address) so that i can update (ie emp_info.address=f_value) using emp_info.save() function.
is there any method available other than emp_info.address, so that i can access the field name using string (ie emp_info[f_name]=f_value ) or something??
You could just use getattr baked into python
attr_name = 'employer_id'
if getattr(employee, attr_name) == 3:
...
You can use the update method on the queryset object. It's a bit hacky since you are really only wanting to update a single object though.
def save_employer_info_ajax(request):
emp_info_query = EmployerInfo.objects.filter(employer__user=request.user)
update_dict = {request.GET['param1'] : request.GET['param2'] }
emp_info_query.update(**update_dict)
Notice that I'm using reverse lookup relations to access EmployerInfo based on the user field of the Employer model. Then you construct a dictionary to hold the keys and values you wish to update, and pass that to the update method of the queryset, not the model instance.
You should be using forms for data entry though. There should be validation on all fields that you're entering into your database. You can use dynamic forms to specify the fields you want included based on the values that you submit via ajax.