I am new in Django and i am making a typical CRUD app. In the "add" section, in the comment textarea this message appears "
<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>"
and i dont know what to do. I had tried multiples solutions in other stackoverflow questions but i cant find the solutions!
Here's the code
class Turno(models.Model):
date = models.DateTimeField()
person = models.ForeignKey('Person', on_delete=models.CASCADE)
medic = models.ForeignKey('Medic', on_delete=models.CASCADE)
observations = models.CharField(blank=True, max_length=255)
def __str__(self):
return f'{self.date} {self.person} {self.medic}'
def new_turn(request):
if request.method == 'POST':
turnFormPost = TurnForm(request.POST)
if turnFormPost.is_valid():
turnFormPost.save()
return redirect("admin_index")
turnForm = TurnForm(instance=Turno)
context = {
'form':turnForm
}
return render(request,"turn_new.html", context)
class TurnForm(ModelForm):
class Meta:
model = Turno
fields = '__all__'
widgets = {
'date': DateTimeInput(attrs={'type':'date'}),
'observations': Textarea(attrs={'rows':5, 'cols':50})
}
-turn_new.html
<div class="container">
<h2>New Turn</h2>
<form method="POST">
{% csrf_token %}
<table>
{{form}}
</table>
<button type="submit" class="btn btn-primary">Create</button>
</form>
<div>
Back to index
</div>
</div>
in the textarea of 'observations' in 'turn_new.html' the message that appears is this
"<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>"
Related
My vews.py:
if you want me to share another piece of information feel free to ask!
I just have a problem with the bidding system !!, I tried the bidding but when I add the new number into the input field and click the place bid button the page just reloads which means the function doesn't work!!
I have another problem when I try to close the bid I git this Django error
ValueError at /bidding/26
The view auctions.views.bidding didn't return an HttpResponse object.
It returned None instead.
The code:
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
user = User.objects.get(username=request.user)
if listing.watchers.filter(id=request.user.id).exists():
is_watched = True
else:
is_watched = False
if not listing.activate:
if request.POST.get('button') == "Close":
listing.activate = True
listing.save()
else:
price = request.POST.get('bid', 0)
bids = listing.bids.all()
if user.username != listing.creator.username:
if price <= listing.price:
return render(request, 'auctions/item.html', {
"listing": listing,
'form': BidForm(),
"message": "Error! Your bid must be largest than the current bid!",
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'is_watched': is_watched,
})
form = BidForm(request.POST)
if form.is_valid():
bid = form.save(commit=False)
bid.user = user
bid.save()
listing.bids.add(bid)
listing.bid = price
listing.save()
else:
return render(request, 'acutions/item.html', {'form'})
context = {
'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'is_watched': is_watched,
'form': BidForm()}
return render(request, 'auctions/item.html', context)
models.py
class Bid(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
bid = models.DecimalField(max_digits=10, decimal_places=2)
time = models.DateTimeField(default=timezone.now)
class Post(models.Model):
# data fields
title = models.CharField(max_length=64)
textarea = models.TextField()
# bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)
imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True)
creator = models.ForeignKey(
User, on_delete=models.PROTECT, related_name="all_creators_listings")
watchers = models.ManyToManyField(
User, blank=True, related_name='favorite')
date = models.DateTimeField(auto_now_add=True)
# for activated the Category
activate = models.BooleanField(default=False)
bids = models.ManyToManyField(Bid, )
def __str__(self):
return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}"
item.html
<div class="card-body">
<ul class="list-group">
<div class="info">
<li class="list-group-item mb-2">Description:<br>{{listing.textarea}}</li>
<li class="list-group-item mb-2">category: {{listing.category.name}}</li>
<li class="list-group-item mb-2"><h5>Start bid: {{listing.price}}$</h5></li>
</div>
<div class="newbid">
<p>{{ message }}</p>
<form action="{% url 'viewList' listing.id %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="bid">{{ listing.bids.count }} bid(s) so far. Your bid is the current bid</label>
</div>
<div class="form-group">
{{ form }}
</div>
<div class="form-group">
<input type="submit" name="button" class="btn btn-primary" value="Place Bid">
</div>
</form>
{% if listing.activate %}
<li><strong>Winner: </strong>{{ listing.bids.last.user.username }}</li>
{% endif %}
{% if user.username == listing.creator.username and not listing.activate %}
<form action="{% url 'viewList' listing.id %}" method="POST">
{% csrf_token %}
<button type="submit" name="button" class="btn btn-danger" value="Close">Close</button>
</form>
{% endif %}
</div>
</ul>
</div>
inside this view, I added a punch of my project requirement (comments/watchlist(bookmark)/and the last thing(that what I have a lot of problem with it) is the system of Bid) that lets users add bids on such posts and let the creator of that post the ability to close it.... please help I am sticking in this zone, I tried many times to understand!
Note I am new at Back-end Development!
There is the two problem in you code first one is hi-lighted by Husam
user = User.objects.get(username=request.user.username)
and the other one is in the return statement in the else part
render(request, 'acutions/item.html', {'form'}) instead of context object you pass the string in which is consider as set object in python and thats why you are getting None type error.
here is the refactored code :-
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
user = User.objects.get(username=request.user.username)
form = BidForm()
is_watched = listing.watchers.filter(id=request.user.id).exists():
context = {}
if not listing.activate:
if request.POST.get('button') == "Close":
listing.activate = True
listing.save()
else:
price = request.POST.get('bid', 0)
bids = listing.bids.all()
if user.username != listing.creator.username:
if price <= listing.price:
context.update({'message':"Error! your bid must be largest than the current bid !"})
else:
form = BidForm(request.POST)
if form.is_valid():
bid = form.save(commit=False)
bid.user = user
bid.save()
listing.bids.add(bid)
listing.bid = price
listing.save()
else:
return render(request, 'acutions/item.html', {'form': form})
context.update({'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'is_watched': is_watched,
'form': form})
return render(request, 'auctions/item.html', context)
The error you face in bidding view and the view you have shared is view list, it would be better if you shared the bidding view and highlight the error line/s
Anyway I have noticed that this line has one mistake:
user = User.objects.get(username=request.user)
Which suppose to be :
user = User.objects.get(username=request.user.username)
Hope this can help you little bit
currently I'm trying to show part quantity (quan) together with part name in the dropdown. I have a Part table that carries the part name and part quantity and this table called as ForeignKey into the Order table. So, in the Order form during choose the part name from the part dropdown, I would like to show part quantity as well besides the part name. Any idea to make it like that?
models.py
class Part(models.Model):
partno = models.CharField(max_length=50)
partname = models.CharField(max_length=50)
quan = models.PositiveIntegerField(default= 0)
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
part = models.ForeignKey(Part, on_delete=models.CASCADE)
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
for form_data in forms_data:
forms = OrderForm(request.POST)
if forms.is_valid():
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</form>
You will have to write "__ str __"(without spaces between str and __) method for model 'Part'
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
Check this post also: What is doing __str__ function in Django?
I have the following Django form that is purposed to create a new item in my database. It is returning a 'false-positive' in that it shows a green 'Done' after I hit submit but the record is not actually added to the database. Any ideas what is causing this?
html
<form method="POST">
{% csrf_token %}
{{form}}
<div style="color:green">{{info}}</div>
<div style="color:red">{{error}}</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
views.py
def creator(request):
if request.method == "POST":
form = CommunicationsForm(request.POST)
if form.is_valid():
form.save()
return render(request,'polls/creation.html',{"form":CommunicationsForm,"info":"Done"})
else:
return render(request,'polls/creation.html',{"form":CommunicationsForm})
forms.py
class CommunicationsForm(forms.ModelForm):
class Meta:
model = Communications
fields = "__all__"
widgets = {
'project':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter your Project Name'}),
'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}),
'intent':forms.Textarea(attrs={'class': 'form-control','placeholder':'Describe the intent and desired outcome of the communication'}),
'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}),
'channel':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Channel'}),
'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}),
'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}),
'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}),
}
models.py
class Communications(models.Model):
project = models.CharField(max_length=200)
title = models.CharField(max_length=200)
intent = models.CharField(max_length=200)
date = models.CharField(max_length=200)
channel = models.CharField(max_length=200)
content_type = models.CharField(max_length=200)
audience = models.CharField(max_length=200)
status = models.CharField(max_length=200)
def __str__(self):
return self.communication
I need to get the data from a form in a Django database. The problem when I use .cleaned_data['name'] I am getting an attribute error
'SnippetForm' object has no attribute 'cleaned_data'.
when I tried passing through if old_form.is_valid(), the if is False.
With my code, I can get the HTML info, but I can not parser it with .clean_data.
Basically I don't want to create a regex and parse the html, I am looking for some Django Method that can help.
Html code got from Django:
<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="Ariel" maxlength="100" id="id_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="as#onsemi.com" maxlength="254" id="id_email"></td></tr>
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" value="Test" maxlength="100" id="id_subject"></td></tr>
<tr><th><label for="id_body">Body:</label></th><td><textarea name="body" cols="40" rows="10" id="id_body">
This is a test</textarea></td></tr>
In my views.py
def data_detail (request, request_id):
data_detail_django = get_object_or_404(Snippet, pk=request_id)
if request.method == "POST": #Also, it is not going throu this if...
old_form = SnippetForm(request.POST, instance=data_detail_django)
else: #The old_form is the html output and is get it with this
old_form = SnippetForm(instance=data_detail_django)
if old_form.is_valid():
print(old_form.cleaned_data['name'])
return HttpResponse("contact view")
In my models
from django.db import models
# Create your models here.
class Snippet(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
subject = models.CharField(max_length=100, blank=True, null=True)
body = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
in my form.py
from django import forms
from .models import Snippet
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = ('name', 'email','subject', 'body')
The solution was: Uning .objects.get(pk = vaule)
def data_detail (request, request_id):
data_dbs = Snippet.objects.get(pk= request_id)
data_out = {'data_dbs': data_dbs}
return render(request, 'form_app/detail.html', data_out )
and in the html to render:
{% extends 'form_app/base.html' %}
{% block main_content %}
{% if data_dbs %}
<p>Name: {{data_dbs.name}}</p>
<p>Email: {{data_dbs.email}}</p>
<p>Subject: {{data_dbs.subject}}</p>
<p>Body: {{data_dbs.body}}</p>
{% else %}
<p> No data</p>
{% endif %}
<a href = '/data'><b>See Form</b></a></li>
{% endblock %}
I'm creating a simple ratemyteacher/prof clone. The issue is that when going trying to add a Review object via my view, I get NOT NULL constraint failed: rate_review.review_id (app name is rate). It works fine when adding via /admin. Also, adding other models work fine.
Here's the view where it occurs:
def add_review(request, teacher_id):
form = ReviewForm()
if request.method == 'POST':
form = ReviewForm(request.POST)
if form.is_valid():
ip = request.META.get('HTTP_CF_CONNECTING_IP')
if ip is None:
ip = request.META.get('REMOTE_ADDR')
form.customSave()
messages.success(request, 'Review added.')
else:
form = ReviewForm(request.POST)
return render(request, 'rate/add_review.html', {'form': form})
return render(request, 'rate/add_review.html', {'form': form})
Here is the form (truncated to exclude loads). I'm using this to render forms:
<form method="POST">{% csrf_token %}
<div class="field">
<label class="label">Stars (whole numbers only)</label>
<div class="control">
{% render_field form.stars class+="input" %}
</div>
</div>
<div class="field">
<label class="label">Review subject</label>
<div class="control">
{% render_field form.subject class+="input" %}
</div>
</div>
<div class="field">
<label class="label">Review text</label>
<div class="control">
{% render_field form.text class+="textarea" placeholder="Review text" rows="10" %}
</div>
</div>
<div class="field">
<label class="label">Username</label>
<div class="control">
{% render_field form.author class+="input" placeholder="eg. ReviewerMan21, John Smith" %}
</div>
</div>
<button type="submit" class="button">Add review</button>
</form>
My models.py:
class Teacher(models.Model):
grade = models.IntegerField()
name = models.CharField(max_length=35)
subject = models.CharField(max_length=50)
ip = models.CharField(max_length=14)
approved = models.BooleanField(null=True, blank=True)
class Review(models.Model):
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
text = models.TextField()
subject = models.CharField(max_length=120)
author = models.CharField(max_length=35)
ip = models.CharField(max_length=14)
date = models.DateTimeField(auto_now_add=True)
stars = models.PositiveSmallIntegerField()
My forms.py:
from django import forms
from .models import Teacher, Review, Grade
from django.core import validators
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ('subject', 'text', 'stars', 'author')
def customSave(self, ip):
lv = self.save(commit=False)
lv.ip = ip
lv.save()
return lv
class TeacherForm(forms.ModelForm):
class Meta:
model = Teacher
fields = ('subject', 'name', 'grade')
def customSave(self, ip):
lv = self.save(commit=False)
lv.ip = ip
lv.save()
return lv
Things I've tried:
Resetting/flushing the DB
Commenting out ip, author & stars
Adding blank=True, null=True to ip, stars and author
Migrating DB
Edit: I've fixed (thanks to the answer below) by changing customSave in ReviewForm to this, and then passing the teacher variable from my view:
def customSave(self, ip, teacher):
lv = self.save(commit=False)
lv.ip = ip
lv.teacher = teacher
lv.save()
return lv
Your error shows that review_id is None (null). I notice that your ForeignKey field to Teacher on the Review model is named review instead of teacher, which would indicate the review_id really belongs to a Teacher object.
I noticed the first line of your view add_review method, you get a Teacher object but never do anything with it. Did you intent to set the teacher ('review' field) on your newly created review to this teacher instance?