RuntimeWarning: DateTimeField received a naive datetime

The problem is not in Django settings, but in the date passed to the model. Here’s how a timezone-aware object looks like: >>> from django.utils import timezone >>> import pytz >>> timezone.now() datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC) And here’s a naive object: >>> from datetime import datetime >>> datetime.now() datetime.datetime(2013, 11, 20, … Read more

What’s the difference between django OneToOneField and ForeignKey?

Differences between OneToOneField(SomeModel) and ForeignKey(SomeModel, unique=True) as stated in The Definitive Guide to Django: OneToOneField A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the “reverse” side of the relation will directly return a single object. In contrast to the OneToOneField “reverse” relation, a ForeignKey “reverse” relation returns a QuerySet. Example … Read more

How to customize user profile when using django-allauth

Suppose you want to ask the user for his first/last name during signup. You’ll need to put these fields in your own form, like so: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label=”Voornaam”) last_name = forms.CharField(max_length=30, label=”Achternaam”) def signup(self, request, user): user.first_name = self.cleaned_data[‘first_name’] user.last_name = self.cleaned_data[‘last_name’] user.save() Then, in your settings point to this form: ACCOUNT_SIGNUP_FORM_CLASS … Read more

Django Rest Framework remove csrf

Note: Disabling CSRF is unsafe from security point of view. Please use your judgement to use the below method. Why this error is happening? This is happening because of the default SessionAuthentication scheme used by DRF. DRF’s SessionAuthentication uses Django’s session framework for authentication which requires CSRF to be checked. When you don’t define any … Read more

When saving, how can you check if a field has changed?

Essentially, you want to override the __init__ method of models.Model so that you keep a copy of the original value. This makes it so that you don’t have to do another DB lookup (which is always a good thing). class Person(models.Model): name = models.CharField() __original_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_name = … Read more

Capturing URL parameters in request.GET

When a URL is like domain/search/?q=haha, you would use request.GET.get(‘q’, ”). q is the parameter you want, and ” is the default value if q isn’t found. However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments). Such as: (r’^user/(?P<username>\w{0,50})/$’, … Read more