Django Mixing State Between Forms - django

I have a strange issue I've never seen before and I'm a bit stuck at where to go next.
We have a fairly standard Django app, with some forms using class based views, and we're finding that state is getting mixed between forms in strange ways.
For example, User A is on the site and fills out form X and sets their postcode.
User B goes to another form altogether, form Y, but the postcode field is already populated with User A's postcode.
The fields share the same name, but are on totally independent forms. The field in this example is a standard Django CharField.
I haven't managed to replicate this behaviour using the Django dev server locally from a little trying. I've upgraded gunicorn to latest version, I've set it to use a single worker, I've disabled caching everywhere in the Django project that I can find.
It's stuck on Django 1.3.7, and it's not a trivial app to upgrade to a supported version. It's running with gunicorn 18 behind nginx.
I've noted the Django mentions of thread safety in class based views, but I don't see us passing any mutable objects to the view, and it's all a fairly plan view and ModelForm. Django's session store is the default (it was previously something else but I removed that to use the Django default which I believe is the db).
Any ideas where to go next to try and figure this out?
Thanks!

Figured it out - turns out it was to do with the behaviour of get_initial in 1.3, which was changed in Django 1.4
https://docs.djangoproject.com/en/dev/releases/1.4/#formmixin-get-initial-returns-an-instance-specific-dictionary
We changed our get_initial to use a copy of the dict rather than the default implementation, and now all is well :)

Related

Django: Last modified by and created by user automatic saving

The age-old question: How can I automatically save last_modifed_user in django models?
I found in several places this general process how to do it using thread local. I'm hesitant to simply implement it that way because I'm not entirely sure of the consequences it has and because all these posts are old.
Is using thread local still the "recommended" way of doing this in django 3? Or does django3 have a better options of doing it?
No, this hasn't changed. Simply because separation of concern is an architectural principle of MVC (model-view-controller), which is also how Django (model-view-template) and most web frameworks with ORM are architected. Models know nothing about the request, it's not available (and in many cases there isn't a request at all when a model is saved, think of management commands or regular tasks running in the background).
The alternative to thread local is to make sure you implement it yourself in the controller layer (view layer in Django):
Create a view mixin that you can mix with all the generic views that use the ModelFormMixin to save the user into the model (ModelFormMixin.form_valid()). Or combine it with a form mixin where the user is passed to the form (FormMixin.get_form_kwargs()) and saved when the form is saved (ModelForm.save()).
Create a ModelAdmin mixin that does the same when saving a model in the django admin site.
This of course means someone on your team may forget to do it when creating new views and forms. The link you posted contains an answer as to the advantages and disadvantages of using thread local.

How to fix django admin foreign key display that used raw_id_fields

I have recently migrated a website from Django 1.6 to Django 1.8 and I can't figure out the simple way to fix the behaviour of django admin when it displays foreignkey fields that use the "raw_id_fields" in the adminClass.
The use case is exactly the one from django book : http://www.djangobook.com/en/2.0/chapter06.html (Figure 6-14)
class BookAdmin(admin.ModelAdmin):
...
raw_id_fields = ('publisher',)
Administration display used to have a spyglass at the end allowing to pick a new foreignkey id, but now none is displayed.
Documentation hint's at some new mechanism but it's unclear how to apply it here:
https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
Thanks
As often, the problem was elsewhere, the statics from the admin had not been updated and i was using an older version of admin static files.
a simple python manage.py collectatic command fixed this issue.
For future reference, any issue with admin should start by making sure statics are up to date.

Is it possible to ignore a system check error in Django 1.7+

I'm running into the following issue:
I have an older (recently upgraded to Django 1.6) site that uses one-to-one relations for user profiles, but the FK references to certain models are pointing to auth.User. I'm building a site in 1.8 on a separate subdomain that uses the same database with the old one and uses two apps from the old one but has a custom auth model class. I know what I'm doing and want different tables for the users of both sites. But the system check for the new site fails with the fields.E301 error:
core.RecipientAccount.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
Is it possible to work around this? Or will I simply have to use 1.6 for the new site or write lots of custom migrations to refactor the old one?
I've found a solution to the problem for the time being. Ultimately I'd refactor the old project to use a custom user model of it's own. But a temporary fix is using a subclass of ForeignKey to reference django.contrib.auth.User which skips the check for swapped model.
class ForeignKeySkipsSwappedCheck(models.ForeignKey):
def check(self, **kwargs):
from django.db.models.fields.related import RelatedField
errors = super(RelatedField, self).check(**kwargs)
errors.extend(self._check_related_name_is_valid())
errors.extend(self._check_relation_model_exists())
errors.extend(self._check_clashes())
return errors

Integrating Django tutorial example Polls app and django-registration

I'm learning Django on Ubuntu 13.04, Python 2.7, Django 1.5, Postgres 9.2,
Bootstrap 3.0. I'd like to achieve a combination of the tutorial example Polls app with django-authentication.
As my first effort I got the Polls app working from the Django 1.5 tutorial. I then installed django-registration 1.0 and these templates to make it work. I chose that package for authentication as opposed to django-allauth as a result of my question on authentication framework.
Now I want to integrate Polls and django-registration to record a set of results per user. After the poll results have been collected the admininstrator uses Django Admin interface to run a script to analyse the results (e.g. compute some statistics) and send an email to a subset of all users.
I briefly looked at two existing projects that looked like could get me there out of the box.
Light Bird's Questionnaire App was too complicated using a custom library of modular class based views. I'd like to keep it as simple as possible, using as much of out-of-the-box Django 1.5 functionality as possible for ease of maintenance and initial design.
Pinax web framework on top of Django, although a great idea, seems to be stuck in dark ages of 2011 with latest code supporting only Django 1.4 and Bootstrap 2.x. Starter projects don't look that useful and documentation isn't flash either.
Based on the above it looks like I'll have to do the integration of Polls and registration manually. At first pass I was thinking roughly the following:
The poll & choice could be simplified down to just a numeric answer to a question.
At database level we would need a separate table.
The primary key would be the userid.
Each column would store one answer per.
I'm guessing this would need a class PollsResults in model.py that would include defining the primary key as User, which should exist via django-registration.
Exactly how to do that and what follows gets a bit hazy to me at the moment.
I'm sure the above is a simple exercise for a Django developer. Could anyone give me some starting hints or even better an existing project that does something similar?
It looks like you're slightly underestimating the power of using a framework such as django. For example, you don't really need to worry too much about tables in the database or what will be their primary keys, because django's Object Relational Mapper (ORM) takes care of a lot of that for you.
If you want to connect two models (database tables) in django you can use a foreignkey like this:
class ThingOne(models.Model):
name = models.CharField(max_length=50)
class ThingTwo(models.Model):
thing_one = models.ForeignKey('ThingOne')
The quotes around 'ThingOne' in my ForeignKey are actually unnecessary because the ThingOne model has already been defined, but I like to use quotes anyway because it means your ForeignKeys will also work for models defined below (in your code) the model linking to them.
You therefore just need to add a relationship between your Polls and User models. If one user might have many poll results you should probably use a ManyToManyField instead of a ForeignKey but the principle is the same. That should be enough to get you started.

Unusual Error when Django App Is Deployed on apache2+mod_wsgi

I'm getting this weird AttributeError on the app I'm currently working on. I'm developing using the development web server i.e. "runserver" command of django toolsets. Then I decided to test the application on apache+mod-wsgi and I persistently get this error though it works fine sometimes. So I think there must be something wrong with that piece of code,
so I decided to comment it out and see what happens. And YES, it still give me the same error (See 2nd picture). <-- NOT RELEVANT NOW. The AttributeError I'm getting on custom User model, even if it actually contains the classmethod get_by_type_and_id() is what I'm interested on.
Have you even seen like this one before? What do you think is causing this? I've followed the tutorial here to deploy it. Note though that User is not the built-in django User model. I think it's a "customized,stripped-down" implementation based from the django's Auth module.
Note that I have not gotten this error on my development using django's own development server. This only happens when I deployed the app on Apache+mod_wsgi.
More Info:
Django version == 1.2.5
Thanks! I'd really appreciate any kind of help.
First Picture:
2nd Picture:
Few things to notice:
Are you sure that you have get_by_type_and_id method for the User?
You set pasword instead of password (typo)
I think you have to indent line 60 in your second screenshot
After hours of diving into the code, I had a eureka moment. So I thought, maybe at some point django.contrib.auth.models.User model is being put into action by some django module used in the application. Because like I mentioned, this app's User model is customized and the application is not using django.contrib.auth.* at least directly. This was my suspicion because this kind of error is not specific to that particular attribute. Sometimes it gets through that point, but then another AttributeError would occur on some other view referring to other User model attributes. Then at one point I noticed that the attributes of User in the error messages was that of django.contrib.auth.models.User.
So I decided to "remove" django.contrib.auth.models on my python path, and there it showed, an error occurred in one of the modules I'm using specifically django.contrib.messages. I removed it, and I'm not seeing the AttributeError again. It turned out that django's Message model has a foreign_key to django.contrib.auth.models.User.
But then, I lost the flexibility of django message framework, especially when I'm using it on view with a HttpResponseRedirect i.e. no way to put useful messages in a template's context. or maybe there is? :)
UPDATE 2 (Pretty Sure Now):
Yes, I'm pretty sure now that django.contrib.messages is the one causing the error. I tried reproducing the error on another application which uses the customized User model i.e. not django.contrib.auth.models.User. I enabled django.contrib.messages module and produced basically the same error. I would like to know why is this happening on Apache+mod_wsgi, but not on django's own development server.