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!
Related
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 have one app that holds a list of work orders, and another app that holds list of parts.
class Order(models.Model):
parts = models.ManyToManyField(Part, blank=True) # Assosiated parts
class Part(models.Model):
partnum = models.CharField(max_length=20) # Part number
mwos = models.ManyToManyField('mtn.Order', blank=True) # Assosiated work orders
Now i want to add a button to my DetailView for order which will open a list of parts, which i will be able to add to my order. At the moment i have a created an UpdateView for my order
class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Order
form_class = AddPartForm
...
and a form
class AddPartForm(forms.ModelForm):
class Meta:
model = Order
fields = ['parts', ]
labels = {'parts': "Parts", }
def FilterList(request):
qs = Part.objects.all()
search_part_query = request.GET.get('search_part')
if is_valid_queryparam(search_part_query):
qs = qs.filter(Q(partnum__icontains=search_part_query)
| Q(descr__icontains=search_part_query)
).distinct()
return qs
def __init__(self, *args, **kwargs):
super(AddPartForm, self).__init__(*args, **kwargs)
self.fields["parts"].widget = CheckboxSelectMultiple()
self.fields["parts"].queryset = self.FilterList()
for this template
{% block content %}
<form method="GET" action=".">
<div class="form-row justify-content-start">
<div class="form-group col-md align-self-center">
<div class="input-group">
<input class="form-conrol py-2 border-right-0 border" type="search" placeholder="Find part" name="search_part">
<span class="input-group-append">
<div class="input-group-text bg-transparent">
<i class="fa fa-search"></i>
</div>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-sm btn-block">Search</button>
</form>
<form action="{% url 'mtn:add_part' order.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock content %}
But when i'm executing it i get
'AddPartForm' object has no attribute 'GET'
error.
I am new to programming, so maybe i am approaching this the wrong way.
A form is normally not aware of the request object. You can make such a form, for example with:
class AddPartForm(forms.ModelForm):
class Meta:
model = Order
fields = ['parts', ]
labels = {'parts': "Parts", }
widgets = {
'parts': CheckboxSelectMultiple
}
def filter_list(self, request):
qs = Part.objects.all()
search_part_query = request.GET.get('search_part')
if is_valid_queryparam(search_part_query):
qs = qs.filter(Q(partnum__icontains=search_part_query)
| Q(descr__icontains=search_part_query)
).distinct()
return qs
def __init__(self, *args, request=None, **kwargs):
super(AddPartForm, self).__init__(*args, **kwargs)
self.fields["parts"].queryset = self.filter_list(request)
In the AddPartView, you can the pass the request as parameter to the form by overriding the .get_form_kwargs(..) method [Django-doc]
class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Order
form_class = AddPartForm
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update(request=self.request)
return kwargs
I'm writing a django app, and I'd like for users to be able to select a [team_number] from a dropdown menu, then when they hit submit be redirected to a page that renders out the database information associated with that selection. I'm using the redirect class View, but the problem I'm having is that there is no dropdown menu showing up to select [team_number] from on the html page team-stats.html.
views.py:
class TeamStatsView(View):
def get(self, request, *args, **kwargs):
return render(request, 'team-stats.html',
{'team_number': TeamStats()})
def post(self, request, *args, **kwargs):
team_number = TeamStats(request.POST, request.FILES)
if team_number.is_valid():
# do stuff & add to database
team_number.save()
team_number = TeamStats.objects.create()
# use my_file.pk or whatever attribute of FileField your id is
# based on
return HttpResponseRedirect('/team-stats/%i/' % team_number.pk)
return render(request, 'team-stats.html', {'team_number': team_number})
models.py:
class Team(models.Model):
team_number = models.IntegerField()
team_notes = models.CharField(max_length=150)
event_id = models.ForeignKey(
'Event', on_delete=models.CASCADE, unique=False)
def __unicode__(self):
return str(self.team_number)
class Meta:
db_table = 'teams'
app_label = 'frcstats'
forms.py:
class TeamStats(forms.ModelForm):
class Meta:
model = Team
fields = ['team_number']
team-stats.html:
<form method="post" action="">
{% csrf_token %} {{ TeamStatsView }}
<input type="submit" value="Submit" />
</form>
If there are any other files that I need to update into here to show what I'm trying to do, please let me know. Thanks
Try changing your view variable name to team_numbers and replacing your team-stats.html snippet with the following:
<form method="post" action="">
<select name="teams">
{% for team_number in team_numbers %}
<option value="{{ team_number }}">Team Num: {{ team_number }}</option>
{% endfor %}
</select>
</form>
Then update your view to:
class TeamStatsView(View):
def get(self, request, *args, **kwargs):
return render(request, 'team-stats.html',
{'team_numbers':Team.objects.values('team_number')})
You can use choices=NUMBERS
NUMBERS = (
('1','1'),
('2','2'),
('3','3'),
('4','4')
)
class Team(models.Model):
team_number = models.IntegerField(choices=NUMBERS )
team_notes = models.CharField(max_length=150)
event_id = models.ForeignKey(
'Event', on_delete=models.CASCADE, unique=False)
def __unicode__(self):
return str(self.team_number)
class Meta:
db_table = 'teams'
app_label = 'frcstats'
Your view variable is called team_number.
Try to change TeamStatsView into team_number:
<form method="post" action="">
{% csrf_token %} {{ team_number }}
<input type="submit" value="Submit" />
</form>
I'm a bit confused on how Forms and ModelForms work, I want to create colored buttons based on a field value while creating a form.
{% for category in form.category %}
<label class="colored-icon btn btn-default btn-sm" style="background-color: {{ category.color }}">
{{ category.choice_label|slice:"1" }}
{{ category.tag }}
</label>
{% endfor %}
The problem is that category.colorobviously doesn't have value I need.
My form is based on a "Transaction" model. I need to somehow access "color" attribute from "Category" model, which looks like this:
forms.py
class TransactionForm(forms.ModelForm):
class Meta:
model = Transaction
models.py
class Transaction(models.Model):
category = models.ForeignKey(Category, default='Unspecified')
class Category(models.Model):
color = models.CharField(max_length=10)
views.py
def index(request):
form = TransactionForm(request.POST)
new_transaction = form.save()
context = {
'form': form,
}
return render(request, 'index.html', context)
What's the proper way to select and pass "category.color" to each field I'm creating?
Thanks.
Try this:
class Category(models.Model):
color = models.CharField(max_length=10)
def __unicode__(self):
return '%s - %s' % (self.OtherFieldName, self.color)
that way inside the select should look like this
<option value='CategoryID'>OtherFieldName_value - color_value</option>
Alright, I've figured out a way to do so with modified #warath-coder answer. I wasn't able to access "_value" property if it was a way to go, so I had to implement "split" filter and use it to split value I've got and use "color" part of this value.
models.py
class Category(models.Model):
color = models.CharField(max_length=10)
def __unicode__(self):
return '%s - %s' % (self.OtherFieldName, self.color)
split_filter.py
#register.filter(name='split')
def split(value, arg):
return value.split(arg)
index.html
{% with category.choice_label|split:"-" as label %}
<label class="btn btn-default btn-sm" style="background-color: {{ label.1 }}">
{{ label.0 }}
{{ category.tag }}
</label>
{% endwith %}
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.