How to pull out the form value only in newforms:
It’s formfield.data
I keep finding myself trying things like formfield.value formfield.val (javascript) and always forget that it’s called “data”.
Enjoy.
Yuji's Increasingly Infrequent Ramblings
How to pull out the form value only in newforms:
It’s formfield.data
I keep finding myself trying things like formfield.value formfield.val (javascript) and always forget that it’s called “data”.
Enjoy.
I got this error recently in my urls.py.
We should naturally be looking for a string in our urls.py (error says str object) and I found that my comment “”” “””” was being the issue.
I’m used to placing a lone string at the beginning of a class or function, but in this case it was in the middle of defining the urlpatterns, so the url parser actually tried to read my string comment.
Just a heads up.
UPDATE:
If you are looking for pydev on Aptana 3 beta, refer here: https://yuji.wordpress.com/2010/06/11/aptana-3-python-support-pydev-on-aptana-3-beta/
I’ve done this a few times, but each time I forget the process. I always end up at the PyDev site and then find my way in Aptana.
You just need to go to Help > Install New Software
In the tooltip that pops up, hit hte checkbox next to Aptana PyDev, and follow the instructions as you continue through the guided installation.
Awesome integration.
By the way, I had an issue where the default editor for .py was set to something other than the “python” editor. Make sure it has been set.
If you’re adding or modifying a column in Postgres and you get this error, maybe it’s because you are changing a type to NOT NULL but the column already exists, with null values, or you’re adding one and the default is in fact NULL. That means you have to specify a default value for the field.
For example, I just added an integer field to a table called newsletter_newsletter:
ALTER TABLE newsletter_newsletter ADD COLUMN opened integer NOT NULL default 0;
Sometimes, I forget.
PostgreSQL is a sleeping giant that will one day break and destroy me. I just sit here hoping it runs smoothly, forever.
I I’m not sure why there are so few results for googling this. Editing foreign keys directly, or at least taking us to the model in question I’ve wanted to do since the first day I used django. I’m finding it very difficult to search for so I’ll add it here. I had to pull out the patch filename to find it again. I wonder why?
The data for a forward relationship (Model A FK –> Model B) should positively identify the target model so I don’t know why a link option hasn’t been built in, because I know tons of people would appreciate that built-in functionality.
This patch will place an edit icon next to the “add” icon for direct foreign links, allowing you to edit an FK in the same manner: a pop up window.
Here’s the ticket that I used to patch my django on my dev server. So far, so good. Has it been merged into 1.1? That would make this useless.
http://code.djangoproject.com/ticket/11397
Go to your directory that CONTAINS django (for example, django-trunk if you used SVN) and download the patch.
http://code.djangoproject.com/attachment/ticket/11397/add_edit_icon.diff
Type:
wget http://code.djangoproject.com/attachment/ticket/11397/add_edit_icon.diff
patch -p1 add_edit_icon.diff
Patch is not my cup of tea, but assuming django hasn’t changed too much, the command should install the patch. Type ‘man patch’ for details on the -pnum argument. I barely know this thing so I can’t say much more.
Ever needed to set up a django admin form with extra validation? For example, you might be creating a form to create multiple objects at once. Perhaps your Client model needs to create a User during the Add view.
Perhaps your Affiliate model needs to generate a Client model and User in the Add view, and allow the user to edit those same models from one Change view.
All of the above can be accomplished with a custom admin form.
ModelAdmins can specify a “form” attribute that overrides the default ModelForm used by the admin add/change views.
We can use this override to set up a ModelForm that intelligently validates the extra non model fields and also saves the related models correctly.
class MyForm(forms.ModelForm):
extra_field = forms.CharField()
class Meta:
model = MyModel
class MyAdmin(admin.ModelAdmin):
form = MyForm
Our admin form now contains an extra required field – “extra_field”.
To add or edit a related model, we need to modify the form to do a useful __init__ and a useful save().
In our __init__ function we need to fill the initial dict with the existing model fields. In our save function we need to write the data to our related model.
You will need to adapt the code to your specific scenario, as a related model can be “related” in any number of ways. A simple foreign key? A reverse relation? It could even be a relation not specified in the model.
class MyForm(forms.ModelForm):
related_model_field1 = forms.CharField()
related_model_field2 = forms.CharField()
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance.id:
related_model = get_related_model() # pull related model somehow
self.initial.update({
'related_model_field1': related_model.field1,
'related_model_field2': related_model.field2,
})
def save(self, *args, **kwargs):
if self.instance.id:
related_model = self.instance.related_model
else:
related_model = RelatedModel()
related_model.related_model_field1 = self.cleaned_data.get('related_model_field1')
related_model.related_model_field2 = self.cleaned_data.get('related_model_field2')
related_model.save()
self.instance.related_model = related_model # adapt to your relation
super(MyForm, self).save(*args, **kwargs)
class MyAdmin(admin.ModelAdmin):
form = MyForm
We’re only doing a few things: validating the new fields in your ModelForm, automatically creating the related model OR updating it if it already exists, and finally populating the initial data if the model is being edited.
As we use more and more fields, explicitly specifying each field and value in the __init__ and save function takes more and more lines of code.
I tend to use a dictionary mapping local form field names to the related object field names so that I can simply use a few list comprehensions to handle the __init__ and save() code.
class MyForm(forms.ModelForm):
related_model_field1 = forms.CharField()
related_model_field2 = forms.CharField()
RELATED_FIELD_MAP = {
# map local field names to the object field names.
'related_model_field1': 'field1',
'related_model_field2': 'field2',
}
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance.id:
related_model = get_related_model() # pull related model somehow
self.initial.update(
dict([(field, getattr(related_model, target_field) for field, target_field in self.RELATED_FIELD_MAP.iteritems())]))
def save(self, *args, **kwargs):
related_model = self.instance.related_model if self.instance.id else RelatedModel()
[setattr(related_model, target_field, self.cleaned_data.get(field) for
field, target_field in self.RELATED_FIELD_MAP.iteritems()]
related_model.save()
self.instance.related_model = related_model # adapt to your relation..
super(MyForm, self).save(*args, **kwargs)
class MyAdmin(admin.ModelAdmin):
form = MyForm
You can be even more DRY by setting up your RELATED_FIELD_MAP to contain “target_field, forms.CharField()” values and instantiate the form manually with the fields.
Using the concepts from this post, you can use the django admin application to generate much more complex, multi-object edit/add forms that appear as one form.
It’s supremely useful when you still want to use the admin interface for 90% of what you do.
Apache2 eats up a lot of memory. It must be configured, and the configuration options are confusing. In fact, all server admin stuff is confusing. The work these guys do is ridiculous. I will learn more one day, but I do freak out once every while when I’m forced to deal with the server.
Suddenly, my dev server was CRAWLING and I could barely get anything done. It turned out it was because apache2 started spawning a lot of processes due to the load.
To check… type in the following
ps -auxf | sort -nr -k 4 | head -10
or alternatively, just use top and sort by memory usage.
Your apache processes should be up there at the top of the memory consumers. If you see multiple apache2 servers running, and it’s overkill, or if you’re on a small server (my dev server is 256mb, so apache2 needs to be scaled back) reduce the number of servers it spawns.
The result should be like so:
www-data 31759 1.5 11.9 218156 31384 ? S 02:53 0:03 \_ /usr/sbin/apache2 -k start www-data 31750 1.3 11.2 218088 29492 ? S 02:52 0:03 \_ /usr/sbin/apache2 -k start www-data 31742 1.2 10.8 219516 28420 ? S 02:51 0:03 \_ /usr/sbin/apache2 -k start www-data 31743 1.3 8.6 220880 22736 ? S 02:51 0:03 \_ /usr/sbin/apache2 -k start www-data 31746 1.1 7.5 218056 19828 ? S 02:51 0:03 \_ /usr/sbin/apache2 -k start root 31733 0.0 1.2 140892 3176 ? Ss 02:51 0:00 /usr/sbin/apache2 -k start www-data 31741 0.0 0.3 27976 996 ? S 02:51 0:00 \_ nginx: worker process www-data 31739 0.0 0.3 27872 836 ? S 02:51 0:00 \_ nginx: worker process root 31786 0.0 0.3 14780 1000 pts/1 R+ 02:56 0:00 \_ ps -auxf root 30330 0.0 0.3 17620 1040 pts/1 Ss Feb11 0:00 \_ -bas
If there are multiple apache processes at the top, you can get rid of most of them if your site doesn’t get much traffic. This is especially important if you are trying to squeeze out every last drop from your server.
So, to reduce the processes generated:
Edit your apache configs, usually in /etc/apache2/apache2.conf
In the mpm_prefork_module settings, set StartServers to 1, MinSpares to 1 or 0, and MaxSpares to something like 3.
For example, 5 processes running will destroy my 256mb server, which is the default minimum for Apache2.
<IfModule mpm_prefork_module>
StartServers 1
MinSpareServers 1
MaxSpareServers 3
MaxClients 150
MaxRequestsPerChild 500
Change the above settings as you test traffic loads to see whether the new settings can handle it. My setup is for very little traffic.
Hola!
I just finished some email tracking software, and I’m going to explain very quickly how it works.
My newsletter sender appends a specific image to the end of the email, with a specific get request that identifies the recipient.
Lets say I have a subscriber model, full of emails. I send the email: “Hello”
subscriber = Subscriber(email='yuji@anuvawines.com', name='Yuji Tomita') subject = 'testing open tracking' body = "hello' new_body = body + '<img src="/open-tracking/?id=%s" />' % (subscriber.id) send_html_mail(subject, new_body, "from@anuvawines.com", [subscriber.email])
This sends an email with an image embedded that identifies the subscriber.
Now, for the view to handle the image request. It must return a valid image or else your html email will often have a broken image icon. Here’s how to pass back an image in django:
def track-open-emails(request):
if 'id' in request.GET:
#do something with the id, which tells you that specific subscriber has opened the email.
#do something to record that an email has been opened.
image_data = open("/path_to_image/", 'rb').read()
return http.HttpResponse(image_data, mimetype="image/png")
done!
One solution: drag the buzz icon to your extra labels area so it’s out of the way.
The second way is to scroll to the bottom, and the option is next to the other Gmail options.
Gmail view: standard | turn on chat | turn off buzz | older version | basic HTML Learn more
This is going to be deadly as more people start using it. I check it like I check my email. I have my gmail on my right monitor all day. My eye glances towards the inbox indicator once every minute at least.
NOT GOOD. But I can’t turn it off yet. It’s new and exciting.
Add the option ‘relative_urls’: ‘false’ to disable the auto absolute-to-relative link changing behavior.
This wiki lists all types of URL converting here… but I’m still having issues. I’ve tried all of them.
I’ve heard of issues with IE auto formatting links, but I’m using Chrome. I’m trying to write an img address for a newsletter, which will obviously fail if i use a relative link.
WWaaait a minute.. Why doesn’t this link fail? >_>
/blah/ is reaching my server from refreshing gmail.. does it automatically determine the domain from email headers or something??