Форум сайта python.su
class Model1(models.Model):
pass
class Model2(models.Model):
model1 = models.ForeignKey(Model1)
class Model3(models.Model):
model2 = models.ForeignKey(Model2)
def model1_delete_handler(sender, instance, **kwargs):
if instance.model2_set.all().count() != 0:
...
def model2_delete_handler(sender, instance, **kwargs):
if instance.model3_set.all().count() != 0:
...
signals.pre_delete.connect(model1_delete_handler, sender=Model1, dispatch_uid = 'model1_delete')
signals.pre_delete.connect(model2_delete_handler, sender=Model2, dispatch_uid = 'model2_delete')
from django.db.models import FileField as DjFileField
class FileField(DjFileField):
# блокирую сохранение
def pre_save(self, model_instance, add):
return getattr(model_instance, self.attname)
# генератор пути к файлу
def generate_filename(self, instance, filename):
return os.path.join(self.upload_to,
str(instance.id),
self.get_filename(filename))
class ItemImage(models.Model):
file = ImageField(upload_to="uploads")
def save(self, *args, **kwargs):
super(ItemImage, self).save(*args, **kwargs)
if self.file:
# генерирую имя и повторно сохраняю
self.file.name = self.file.field.generate_filename(self, self.file.name)
self.file.save(self.file.name, self.file, save=False)
ItemImage.objects.filter(id=self.id).update(file=self.file)
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args):
loader = QUiLoader()
file = QFile('file.ui')
file.open(QFile.ReadOnly)
myWidget = loader.load(file, self)
file.close()
self.addWidget(myWidget)
def main():
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
class Task(Named):
proj = models.ForeignKey(Proj)
type = models.ForeignKey(TaskType)
tags = models.ManyToManyField(Tag, null=True, blank=True)
description = models.TextField(blank=True)
TASK_RELATINGS = (
(0, 'косвенно зависит'),
(1, 'включает в себя'),
(2, 'является частью'),
(3, 'является следствием'),
(4, 'является предшедственником'),
)
class TaskRelating(Named):
task_from = models.ForeignKey("Task", related_name="from_task")
task_to = models.ForeignKey("Task", related_name="to_task")
description = models.TextField(blank=True)
tags = models.ManyToManyField(Tag, null=True, blank=True)
type = models.IntegerField(choices=TASK_RELATINGS)
class Proj(Named):
authors = models.ManyToManyField(User)
tags = models.ManyToManyField(Tag, null=True, blank=True)
specifications = models.TextField(blank=True)
projects = Proj.objects.filter(authors=user)
for project in projects:
project.tasks = Task.objects.filter(proj=project)
class FlatSell(models.Model):
#...
class Image(models.Model):
#...
owner = models.ForeignKey(FlatSell, blank=True, null=True)
def upload(request, owner_id, form_class=PhotoUploadForm,
template_name="upload.html"):
# upload form for photos
#
photo_form = form_class()
if request.method == 'POST':
if request.POST["action"] == "upload":
photo_form = form_class(request.user, request.POST, request.FILES)
if photo_form.is_valid():
photo = photo_form.save(commit=False)
photo.ownerflat = owner_id
photo.save()
request.user.message_set.create(message=_("Successfully uploaded photo '%s'") % photo.title)
return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))
return render_to_response(template_name, {
"photo_form": photo_form,
}, context_instance=RequestContext(request))
LOGIN_URL = '/login/'
LOGOUT_URL ='/logout/'
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
{% block breadcrumbs %}<div class="breadcrumbs"><a href="/">{% trans 'Home' %}</a>{% if title %} › {{ title }}{% endif %}</div>{% endblock %}
from django.conf.urls.defaults import *
urlpatterns = patterns('',
('^pages/', include('django.contrib.flatpages.urls')),
)
from django.core.urlresolvers import reverse
reverse('django.contrib.flatpages.views.flatpage', kwargs={'url': '/about-us/'})
# Gives: /pages/about-us/
<a href='{% url django.contrib.flatpages.views.flatpage url="/about-us/" %}'>About Us</a>
urlpatterns = patterns('',
('^pages/', include('django.contrib.flatpages.urls')),
)
class A():
def af(self):
def bf():
print 'bf'
bf()
a = A()
def cf(x,y):
print 'cf'
#
a.af.bf = cf
#
a.af()
>>> 'cf'
import smtplib
from email.MIMEText import MIMEText
from extract import MAILS
def send(to):
you = to
# текст письма
text = 'Здравствуйте!'
# заголовок письма
subj = 'САБЖ'
server = "smtp.km.ru"
name,pwd,me = "pythont","123456","pythont@km.ru"
user_name = name
user_passwd = pwd
msg = MIMEText(text, "", "utf-8")
msg['Subject'] = subj
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP(server, port)
s.starttls()
s.login(user_name, user_passwd)
s.sendmail(me, you, msg.as_string())
s.quit()
send("youmail@yandex.ru")
client = suds.client.Client(WSDLfile)
client.service.Login('mylogin', 'mypass')
print client.options.transport.cookiejar
<cookielib.CookieJar[<Cookie sessnum=9WAXQ25D37XY535F6SZ3GXKSCTZG8CVJ for .IP.IP.IP.IP/>]>
<cookielib.CookieJar[]>
# -*- coding: utf-8 -*-
import pythoncom, pyHook
import codecs, sys, os
outf = codecs.getwriter('cp866')(sys.stdout, errors='replace')
sys.stdout = outf
def OnKeyboardEvent(event):
print event.Ascii
if event.KeyID == 192:
exit(1)
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
class srcTableModel(QtCore.QAbstractTableModel):
def __init__(self, fileName = QtCore.QString()):
super (srcTableModel, self).__init__()
self.ships = []
self.fileName = fileName
self.dirty = True
def rowCount (self, index=QtCore.QModelIndex()):
return len(self.ships)
def columnCount (self, index=QtCore.QModelIndex()):
return 11
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return
if orientation == QtCore.Qt.Horizontal:
if section == EQUIPMENT:
return (QtGui.QApplication.translate("MainWindow", "Виробництво", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCCODE:
return (QtGui.QApplication.translate("MainWindow", "№ дж.", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCNAME:
return (QtGui.QApplication.translate("MainWindow", "Найменув. дж.", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCX1:
return (QtGui.QApplication.translate("MainWindow", "X,м", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCY1:
return (QtGui.QApplication.translate("MainWindow", "Y,м", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCTYPE:
return (QtGui.QApplication.translate("MainWindow", "Тип дж.", None, QtGui.QApplication.UnicodeUTF8))
elif section == ZONESIZE:
return (QtGui.QApplication.translate("MainWindow", "Розмір СЗЗ", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCHEIGHT:
return (QtGui.QApplication.translate("MainWindow", "Висота дж., м", None, QtGui.QApplication.UnicodeUTF8))
elif section == SRCDIAMETER:
return (QtGui.QApplication.translate("MainWindow", "Діаметер дж., м", None, QtGui.QApplication.UnicodeUTF8))
elif section == GASDEPLETION:
return (QtGui.QApplication.translate("MainWindow", "Витрата ПГВС, м3/с", None, QtGui.QApplication.UnicodeUTF8))
elif section == GASTEMPERATURE:
return (QtGui.QApplication.translate("MainWindow", "Темпер. ПГВС", None, QtGui.QApplication.UnicodeUTF8))
return int(section + 1)
def data (self, index, role=QtCore.Qt.DisplayRole):
if index.isValid() and 0 <= index.row() < len(self.ships):
ship = self.ships [index.row()]
column = index.column()
if role == QtCore.Qt.DisplayRole:
if column == EQUIPMENT:
return QtCore.QVariant(ship.equipment)
elif column == SRCCODE:
return QtCore.QVariant(ship.srcCode)
elif column == SRCNAME:
return QtCore.QVariant(ship.srcName)
elif column == SRCX1:
return QtCore.QVariant(ship.srcX1)
elif column == SRCY1:
return QtCore.QVariant(ship.srcY1)
elif column == SRCTYPE:
return QtCore.QVariant(ship.srcType)
elif column == ZONESIZE:
return QtCore.QVariant(ship.zoneSize)
elif column == SRCHEIGHT:
return QtCore.QVariant(ship.srcHeight)
elif column == SRCDIAMETER:
return QtCore.QVariant(ship.srcDiameter)
elif column == GASDEPLETION:
return QtCore.QVariant(ship.gasDepletion)
elif column == GASTEMPERATURE:
return QtCore.QVariant(ship.gasTemperature)
return
def flags(self, index):
if not index.isValid():
return QtCore.Qt.ItemIsEnabled
return QtCore.Qt.ItemFlags(QtCore.QAbstractTableModel.flags(self, index)|QtCore.Qt.ItemIsEditable)
def setData (self, index, value, role=QtCore.Qt.DisplayRole):
if index.isValid() and 0 <= index.row() < len (self.ships):
ship = self.ships [index.row()]
column = index.column()
if column == EQUIPMENT:
ship.equipment = value.toString()
elif column == SRCCODE:
value, ok = value.toInt()
if ok:
ship.srcCode = value
elif column == SRCNAME:
ship.srcName = value.toString()
elif column == SRCX1:
value, ok = value.toInt()
if ok:
ship.srcX1 = value
elif column == SRCY1:
value, ok = value.toInt()
if ok:
ship.srcY1 = value
elif column == SRCTYPE:
ship.srcType = value.toString()
elif column == ZONESIZE:
value, ok = value.toInt()
if ok:
ship.zoneSize = value
elif column == SRCHEIGHT:
value, ok = value.toInt()
if ok:
ship.srcHeight = value
elif column == SRCDIAMETER:
value, ok = value.toInt()
if ok:
ship.srcDiameter = value
elif column == GASDEPLETION:
value, ok = value.toInt()
if ok:
ship.gasDepletion = value
elif column == GASTEMPERATURE:
value, ok = value.toInt()
if ok:
ship.gasTemperature = value
self.dirty = True
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
return True
return False
def insertRows (self, position, rows=1, index=QtCore.QModelIndex()):
self.beginInsertRows(QtCore.QModelIndex(), position, position + rows - 1)
for row in range(rows):
self.ships.insert(position + row, srcShip("Unknown", 0, "Unknown", 0, 0, "Unknown", 0, 0, 0, 0, 0))
self.endInsertRows()
self.dirty = True
return True
def removeRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginRemoveRows(QtCore.QModelIndex(), position, position + rows - 1)
self.ships = self.ships[:position] + self.ships [position + rows:]
self.endRemoveRows()
self.dirty = True
return True
def loadFile(self, fileName):
exception = None
fh = None
self.fileName = QtCore.QString(fileName)
try:
if self.fileName.isEmpty():
raise IOError, "no fileName specified for loading"
fh = QtCore.QFile(self.fileName)
if not fh.open(QtCore.QIODevice.ReadOnly):
raise IOError, unicode(fh.errorString())
stream = QtCore.QDataStream(fh)
magic = stream.readInt32()
if magic != MAGIC_NUMBER:
raise IOError, "unrecognized file type"
fileVersion = stream.readInt16()
if fileVersion != FILE_VERSION:
raise IOError, "unrecognized file type version"
stream.setVersion(QtCore.QDataStream.Qt_4_5)
self.ships = []
while not stream.atEnd():
equipment = QtCore.QString()
stream >> equipment
srcCode = stream.readInt32()
srcName = QtCore.QString()
stream >> srcName
srcX1 = stream.readInt32()
srcY1 = stream.readInt32()
srcType = QtCore.QString()
stream >> srcType
zoneSize = stream.readInt32()
srcHeight = stream.readInt32()
srcDiameter = stream.readInt32()
gasDepletion = stream.readInt32()
gasTemperature = stream.readInt32()
self.ships.append(srcShip(equipment, srcCode, srcName, srcX1, srcY1, srcType, zoneSize, srcHeight, srcDiameter, gasDepletion, gasTemperature))
self.reset()
self.dirty = False
except (IOError, OSError), e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception
def saveFile(self):
exception = None
fh = None
try:
if self.fileName.isEmpty():
self.fileName = QtGui.QFileDialog.getSaveFileName(None, "Ships - Choose Save File", "", "Trianon project (*.tri)")
fh = QtCore.QFile(self.fileName)
if not fh.open(QtCore.QIODevice.WriteOnly):
raise IOError, unicode(fh.errorString())
stream = QtCore.QDataStream(fh)
stream.writeInt32(MAGIC_NUMBER)
stream.writeInt16(FILE_VERSION)
stream.setVersion(QtCore.QDataStream.Qt_4_5)
for ship in self.ships:
stream << QtCore.QString(ship.equipment)
stream.writeInt32(ship.srcCode)
stream << QtCore.QString(ship.srcName)
stream.writeInt32(ship.srcX1)
stream.writeInt32(ship.srcY1)
stream << QtCore.QString(ship.srcType)
stream.writeInt32(ship.zoneSize)
stream.writeInt32(ship.srcHeight)
stream.writeInt32(ship.srcDiameter)
stream.writeInt32(ship.gasDepletion)
stream.writeInt32(ship.gasTemperature)
self.dirty = False
except IOError, e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception
Mb-3:mysite dmitryvinogradov$ python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute
self.validate()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in <module>
backend = load_backend(settings.DATABASE_ENGINE)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend
return import_module('.base', 'django.db.backends.%s' % backend_name)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 13, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dynamic module does not define init function (init_mysql)
Mb-3:mysite dmitryvinogradov$ easy_install MySQL-python
Searching for MySQL-python
Best match: MySQL-python 1.2.3c1
Processing MySQL_python-1.2.3c1-py2.6-macosx-10.3-fat.egg
MySQL-python 1.2.3c1 is already the active version in easy-install.pth
Using /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.3-fat.egg
Processing dependencies for MySQL-python
Finished processing dependencies for MySQL-python
import curses
screen = curses.initscr()