How to fix Django warning “(models.W042) Auto-created primary key used when not defining a primary key type”?

Your models do not have primary keys. But they are being created automatically by django. You need to choose the type of auto-created primary keys: https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys (new in Django 3.2) Either add this to settings.py: DEFAULT_AUTO_FIELD=’django.db.models.AutoField’ or class Topic(models.Model): id = models.AutoField(primary_key=True) …

Django Static Files Development

Based on what you’ve posted so far, it looks like you’re following the docs for django.contrib.staticfiles. I agree that the docs can be difficult to follow especially if one is new to django. I believe the confusion stems from the fact that django.contrib.staticfiles has two modes of operation: During the development phase where the development … Read more

Django unique, null and blank CharField giving ‘already exists’ error on Admin page

None of the answers clearly describe the root of the problem. Normally in the db you can make a field null=True, unique=True and it will work… because NULL != NULL. So each blank value is still considered unique. But unfortunately for CharFields Django will save an empty string “” (because when you submit a form … Read more

Django AdminForm field default value

Assuming the value is based on ‘request’ you should use this: class MyModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(MyModelAdmin, self).get_form(request, obj, **kwargs) form.base_fields[‘my_field_name’].initial=”abcd” return form

How to get two random records with Django

The order_by(‘?’)[:2] solution suggested by other answers is actually an extraordinarily bad thing to do for tables that have large numbers of rows. It results in an ORDER BY RAND() SQL query. As an example, here’s how mysql handles that (the situation is not much different for other databases). Imagine your table has one billion … Read more

tech