Snippet List
I don't know if you noticed but GenericForeignKey behaves badly in some situations. Particularly if you assign a not yet saved object (without pk) to this field then you save this object the fk_field does not get updated (even upon saving the model)- it's updated only upon assigning object to the field. So you have to save the related object prior to even **assigning** it to this field. It's get even more apparent when you have null=True on the fk/ct_fields, because then the null constrains won't stop you from saving an invalid object. By invalid I mean an object (based on a model with GFK field) which has ct_field set but fk_field=None.
Maybe this problem is irrelevant in most use case scenarios but this behaviour certainly isn't logical and can introduce silent bugs to your code.
- genericforeignkey
- contenttypes
My previous snippet with captcha wasn't very portable but Marco Fucci figured out the thing that I couldn't - value_from_datadict function. So all credits go to him and his snippet, I adapted it to my needs, maybe you like my version better - it doesn't need any captcha libraries and let's you modify the widget's html easily. Also I added an option to pass remoteip to google api's verify method.
How to use it:
In your settings.py add:
RECAPTCHA_PUBKEY = 'your recaptcha public key'
RECAPTCHA_PRIVKEY = 'your recaptcha private key'
After that just import and use ReCaptchaField in your form as you would any other field. That's it.
*** Important *** If you want to have peace of mind in case google decided that the remoteip parametr is mandatory then:
Derive every form that has the captcha field from ReCaptchaForm and when you create the form object after receiving POST/GET, pass a remoteip parameter like that:
form = YourCaptchaForm(data=request.POST, remoteip=request.META['REMOTE_ADDR'])
It is not so portable and easy as I wanted it to be because of how django forms work - they don't play well with recaptcha.
To get it to work:
* Add two variables to your app settings, **RECAPTCHA_PUBKEY** and **RECAPTCHA_PRIVKEY**
* Derive forms you want to have a captcha from the provided `ReCaptchaForm` class (how to get it working with ModelForm? any ideas?)
* * If you override the form's clean method make sure you firstly call the `ReCaptchaForm`'s clean method *
* In your view, upon receiving the form data initialize the objects like this `form = YouFormClassDerivedFromReCaptchaForm(remoteip=request.META['REMOTE_ADDR'], data=request.POST)` (or request.GET of course) - this is because reCaptcha needs the user's remote ip.
pinkeen has posted 3 snippets.