Unnamed title appears blank - django

I have a form that I can save the title as blank in this case the function transform the blank as unnamed + primary key. But in my case the saving as blank remains blank . I don't know what is the problem.
The template :
<div class="page-header">
<h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %}</div>
<div id="tab1" class="tab" >
<form action="{% url "backtest" %}" method='POST' role='form' id='form'>
{% csrf_token %}
<input type="hidden" name="tabs" value="first" id="toggle-tab1" checked="checked" />
{% include 'tags/parameters_form.html' %}
<br />
{% include 'tags/parameters_backtest_form.html' %}
<br />
{% if user.is_authenticated %}
<input type='submit' id='run' value='Run' class='btn btn-default'>
{% if user.profile.is_active %}
Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
{% else %}
<p>
Expired account! you need to reactivate in order to save parameters.
</p>
{% endif %}
{% else %}
Please login in order to Run backtesting!
</br>
Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).
{% endif %}
The models.py :
title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters')
def __unicode__(self):
if self.title:
return u'%s' % (self.title)
else:
return u'Unnamed%s' % (self.pk)

As pk is integer.
You need to format it as integer.
return u'Unnamed%d' % (self.pk)

Related

Django template variable removes content after whitespace

I am having this very confusing issue and I could only find someone who had the same issue 9 year ago but it wasn't solved : Posting a hidden field with whitespace removes content after whitespace.
First of all I'm very new to programming so pardon me if this is a very obvious issue and if my bug is very ugly !
Basically I am trying to pass the content of a variable through the value parameter of an input tag inside of a form. This variable contains strings separated by whitespaces ("test space space")
My goal is to then manipulate this data in a view through request.POST
The issue is that the first word gets passed just fine but anything after the first whitespace isn't passed to the database.
Note that I am using the same variable elsewhere in the same template and the entire title is displayed without issue
Here is my view :
#login_required
def watchlist(request):
user = request.user
all_watched_auctions = WatchedAuction.objects.all()
user_watched_auctions=all_watched_auctions.filter(user_id=user.id)
if request.method == "POST" :
auction_info = request.POST
user_id = auction_info.get('user_id')
auction_id = auction_info.get('auction_id')
title = request.POST.get('title')
# #creating a watched auction
auction_to_watch = WatchedAuction(user_id=user_id, auction_id=auction_id, is_watched=True, title=title)
# #preventing duplicates
if auction_id not in user_watched_auctions:
auction_to_watch.save()
test = user_watched_auctions.values_list("auction_id", flat=True)
active_listings = Listing.objects.filter(status="ACTIVE")
return render(request,"auctions/watchlist.html",{
"watchlist" : test,
"listings" : active_listings,
"user" : user,
})
And here is the template. You can skip to the end. That's where the troublesome form is :
{% extends "auctions/index.html" %}
{% block title %} {{listing.title}}{% endblock %}
{% block h2 %}
{% if listing.status == "ACTIVE" %}
<h2>Listing is active</h2>
{% else %}
<h2>Listing is inactive</h2>
{% endif %}
{% endblock %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<div>
<div>{% block test1 %}
{% if test.id == listing.id %}
{{block.super}}
</div>
<div>
</div>
{% if listing.author_id == user_id and listing.status == "ACTIVE" %}
</div>
<form action="" method="post">
{% csrf_token %}
<a href="">
<button> Close listing </button>
</a>
</form>
{% endif %}
{% if listing.author_id != user_id and listing.status == "ACTIVE" %}
<form action="{% url 'watchlist' %}" method="post" value="test.id">
{% csrf_token %}
<input type="hidden" name="user_id" value={{user_id}}>
<input type="hidden" name="auction_id" value={{listing.id}}>
<input type="hidden" name="is_valid" value=True>
<input type="hidden" name="title" value={{listing.title}}>
<button type="submit"> add to watchlist</button>
</form>
{% endif %}
{% endif %}
{% endblock %}
Thanks a lot to anyone taking the time to help me !
Most Probably this is due to lack of quotes between actual value value="actual_value". You can use single quotes or double quotes according to your html. Please try this way. It may work.
<input type="hidden" name="user_id" value="{{user_id}}">
<input type="hidden" name="auction_id" value="{{listing.id}}">
<input type="hidden" name="is_valid" value="True">
<input type="hidden" name="title" value="{{listing.title}}">
<button type="submit"> add to watchlist</button>

Django - Account Settings BooleanField

I reviewed most of the posts here related to Django and BooleanField update, but I couldn't find any related to my problem solution.
I have a custom user models.py:
# Own custom user model
class Account(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
guardianSource = models.BooleanField(default=True)
bbcSource = models.BooleanField(default=False)
independentSource = models.BooleanField(default=False)
categoryCoronaVirus = models.BooleanField(default=False)
categoryPolitics = models.BooleanField(default=False)
categorySport = models.BooleanField(default=False)
When I register a user it seems to register in the database all correct values for the checkboxes. The problem is when I want to edit user information I cannot see if a checkbox was checked on registering or not, it displays the checkboxes itself, but they are all empty (False). However, it correctly requests the username and displays it so I can edit it, but all the checkboxes are unchecked.
views.py:
def account_view(request):
if not request.user.is_authenticated:
return redirect('login')
context = {}
if request.POST:
form = AccountUpdateForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
context['success_message'] = "Updated"
else: # Display the saved user details from database
form = AccountUpdateForm(
initial = {
'username':request.user.username,
"guardianSource": request.user.guardianSource,
"bbcSource": request.user.bbcSource,
"independentSource": request.user.independentSource,
"categoryCoronaVirus": request.user.categoryCoronaVirus,
"categoryPolitics": request.user.categoryPolitics,
"categorySport": request.user.categorySport,
})
context['account_form'] = form
return render(request, 'accounts/account.html', context)
account html:
{% extends 'base.html' %}
{% block content %}
<form class="form-signin" method="POST">{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Account Settings</h1>
<label for="username" class="sr-only">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" value="{{account_form.initial.username}}">
<br>
<div class="form-control">
<p><b>Please choose news sources!</b></p>
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="guardianSource" id="guardianSource" value="{{account_form.initial.guardianSource}}" >
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="bbcSource" id="bbcSource" value="{{account_form.initial.bbcSource}}" >
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="independentSource" id="independentSource" value="{{account_form.initial.independentSource}}" >
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >The Guardian</label>
<input type="checkbox" name="categoryCoronaVirus" id="categoryCoronaVirus" value="{{account_form.initial.categoryCoronaVirus}}" >
<br>
<label for="categoryPolitics" >BBC News</label>
<input type="checkbox" name="categoryPolitics" id="categoryPolitics" value="{{account_form.initial.categoryPolitics}}" >
<br>
<label for="categorySport" >The Independent</label>
<input type="checkbox" name="categorySport" id="categorySport" value="{{account_form.initial.categorySport}}">
</div>
{% for field in registration_form %}
<p>
{% for error in field.errors %}
<p sttle="color:red"> {{ error }}</p>
{% endfor %}
</p>
{% endfor %}
{% if registration_form.non_field_errors %}
<div style="color:red;">
<p>{{registration_form.non_field_errors}}</p>
</div>
{% endif %}
{% for field in account_form %}
<p>
{% for error in field.errors %}
<p sttle="color:red"> {{ error }}</p>
{% endfor %}
</p>
{% endfor %}
{% if account_form.non_field_errors %}
<div style="color:red;">
<p>{{account_form.non_field_errors}}</p>
</div>
{% endif %}
{% if success_message %}
<p style = "color: green; text-align:center;">{{success_message}}</p>
{% endif %}
<h6 class="text-muted">
If you don't choose a source and category it will automatically assign the ones that are checked!<br>
NOTE: You <b>MUST</b> select at least 1 choice for each!!!
</h6>
<button class="btn btn-lg btn-primary btn-block" type="submit">Save Changes</button>
</form>
<div class="d-flex flex-column">
<a class="m-auto" href="{% url 'password_change' %}">Change password</a>
</div>
{% endblock content %}
Thanks in advance and I am sorry if my post is duplicated.
EDIT:
The issue was found.
In the account.html file the values for each input type checkbox were wrong.
What I changed from:
<input type="checkbox" name="guardianSource" id="guardianSource" value="{{account_form.initial.guardianSource}}" >
To:
<input type="checkbox" name="guardianSource" id="guardianSource" value="{{account_form.guardianSource}}" >
For all the input values after the username input the initial had to be removed
You don't need to pass initial when you are initializing a ModelForm and have the instance
else: # Display the saved user details from database
form = AccountUpdateForm(instance=request.user)
You can use the field directly in the template and it will be rendered with the correct values, you don't need to construct the html for the input yourself
<label for="{{ account_form.guardianSource.id_for_label }}">The Guardian</label>
{{ account_form.guardianSource }}
The docs have a section on how to render fields manually

Django - Select a valid choice. That choice is not one of the available choices

Here are my forms:
class RoleForm(forms.ModelForm):
class Meta:
model = models.RoleModel
fields = ['name']
class FeatureForm(forms.ModelForm):
role = forms.ModelChoiceField(queryset=models.RoleModel.objects.values_list('name', flat=True).distinct())
class Meta:
model = models.FeatureModel
fields = ['role','feature']
In my bootstrap form, the choices display properly. I get a list of all roles. But if I fill the feature form and hit submit it says - "Select a valid choice. That choice is not one of the available choices."
My models are:
class RoleModel(models.Model):
name = models.CharField(validators=[alphanumeric], max_length=50, unique=True, blank=False)
class FeatureModel(models.Model):
role = models.ForeignKey(RoleModel, on_delete=models.PROTECT)
feature = models.CharField(validators=[alphanumeric], max_length=10, unique=True)
my bootsrtap form is:
<form action="{% url 'feature_form' %}" novalidate method="POST">{% csrf_token %}
<div class="row">
<div class="col">
<label for="role">{{ fform.role.label }}</label>
<p><select class="form-control id="role" name="role">
{% for item in fform.role %}
{{ item }}
{% endfor %}
</select></p>
{% for error in fform.role.errors %}
<p><small class="alert-danger">{{ error }}</small></p>
{% endfor %}
</div>
<div class="col">
<label for="feature">{{ fform.feature.label }</label>
<p><input type="text" class="form-control" id="feature" name="feature"
{% if fform.feature.value is not None %}
value="{{ fform.feature.value }}"
{% endif %}
></p>
{% for error in fform.feature.errors %}
<p><small class="alert-danger">{{ error }}</small></p>
{% endfor %}
</div>
</div>
<input class='btn btn-primary btn-sm' type='submit' value='Save'>
</form>
My need is simple. The second form (FeatureForm) has two fields. role being foreign key of another model and a text field to type in name of a feature. On my client side, I need the foreign key to be displayed as a select option with a list. I chose a value from this select, enter the value of feature and hit save. It has to save.
It doesn't work, because your queryset includes only names, but you need an id / primary key of a RoleModel. Since your choices don't have an id, they aren't a valid choice.
Firstly, your RoleModel name is set to unique and is therefore no point in querying distinct() name values because they will be distinct already by unique definition.
You also don't need to construct your own select input. Django will take care of this.
All you need is:
class RoleModel(models.Model):
name = models.CharField(validators=[alphanumeric], max_length=50, unique=True, blank=False)
def __str__(self):
return self.name
class FeatureForm(forms.ModelForm):
class Meta:
model = models.FeatureModel
fields = ['role', 'feature']
def __init__(self, *args, **kwargs):
super(FeatureForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs = {'class': 'form-control'}
and
<form action="{% url 'feature_form' %}" novalidate method="POST">
{% csrf_token %}
<div class="row">
<div class="col">
<label for="role">{{ fform.role.label }}</label>
<p>{{ fform.role }} </p>
{% for error in fform.role.errors %}
<p><small class="alert-danger">{{ error }}</small></p>
{% endfor %}
</div>
<div class="col">
<label for="feature">{{ fform.feature.label }</label>
<p>{{ fform.feature }}</p>
{% for error in fform.feature.errors %}
<p><small class="alert-danger">{{ error }}</small></p>
{% endfor %}
</div>
</div>
<input class='btn btn-primary btn-sm' type='submit' value='Save'>
</form>
EDIT: Otherwise, a Select input in this case should be constructed as:
<select>
<option value="1">Name 1</option>
<option value="2">Name 2</option>
</select>
where value is an id, a primary key of RoleModel in your case. Your select options don't have this value.

django form is invalid but has no errors

my datefields in my django form render always as invalid, but no errors of the how and why are given. (I use both non_field_errors as field.errors )
My Form
class FilterJournalForm(forms.Form):
end_initial = datetime.now(utc)
from_initial = (end_initial - timedelta(days=30))
from_date = forms.DateField(
widget=forms.DateInput(format='%m-%d-%Y'),
initial=from_initial,
required=True,
)
end_date = forms.DateField(
widget=forms.DateInput(format='%m-%d-%Y'),
initial=end_initial,
required=True,
)
part of my view that has the form:
filter_form = FilterJournalForm(request.POST or None)
if request.POST:
print request.POST
if filter_form.is_valid():
print "success"
My template part:
<form class="form-inline" action="" method="POST">
{% csrf_token %}
<div class="form-group">
{{ filter_form.from_date|add_css_class:"form-control input-sm" }}
</div> until
<div class="form-group">
{{ filter_form.end_date|add_css_class:"form-control input-sm" }}
</div>
<button type="submit" class="btn btn-primary btn-sm" >Filter</button>
{% if filter_form.errors %}
<div id="form-error">
<p>The operation could not be performed because one or more error(s) occurred.<br />{{ filter_form.non_field_errors }}</p>
<ul>
{% for field in form %}
<li>{{ field.errors|striptags }}</li>
{% endfor %}
</ul>
</div>
Any idea what is going wrong here? (i also tried to change the initial input of my formfields to date.today() to see if datetime objects could be ruining it. But that as well is not the problem.
{% endif %}

Why aren't labels appearing in my Django ModelForm?

I have a very simple ModelForm in my app that looks like this:
# ModelForm
class ProductForm(ModelForm):
class Meta:
model = MyModel
exclude = ['created', 'last_modified', 'serial_number']
# Model
class BaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True, blank=True, null=True)
class MyModel(BaseModel):
product = models.TextField(verbose_name='Product Name')
serial_number = models.TextField(verbose_name='Serial Number')
And a form that looks like this:
# Form
<form method="POST" action="{% url some_url %}">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% for field in form %}
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<div>
{{ field.label_tag }}:
{{ field }}
</div>
{% endfor %}
{% endfor %}
<div class="actions">
<input class="button submit focus" type="submit" value="{% trans "Save" %}" />
</div>
</form>
When I check out the view using this, I just see a colon (:) followed by the textfield: The label is gone.
According to the documentation for ModelForm:
In addition, each generated form field has attributes set as follows:
...
The form field’s label is set to the verbose_name of the model field, with the first character capitalized.
What mistake have I made?
I am using Django 1.4.1 if it matters.
You have to put the field label inside a <label> tag. So:
<div>
<label for="id_{{field.html_name}}">{{field.label}}:</label>
{{ field }}
</div>
The only solution I managed to find that still allowed me to separate each row of the form was doing the following:
<form method="POST" action="{% url some_url %}">
{% csrf_token %}
{{ formset.as_ul }}
<div class="actions">
<input class="button submit focus" type="submit" value="{% trans "Save" %}" />
</div>
</form>
... the key piece being the {{ formset.as_ul }} instead of iterating through each field.
As for why the other listed solution (or the solution in the documentation) didn't work, I will remain baffled.