I'm using a Django modelform to update data, and for some reason one field is not updating, while all others are.
The model:
class Five(models.Model):
name = models.CharField(max_length=100)
school = models.CharField(max_length=100)
email = models.CharField(max_length=100)
first = models.CharField(max_length=100)
second = models.CharField(max_length=100)
third = models.CharField(max_length=100)
fourth = models.CharField(max_length=100)
fifth = models.CharField(max_length=100)
edited = models.CharField(max_length=10)
def __unicode__(self):
return self.name
The modelForm:
class FiveForm(ModelForm):
class Meta:
model = Five
exclude = ['edited']
The view:
if (request.method == "POST"):
form = fiveForm.FiveForm(request.POST)
edited = 1
if (form.is_valid()):
new_five = form.save(commit=False)
new_five.edited = edited
new_five = form.save()
The markup:
<form action="{% url 'choose' %}" method="post">
{% csrf_token %}
<p id="formname"></p>
<table>
<tr><td>Full Name:</td><td>{{ form.name }}</td></tr>
<tr><td>Email Address:</td><td>{{ form.email }}</td></tr>
<tr><td>Your College:</td><td>{{ form.school }}</td></tr>
<tr><td>Choice 1:</td><td>{{ form.first }}</td></tr>
<tr><td>Choice 2:</td><td>{{ form.second }}</td></tr>
<tr><td>Choice 3:</td><td>{{ form.third }}</td></tr>
<tr><td>Choice 4:</td><td>{{ form.fourth }}</td></tr>
<tr><td>Choice 5:</td><td>{{ form.fifth }}</td></tr>
</table>
<input type="submit" class="btn btn-default btn-lg sub" value="High 5!" />
</form>
For some reason, every field except name is updated in the database. Can't figure it out.
Thanks for any help.
You need to call the save method of the instance new_five after you have modified it.
if form.is_valid():
new_five = form.save(commit=False)
new_five.edited = edited
new_five.save()
Currently, you are calling the form's save method twice, which won't work.
Related
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 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>"
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 spend a lot of time in google and find a few solutions for my problem
but none of them works :((
models :
class Album(models.Model):
name = models.CharField(max_length=100)
author = models.CharField(max_length=100)
picture_address = models.TextField(max_length=1000)
creation_year = models.IntegerField(default=-1)
rate = models.IntegerField(default=0)
class Music(models.Model):
name = models.CharField(max_length=100)
cover = models.ImageField(upload_to=upload_destination)
album_id = models.ForeignKey(Album, on_delete=models.CASCADE)
and here is form :
class music_create_form(forms.ModelForm):
album_options = [('', '')]
for album in models.Album.objects.all():
album_options.append((album,album.name))
name = forms.CharField(required=True
, widget=forms.TextInput(attrs={'class': "normal_padding form-control"}))
cover = forms.FileField(required=True
, widget=forms.FileInput(attrs={'class': "normal_padding", 'accept': "image/jpeg"}))
album_id = forms.Field(required=True
,
widget=forms.Select(attrs={'class': "normal_padding form-control"}, choices=album_options))
class Meta:
model = models.Music
fields = [
'name', 'cover', 'album_id'
]
and here is view :
def create_music(request):
form = forms.music_create_form(request.POST or None, request.FILES or None)
context = {'form': form}
if request.method == "POST":
if form.is_valid():
print(form)
data = form.save(commit=False)
data.save()
context['action_done'] = True
return render(request, 'music/create_music.html', context)
when i try to add new model with that form , i got the error at this line : " if form.is_valid() "
Cannot assign “'Album object (6)'”: “Music.album_id” must be a “Album” instance
This is my form in template :
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
<div class="form-inline">
<h5 class="normal_padding">Music Name:</h5>
{{ form.name }}
</div>
<div class="form-inline">
<h5 class="normal_padding">Music Cover:</h5>
{{ form.cover }}
</div>
<div class="form-inline">
<h5 class="normal_padding">Album:</h5>
{{ form.album_id }}
</div>
<button type="submit" class="btn btn-primary">save data</button>
</div>
</form>
You shouldn't use forms.Field. In this case, you should use a ModelChoiceField, that will take care of getting the choices for you.
class MusicCreateForm(forms.ModelForm):
name = forms.CharField(required=True
, widget=forms.TextInput(attrs={'class': "normal_padding form-control"}))
cover = forms.FileField(required=True
, widget=forms.FileInput(attrs={'class': "normal_padding", 'accept': "image/jpeg"}))
album_id = forms.ModelChoiceField(queryset=Album.objects.all(),
widget=forms.Select(attrs={'class': "normal_padding form-control"}))
As an aside, it would be better to rename your ForeignKey and form field to album. That way music.album is the related album and music.album_id is it's id. At the moment, music.album_id is the album and music.album_id_id is the id.
I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database.
This is my class view:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form = forms.LeadForm()
fields = ['name','email','tel','kind']
This is my model form:
class LeadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kind = models.Lead.kind
class Meta:
model = models.Lead
kind = forms.CharField(widget=forms.HiddenInput())
fields = ['name','email','tel','kind']
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="{{ form.kind.monthly }}" />
<input type="submit" name="" value="Submit" class="btn btn-info">
I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database.
I found the solution! Yeah! Please let me know if there is maybe a better or more correct solution!
This is my class View:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form_class = forms.LeadForm
This is my model form:
class LeadForm(forms.ModelForm):
class Meta:
model = models.Lead
fields = ['name','email','tel','kind']
widgets = {
'kind':forms.HiddenInput()
}
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="monthly">
<input type="submit" name="" value="Submit" class="btn btn-info">
Finally after 2 days of struggling, I hope this can help someone else out!