I am working on a MAC and Windows for this issue. Summer note will not display icons in chrome or edge on either Mac or windows and deployed or locally. Everything works fine in safari and on my iPhone. I migrated and collected the static files and they showed up in my s3 bucket. Seems like everything is set up correctly since it does work.
settings.py
INSTALLED_APPS = [
'django_summernote',
]
SUMMERNOTE_THEME = 'bs5'
SUMMERNOTE_CONFIG = {
'summernote': {
'width': '100%',
}
}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('summernote/', include('django_summernote.urls')),
]
forms.py
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class CreateVenueForm(ModelForm):
class Meta:
model = Venue
fields = ('name', 'address', 'city', 'state', 'zip', 'description',)
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Gived your venue a title'}),
'address': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Number and Street name'}),
'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'city'}),
'state': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Give your event a title'}),
'zip': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Zip'}),
'description': SummernoteWidget(),
}
template
<div class="row">
<div class="col">{{form.description.label}}<br/>{{form.description|safe}}</div>
</div>
Related
I have two DateTime Fields in a model:
models.py
start_appointment = models.DateTimeField(default=timezone.now, blank=True)
end_appointment = models.DateTimeField(default=timezone.now, blank=True)
i also have a form where i set widgets for above fields:
'start_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
'end_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
i have an update view where i want to update appointment's fields for example start_appointment. However when rendering form in a template these two fields are shown as dd/mm/yyyy --:--, -- meaning values from database not shown, while all the others are rendered with no problem.
From the other hand i can execute the form with no problem and update is successful.
template:
<div class="form-group row">
<label class="col-form-label col-3 text-lg-right text-left">{% trans 'Start Appointment' %}</label>
<div class="col-9">
{{ form.start_appointment }}
</div>
</div>
Update
Adding forms.py
class AddAppointmentForm(forms.ModelForm):
class Meta:
model = Appointment
fields = ['user', 'name', 'appointment_notes', 'seat', 'start_appointment', 'end_appointment']
widgets = {
'user': forms.Select(attrs={'class': 'form-control'}),
'name': forms.TextInput(attrs={'class': 'form-control'}),
'appointment_notes': forms.Textarea(attrs={'maxlength': '900', 'class': 'form-control' }),
'seat': forms.Select(attrs={'class': 'form-control'}),
'start_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
'end_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}),
}
What might be the problem?
the problem might be this 'type': "datetime-local"
try this
try to change your datetime to something like this
'start_appointment': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class':'datetimefield'})
and for datetimepicker you can use something like this
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
window.addEventListener("DOMContentLoaded", function () {
flatpickr(".datetimefield", {
enableTime: true,
enableSeconds: true,
dateFormat: "Y-m-d H:i:S",
});
});
</script>
you can learn more on Flatpickr here https://flatpickr.js.org/
I have a model named SaleEntry:
class SaleEntry(models.Model):
date = models.DateField()
ebay_price = models.FloatField()
amazon_price = models.FloatField()
ebay_tax = models.FloatField()
paypal_tax = models.FloatField()
tm_fee = models.FloatField(default=0.3)
promoted = models.FloatField(default=0.0)
profit = models.FloatField()
discount = models.FloatField(default=0)
country = models.CharField(max_length=100, default="-----")
user = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
def save(self, *args, **kwargs):
if not self.pk: # object is being created, thus no primary key field yet
change_balance = Balance.objects.get(user=self.user)
change_balance.balance = change_balance.balance - self.amazon_price - self.tm_fee + self.discount
change_balance.save()
super(SaleEntry, self).save(*args, **kwargs)
def calc_profit(self):
return self.ebay_price - self.amazon_price - self.ebay_tax - self.paypal_tax - self.tm_fee - self.promoted + self.discount
def __str__(self):
return f'{self.user} - {self.profit}'
And I have a form handling this model SaleEntryForm:
class SaleEntryForm(ModelForm):
class Meta:
model = SaleEntry
fields = "__all__"
widgets = {
'date': DateInput(attrs={'class': 'form-control', 'id':'f_date'}),
'ebay_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'eBay Price', 'id':'f_ebay_price', 'onkeyup': 'calc_profit()'}),
'amazon_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Amazon Price', 'id':'f_amazon_price', 'onkeyup': 'calc_profit()'}),
'ebay_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'eBay Tax', 'id':'f_ebay_tax', 'onkeyup': 'calc_profit()'}),
'paypal_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Paypal Tax', 'id':'f_paypal_tax', 'onkeyup': 'calc_profit()'}),
'tm_fee': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'TM Fee', 'id':'f_tm_fee', 'onkeyup': 'calc_profit()'}),
'promoted': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Promoted', 'id':'f_promoted', 'onkeyup': 'calc_profit()'}),
'profit': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Profit', 'readonly':'true', 'id':'f_profit'}),
'discount': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Discount', 'id':'f_discount'}),
'country': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Country', 'id':'f_country'}),
}
def __init__(self, *args, **kwargs):
'''
relate the sale registration form to the user who created it.
'''
user_id = kwargs.pop('user_id')
super().__init__(*args, **kwargs)
self.fields['user'] = forms.ModelChoiceField(queryset=User.objects.filter(id=user_id), empty_label=None, initial=User.objects.get(id=user_id))
self.fields['user'].widget.attrs['class'] = 'no-display'
I am using this form in the html page:
<form id="form_add_sale">
{% csrf_token %}
<tr>
{% for field in form %}
{% if field is not form.user %}
<td>
{{ field }}
</td>
{% else %}
{{ field }}
{% endif %}
{% endfor %}
<td><input class="btn btn-primary" type="submit" display="inline" name="btn_register_sale"></td>
</tr>
</form>
and this is the ajax to send the data to server:
$(document).on("submit", '#form_add_sale', function(e){
e.preventDefault();
$.ajax({
url:"{% url 'add_sale' %}",
type:"POST",
data:{
date: $("#f_date").val(),
ebay_price: $("#f_ebay_price").val(),
amazon_price: $("#f_amazon_price").val(),
ebay_tax: $("#f_ebay_tax").val(),
paypal_tax: $("#f_paypal_tax").val(),
tm_fee: $("#f_tm_fee").val(),
promoted: $("#f_promoted").val(),
profit: $("#f_profit").val(),
discount: $("#f_discount").val(),
country: $("#f_country").val(),
},
success: function(){
alert("Created new sale!");
}
})
//.done(function(response){
// $("#table_sales").load(location.href + " #table_sales");
//})
.fail(function(xhr, status, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
})
})
upon submitting the form, I'm getting the next error (which didn't occur when submitting the form regularly without ajax with the exact same code in the view):
<ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
this is the request.POST:
<QueryDict: {'date': ['2021-02-11'], 'ebay_price': ['70'], 'amazon_price': ['50'], 'ebay_tax': ['10'], 'paypal_tax': ['5'], 'tm_fee': ['0.3'], 'promoted': ['0.0'], 'profit': ['4.70'], 'discount': ['0'], 'country': ['-----']}>
I think you forgot the csrf_token. try adding:
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
to the data.
More information can be found here
This field timeout = int(request.POST.get('timeout')) throws an error saying
invalid literal for int() with base 10: ''
this is my model field: timeout = models.IntegerField(default=10)
The forms submits just fine if I submit number because the form interprets it as a string but my form handler will convert it into integer. But it fails if I leave the field blank. Seems like it can't process an empty string.
What can I do ?
forms.py:
class TestCaseSuiteForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Name'}), label='')
documentation = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Documentation'}), label='')
setup = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Setup'}), label='')
teardown = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter teardown'}), label='')
force_tags = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Force Tags'}), label='')
timeout = forms.IntegerField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Timeout (optional)'}),
required=False, label='')
class Meta:
model = TestCase
fields = [
'name',
'documentation',
'force_tags',
'setup',
'teardown',
'timeout',
]
my view:
def index(request):
if request.method == 'POST':
form_tc = TestCaseForm(request.POST)
form_ts = TestCaseSuiteForm(request.POST)
if form_tc.is_valid() or form_ts.is_valid():
form_tc.save()
form_ts.save()
return redirect('/list')
In case you're wondering ... I've got two forms using one submit button.
Having gone to the trouble of defining a form and validating it, you are supposed to use that validated data, rather than resorting to the raw post data. Not only will the validated data use defaults as defined in the form where necessary, it will also convert types etc.
if form_tc.is_valid() and form_ts.is_valid():
TestCase.objects.create(
name=form.cleaned_data['name'],
documentation=cleaned_data['documentation'],
...
)
Note, you need to use the unprefixed field names as the keys here.
But this still isn't really getting you what you want. You haven't defined all your model fields as form fields, so you won't get defaults for the fields you haven't defined. Instead you should be using a model form.
class TestCaseSuiteForm(forms.ModelForm):
class Meta:
model = TestCase
fields = ['name', 'documentation', ...]
and now in your view you simply save the form to create the objects:
if form_tc.is_valid() and form_ts.is_valid():
form_tc.save()
form_ts.save()
Now your model defaults will be used appropriately.
Set a default using:
timeout = int(request.POST.get('timeout', 0))
How do I remove the ----- in my django ModelForm widgts?
documentation say to use empty_label but it is for SelectDateWidget
my form
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
exclude = ('copy', 'created', 'researcher', 'keywords', 'application_area', 'predominant_area')
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Titulo da oportunidade'
}),
'conclusion_date':forms.TextInput(attrs={
'class': 'form-control',
'type':'text',
'placeholder':'Data de conclusão'
}),
'category': forms.RadioSelect(attrs={
'class':'form-control'
}),
'result':forms.Select(attrs={
'class':'form-control'
}),
}
You can add default value for your select input then it will show default value initially.
For further reference:
https://docs.djangoproject.com/en/2.0/topics/forms/
https://docs.djangoproject.com/en/2.0/ref/forms/fields/
I'm struggling to get my tests to throw a form validation error in Django. This is using standard/default input types.
# forms.py
class NewUserForm(forms.Form):
first_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'First Name'})),
last_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Last Name'})),
email = forms.EmailField(),
mobile = floppyforms.CharField(
required=False,
widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Mobile number', 'autocomplete': 'false'})),
postcode = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Postcode'})),
super_balance = floppyforms.CharField(widget=floppyforms.RangeInput(attrs={'class': 'bar', 'type': 'range', 'id': 'rangeinput',
'value': '492500', 'min': '75000', 'max': '1000000',
'step': '5000', }))
# tests.py
class NewUserFormTest(TestCase):
def setUp(self):
self.valid_data = {
'first_name': 'herp',
'last_name': 'derp',
'email': 'herp#derp.com',
'mobile': '0412345678',
'postcode': '00000',
'relationship_status': 'S',
'super_balance': '100000',
'current_super_provider': '49'
}
...
def test_invalid_fields(self):
form = NewUserForm({})
self.assertFalse(form.is_valid()) # correct
data = self.valid_data
data['email'] = 24234 # this field should fail
form = NewUserForm(data)
form.is_valid() # returns True
When I pass a blank dictionary to the initial form. form.errors displays {'super_balance': ['This field is required.']}. This is more confusing because the documentation states that unless explicitly declared then all fields are assumed to be required.
I'm using 1.8.5
Cheers in advance
You need to remove the trailing commas from all the fields in your form.
Instead of
class NewUserForm(forms.Form):
...
email = forms.EmailField(),
...
it should be
class NewUserForm(forms.Form):
...
email = forms.EmailField()
...
At the moment, NewUserForm.email is a tuple, not a field, so any values for that field in the data dictionary are ignored. The only field without the trailing comma is super_balance, which is why it is the only error that appears when you pass a blank dictionary to the form.