Please, I am a new user of django and I don't understand what is wrong in my model.
I have activated the admin, and created a new model:
class Strumenti(models.Model):
cod_stru = models.AutoField(db_column='cod_stru', primary_key=True)
sht_name = models.CharField(db_column='sht_name', max_length=15, blank=True, null=True)
descr = models.CharField(db_column='descr', max_length=45, blank=True, null=True)
isin = models.CharField(db_column='isin', max_length=16)
tipo = models.CharField(db_column='tipo', max_length=1)
mktcode = models.ForeignKey(Mercati, on_delete=models.CASCADE, default=1)
ccy1 = models.ForeignKey(Valute, related_name='ccyone', on_delete=models.CASCADE)
ccy2 = models.ForeignKey(Valute, related_name='ccytwo', on_delete=models.CASCADE)
beta = models.DecimalField(db_column='beta', max_digits=2, decimal_places=2, blank=True, null=True)
system = models.NullBooleanField(db_column='system', default=False, null=True)
template = models.NullBooleanField(db_column='template', default=False, null=True)
tenor = models.CharField(db_column='tenor', max_length=4, blank=True, null=True)
divy = models.DecimalField(db_column='divy', max_digits=5, decimal_places=5, blank=True, null=True)
fxpair = models.CharField(db_column='fxpair', max_length=6, blank=True, null=True)
cod_emitt = models.ForeignKey(Emittenti, on_delete=models.CASCADE, null=True)
idx_code = models.ForeignKey(Indexdef, on_delete=models.CASCADE, null=True)
vol_type = models.IntegerField(db_column='vol_type', blank=True, null=True)
def __unicode__(self):
return u'%s - %s - %s - %s' % (self.cod_stru, self.sht_name, self.descr, self.tipo)
when I try to ADD a new record I get this error:
**'ascii' codec can't encode character u'\xe3' in position 14: ordinal not in range(128)**
I am using Django 1.9, python 2.7, Mysql (utf8_unicode_ci)
hereunder the error during template rendering
In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33
ascii
23 {% endblock %}
24 {% endif %}
25
26 {% block content %}<div id="content-main">
27 {% block object-tools %}
28 {% if change %}{% if not is_popup %}
29 <ul class="object-tools">
30 {% block object-tools-items %}
31 <li>
32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %}
33 {% trans "History" %}
someone can help me?
Ok, I found the problem.
I stored in the 'Valute' table the description "São Tomé and Príncipe".
chars like ã é í produce the error, even if I don't understand why my .encode(uft-8) didn't work...
Any why I have just changed the string to "Sao Tome and Principe" and now it seems to be fine.
Related
I have two Models in my application that are related to each other (Item and ItemGallery). In my Template, I want the user to have the option of Edit Gallery or Add Gallery. Once the User has entered the image gallery belong to an item before the Interface should change to Edit Gallery. If not, the Interface should be Add Gallery. In a short world, I should be able to know if an item has or have a gallery image or not. If it has gallery then, edit Gallery if not Add Gallery
{% if mylists.itemgallery.all >= 1 %}
<a href="{% url 'add_gallery' mylists.id %}">
<i class="fa fa-pencil"></i>Edit Gallery
</a>
{% else %}
<a href="{% url 'add_gallery' mylists.id %}">
<i class="fa fa-pencil"></i>Add Gallery
</a>
{% endif %}
models.py
class Item(models.Model):
STATUS = (
('Used', "Used"),
('New', "New"),
('Fairly Used', 'Fairly Used'),
('Tokunbo', 'Tokunbo'),
)
ITEM_TYPE = (
('Demand', "Demand"),
('Offer', "Offer"),
)
SALES_TYPE = (
('By Dealer', "By Dealer"),
('By Owner', "By Owner"),
)
CAR_MAKE = (
('Toyota', "Toyota"),
('Nissan', "Nissan"),
('Audi', 'Audi'),
('Honda', 'Honda'),
('Volkswagen', 'Volkswagen'),
('Mercedes Benz', 'Mercedes Benz'),
('Land Rover', 'Land Rover'),
('BMW', 'BMW'),
)
QUALIFICATION = (
('PhD', "PhD"),
('BSc', "BSc"),
('HND', "HND"),
("O'Level", "O'level"),
)
name = models.CharField('Add Title', max_length=100)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
description = models.TextField('Full Detail of the Add')
role = models.TextField('Job Role Detail')
image = models.ImageField(upload_to='item')
status = models.CharField(max_length=50, choices=STATUS, null=True, blank=True)
item_type = models.CharField('Type of Item', max_length=20, choices=ITEM_TYPE, null=True, blank=True)
compensation = models.DecimalField("Conpensation", default='000.00', max_digits=10, decimal_places=2, null=True, blank=True)
price = models.DecimalField("Asking Price", default='000.00', max_digits=10, decimal_places=2, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('item_details', kwargs={'pk': self.pk})
def __str__(self):
return f'{self.name} - {self.user.email}'
class ItemGallery(models.Model):
item = models.ForeignKey(Item, related_name='itemgallery', on_delete=models.CASCADE)
image = models.ImageField(upload_to='gallery')
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f'{self.item.name} - {self.image}'
I am developing an app in Django.
It was working fine until I renamed some fields in my model.
I have run migrate and makemigrations.
Then, when I log in as admin ad try to access "mymodel" in section "myapp", this is what I get:
TypeError at /admin/myapp/glossary_entry/
not enough arguments for format string
What's the problem?
(Everything else in my app works perfectly until it comes to access the model contents inside admin page)
I post the complete error message here:
TypeError at /admin/myapp/glossary_entry/ not enough
arguments for format string Request Method: GET Request
URL: http://127.0.0.1:8000/admin/myapp/glossary_entry/
Django Version: 2.2.2 Exception Type: TypeError Exception Value: not
enough arguments for format string Exception
Location: C:\Users\Tommaso\Django rest framework\Udemy
Django\Myproject\myapp\models.py in str,
line 95 Python Executable: C:\Applicazioni_Tommaso\Phyton\python.exe
Python Version: 3.6.5 Python Path: ['C:\Users\Tommaso\Django rest
framework\Udemy ' 'Django\Myproject',
'C:\Applicazioni_Tommaso\Phyton\python36.zip',
'C:\Applicazioni_Tommaso\Phyton\DLLs',
'C:\Applicazioni_Tommaso\Phyton\lib',
'C:\Applicazioni_Tommaso\Phyton',
'C:\Applicazioni_Tommaso\Phyton\lib\site-packages',
'C:\Applicazioni_Tommaso\Phyton\lib\site-packages\pip-19.1.1-py3.6.egg']
Server time: Sat, 28 Sep 2019 08:56:32 +0000 Error during template
rendering In template
C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\contrib\admin\templates\admin\base.html,
error at line 62
not enough arguments for format string 52 {% endblock %}
53 54 {% endif %} 55 {% endblock %} 56
{% block nav-global %}{% endblock %} 57 58 59 {% block breadcrumbs %} 60 61 {% trans
'Home' %} 62 {% if title %} › {{ title }}{% endif %}
63 64 {% endblock %} 65 {% endif %} 66 67 {%
block messages %} 68 {% if messages %} 69 {% for message in messages %} 70 {{
message|capfirst }} 71 {% endfor %} 72 {%
endif %}
Here is my admin.py:
from django.contrib import admin
from .models import glossary_entry
admin.site.register(glossary_entry)
Here is my model.py:
from django.db import models
from django.utils import timezone
from django.core.exceptions import ValidationError
Admin_approval_switch_choices=[
("show","show"), # 1=valore da inserire negli script (=variabile), 2=valore assunto in relatà nel db
("hide","hide"),
]
class glossary_entry(models.Model):
Lemma = models.CharField(max_length=256, blank=True, null=True)
Acronimo = models.CharField(max_length=25, blank=True, null=True)
Definizione = models.TextField(blank=True, null=True)
Ambito_riferimento = models.CharField(max_length=256, blank=True, null=True)
Autore_definizione = models.CharField(max_length=256, blank=True, null=True)
Posizione_definizione = models.CharField(max_length=256, blank=True, null=True)
Url_definizione = models.URLField(max_length=400, blank=True, null=True)
Titolo_documento_fonte = models.CharField(max_length=256, blank=True, null=True)
Autore_documento_fonte = models.CharField(max_length=256, blank=True, null=True)
Host_documento_fonte = models.CharField(max_length=256, blank=True, null=True)
Url_documento_fonte = models.URLField(max_length=400, blank=True, null=True)
Data_inserimento_entry = models.DateField(blank=False, null=False, default=timezone.now().date() )
Id_statico_entry = models.CharField(max_length=256, blank=False, null=False, default="ITCH00000")
Admin_approval_switch = models.CharField(max_length=30,blank=False, null=False, default=Admin_approval_switch_choices[1], choices=Admin_approval_switch_choices)
class Meta:
ordering = ['-Admin_approval_switch', 'Lemma', 'Id_statico_entry']
def clean(self):
if not (self.Lemma or self.Acronimo or self.Definizione or self.Ambito_riferimento or self.Autore_definizione or self.Posizione_definizione or self.Url_definizione or self.Titolo_documento_fonte or self.Autore_documento_fonte or self.Host_documento_fonte or self.Url_documento_fonte):
raise ValidationError("Non è stata inserita alcuna terminologia. Compilare almeno un campo del form.")
def __str__(self):
return "%s / %s - %s - [%s]" % (self.Lemma, self.Id_statico_entry, self.Admin_approval_switch)
SOLVED:
In the last line of class meta, in model.py:
def __str__(self):
return "%s / %s - %s - [%s]" % (self.Lemma, self.Id_statico_entry, self.Admin_approval_switch)
There is a mismatch in "string inserting tags" and "inserting arguments" (excuse my bad english please).
I substituted the line with:
def __str__(self):
return "%s - %s - [%s]" % (self.Lemma, self.Id_statico_entry, self.Admin_approval_switch)
and now averything works fine.
I have a model like this:
class Slide(models.Model):
slideshow = models.ForeignKey(Slideshow, verbose_name=_('slideshow'), blank=False)
title = models.CharField(_('title'), blank=False, max_length=255)
image = FileBrowseField(_('image'), max_length=255, null=True, blank=True, default=None)
url = models.CharField(_('url'), blank=True, max_length=255)
And in template I do:
{% for slide in slideshow_slides %}
-->> {{ slide.url }}
{% endfor %}
As a result I have the text: -->> google.com and url: mydomain.com/google.com
How to get a url just google.com without such addition as mydomain.com?
If slide.url doesn't have http:// in it then your domain url is added by default.
after searching for a long time without getting an answer i'm gonna try here.
I'm working on django. My project is a mailling system, each time a recipient open a mail i know what mail get opened who opened it and when it get opened.
Here is the table where i display the stats. It shows me every recipient and the datetime, but my problem is that i want to see every recipient once, and then to show how many times it get opened.
<tbody>
{% for stat_mail in stat_mail %}
{% ifchanged stat_mail.recipient %}
<tr>
<td>{{ stat_mail.recipient }}</td>
<td>{{ stat_mail.datetime }}</td>
<td>{{ stat_mail.recipient_set.all|length }}</td>
</tr>
{% endifchanged %}
{% endfor %}
</tbody>
For example :
Test 1 opened the mail at 5PM and at 8PM, so the table should display
Test 1 / 5PM, 8PM / 2
The name of the recipient, the date of the oppening, and the number of oppening.
Sorry for the bad english but i'm french :)
Hope someone can help me, if u have other question or need more code just ask.
Thanks a lot !
EDIT : My models.py
class Recipient(models.Model):
name = models.CharField(max_length=255, verbose_name= ('Nom'), null=True, blank=True)
first_name = models.CharField(max_length=255, verbose_name= ('Prénom'), null=True, blank=True)
mail = models.EmailField(verbose_name= ('Adresse du destinataire'))
def __unicode__(self):
return u'%s %s' % (self.name, self.first_name)
class Tag(models.Model):
name = models.CharField(max_length=255, blank=False)
recipients = models.ManyToManyField(Recipient, verbose_name='Destinataires', null=False, blank=False, related_name="tags")
def __unicode__(self):
return self.name
class Mail(models.Model):
subject = models.CharField(max_length=255, verbose_name= ('Sujet'), blank=False, null=False)
content = HTMLField(verbose_name= ('Contenu'), blank=False, null=False, default=' ')
tags = models.ManyToManyField(Tag, verbose_name= ('Destinataires'), null=True, blank=True, related_name='mails')
recipients = models.ManyToManyField(Recipient, verbose_name='Destinataires', null=True, blank=True, related_name='mails')
date_create = models.DateTimeField(verbose_name= ('Date de création'), default=datetime.now, blank=False, editable = False)
writer = models.ForeignKey(Intervenant, verbose_name= ('Personne écrivant la compagne'), null=True, blank=True)
holding = models.ForeignKey(Holding, verbose_name= ('Organisation'),related_name= ('Questionnaire_mail'), null=False, blank=False, default=1, editable = False)
sended = models.BooleanField(verbose_name = ('Compagne envoyée ?'), default=False, editable=False)
opened = models.IntegerField(verbose_name=("Nombre totale d'ouverture"), default=0, editable=False)
email = models.EmailField(verbose_name='Destinataire de Test', blank=True, null=True)
date_create = models.DateTimeField(verbose_name= ('Date de création'), default=datetime.now, blank=False, editable = False)
date_sent = models.DateTimeField(verbose_name= ('Date de création'), blank=True, null=True, editable = False)
def __unicode__(self):
return self.subject
class Mail_Stats(models.Model):
mail = models.ForeignKey(Mail, verbose_name= ('Compagne'), related_name='mails_stats')
recipient = models.ForeignKey(Recipient, verbose_name= ('Destinataires'), null=True, blank=True, related_name='mails_stats')
datetime = models.DateTimeField(verbose_name= ('Date et Heure'), auto_now_add=True)
You should prepare your data in the view and then pass it to the template. Something like this (untested):
from django.shortcuts import render
from .models import Mail_Stats
def stats_view(request):
recipient_list = [] # this will be put in the template context
current_recipient = None
cnt_read = 0
read_datetime_list = []
for stat in Mail_Stats.objects.all().order_by('mail', 'recipient'):
if stat.recipient != current_recipient:
if cnt_read > 0:
recipient_list.append({
'recipient': current_recipient,
'read_datetime_list': read_datetime_list,
'cnt_read': cnt_read
})
current_recipient = stat.recipient
cnt_read = 0
read_datetime_list = []
cnt_read += 1
read_datetime_list.append(stat.datetime)
# add last recipient to the list, if not None
if current_recipient is not None:
recipient_list.append({
'recipient': current_recipient,
'read_datetime_list': read_datetime_list,
'cnt_read': cnt_read
})
render(request, 'mail_stats.html', { 'recipient_list': recipient_list })
Then in your template you could simply do something like this:
<tbody>
{% for r in recipient_list %}
<tr>
<td>{{ r.recipient }}</td>
<td>
<ul>
{% for dt in r.read_datetime_list %}
<li>{{ dt }}</li>
{% endfor %}
</ul>
</td>
<td>{{ r.cnt_read }}</td>
</tr>
{% endfor %}
</tbody>
The important thing is: do not struggle doing complex stuff in templates, keep them only for presentation purposes. Move all logic in the view (or models, or utility modules), there you can leverage all the power of Python.
I've got a dJango webform from a model with some error checking (valid email field,etc).
Everything works fine in various browsers Opera,Camino,Netscape,Safari and IE (except IE7).
All I get in IE7 is the 'Internet Explorer cannot display the webpage' message. If the forms valid the data gets written to the database so I think its something to do with the redirect stage.
I've tried various things method=get and javascript form submission but nothing seems to stop IE7 giving me this error.
Any help would be appreciated.
forms.py
class NewElectiveForm(ModelForm):
host_country = forms.CharField(widget=forms.widgets.Select(choices=COUNTRIES) , label="Destination")
host_type = forms.CharField(widget=forms.widgets.Select(choices=HOST_TYPE) , label="Location type")
host_name = forms.CharField(max_length=256, label="Name of host institution")
host_street = forms.CharField(required = False, max_length=100, label="Street")
host_city = forms.CharField(required = False, max_length=100, label="City")
host_district = forms.CharField(required = False, max_length=100, label="District")
host_zipcode = forms.CharField(required = False, max_length=100, label="Zipcode")
host_supervisor = forms.CharField(required = False, max_length=256, label="Name of supervisor")
host_email = forms.EmailField(required = False, max_length=100, label="Email")
host_fax = forms.CharField(required = False, max_length=100, label="Fax.No.")
host_tel = forms.CharField(required = False, max_length=100, label="Tel.No.")
start_date = forms.DateField(widget=SelectDateWidget(),label="Elective start date")
end_date = forms.DateField(widget=SelectDateWidget(),label="Elective end date")
subject = forms.CharField(required = False, max_length=256,label="Subject")
reasons = forms.CharField(required = False, widget=forms.widgets.Textarea(attrs={'class':'question'}), label="Please state briefly the reasons for this choice's location and subject")
outcomes = forms.CharField(required = False, widget=forms.widgets.Textarea(attrs={'class':'question'}), label="Please give upto to 4 outcomes that you hope to achieve during this elective")
your_mobile = forms.CharField(required = False, max_length=100, label="Please provide your mobile number if you are taking it with you")
insurance = forms.BooleanField(required = False, label="Please confirm that you have arranged holiday insurance")
malpractice = forms.BooleanField(required = False, label="Please confirm that you have medical malpractice cover")
groupinfo = forms.CharField(required = False, label="If you planning your Elective in a group, please list your fellow students")
#risk_upload = forms.FileField(widget=AdminFileWidget, required = False, label='Upload a completed risk assesment form')
#evidence_upload = forms.FileField(widget=AdminFileWidget, required = False, label='Upload an evidence document')
class Meta:
model = ElectiveRecord
exclude = ('id', 'review','elective', 'status', 'edit_userid','modified')
html template:
<form enctype="multipart/form-data" method="post" class="uniForm" id="newform" >
{% for i in form %}
<div class="fieldwrapper {% for error in i.errors %} error {% endfor %}">
{% for error in i.errors %}
<b>{{error|escape}}</b><br/>
{% endfor %}
{{ i.label_tag }} :
{% if i.html_name == "reasons" or i.html_name == "outcomes" %} <br/> {% endif %}
{{ i }}
{% if i.html_name == "evidence_upload" %} <br/>latest file= xxx {% endif %}
{% if i.html_name == "risk_upload" %} <br/>latest file= xxx {% endif %}
</div>
{%endfor%}
<div class="fieldWrapper"> <input type="submit" value="Save" NAME='save' > </div>
</form>
models.py
class ElectiveRecord(models.Model):
elective = models.ForeignKey(Elective, null=True, blank=True)
status = models.CharField(choices=ELECTIVE_STATUS_FLAGS, max_length=40)
edit_date = models.DateTimeField(auto_now_add=True)
edit_userid = models.CharField(max_length=12)
host_country = models.CharField(max_length=100, help_text="Destination")
host_type = models.CharField(choices=HOST_TYPE, max_length=10, help_text="Location type")
host_name = models.CharField(max_length=256, help_text="Name of host institution")
host_street = models.CharField(max_length=100, help_text="Street")
host_city = models.CharField(max_length=100, help_text="City")
host_district = models.CharField(max_length=100, help_text="District")
host_zipcode = models.CharField(max_length=100, help_text="Zipcode")
host_supervisor = models.CharField(max_length=256, help_text="Name of supervisor")
host_email = models.CharField(max_length=100, help_text="Email")
host_fax = models.CharField(max_length=100, blank=True, help_text="Fax.No.")
host_tel = models.CharField(max_length=100, help_text="Tel.No.")
start_date = models.DateField(help_text="Elective start date")
end_date = models.DateField(help_text="Elective end date")
subject = models.CharField(max_length=256,help_text="Tel.No.")
reasons = models.TextField(help_text="Please state briefly the reasons for this choice's location and subject")
outcomes = models.TextField(help_text="Please give upto to 4 outcomes that you hope to achieve during this elective")
your_mobile = models.CharField(max_length=100, blank=True, help_text="Please provide your mobile number if you are taking it with you")
insurance = models.BooleanField(default=False, help_text="Please confirm that you have arranged holiday insurance")
malpractice = models.BooleanField(default=False, help_text="Please confirm that you have medical malpractice cover")
groupinfo = models.CharField(max_length=256, blank=True, help_text="If you planning your Elective in a group, please list your fellow students")
modified = models.DateTimeField(auto_now_add=True)
class Meta:
get_latest_by = 'modified'
def __unicode__(self):
return u"[%s] %s, %s " % (self.id,self.host_name,self.subject)
Confirm that it's the redirect stage that's causing the problem by replacing
HttpResponseRedirect(url)
with
HttpResponse('<!DOCTYPE html><html><head><title>title</title></head><body>%(url)s</body></html>' % {'url':url})
If this doesn't render, then the problem is happening before the redirect. If it does render, then the problem may be the redirect, or it may be the redirected page. Click on the link. If the next page displays correctly, the problem is almost certainly the redirect itself. Otherwise, the problem is in the redirected page.