Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django recursive child parent queryset
I have a hard time to connect a RawQerySet to one of my models. I searched but could not find anything helpful. I'm working with two tables: Table 1. is a "part" table, contains all kind of parts (BM-), plus "machine-build" names, like B1 Bowling Machine: class Part(models.Model): part_id = models.AutoField(primary_key=True) part_children = models.ForeignKey(Part_Part, blank=True, null=True) part_number = models.CharField(default='part number here', max_length=120) part_description = models.TextField(default='text here', null=True) part_revision = models.TextField(default='text here', null=True) Table 2. a "part_part" is a parent-children connection table. For example: part_id 205 is a parent machine-build, it has no parent itself because it is top level, therefore in "part_part" table part_id_parent is NULL. The same time part_id 47 is a child of part_id 205. I can have parts (like Arduino UNO) with one or more parents. This way I can have more levels. class Part_Part(models.Model): part_part_id = models.AutoField(primary_key=True) part_id_parent = models.IntegerField(null=True) part_id_child = models.IntegerField() part_qty = models.IntegerField(null=True) I managed to get a recursive query working with PostgreSQL to find the relations: class PartPartQuerySet(models.query.QuerySet): def recursive_query(self, parent_id): if parent_id is None: exp = " is NULL" sql = '''with recursive rel_tree as ( select part_part_id, part_id_parent, part_id_child, 1 as level, array[part_part_id] as path_info from inventory_part_part where part_id_parent ''' … -
Google App Engine, Django: Tables are not made in Google cloud SQL after deployment
I am deploying a website with django-backend on google app engine. I followed their tutorial. I have run the website on my local server using MySQL and it runs perfectly. When deploy it on Google App Engine it gives me the following error: ProgrammingError "Table 'clouddatabasename'.'appname'_'modelname' doesn't exist" Here is my app.yaml: # [START django_app] runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /static static_dir: static/ - url: .* script: wt.wsgi.application # Only pure Python libraries can be vendored # Python libraries that use C extensions can # only be included if they are part of the App Engine SDK # Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27 libraries: - name: MySQLdb version: 1.2.5 - name: django version: "1.11" env_variables: CLOUDSQL_CONNECTION_NAME: 'copied perfectly from google cloud sql instance' CLOUDSQL_USER: username CLOUDSQL_PASSWORD: password # [END django_app] # Google App Engine limits application deployments to 10,000 uploaded files per # version. The skip_files section allows us to skip virtual environment files # to meet this requirement. The first 5 are the default regular expressions to # skip, while the last one is for all env/ files. skip_files: - ^(.*/)?#.*#$ - ^(.*/)?.*~$ - ^(.*/)?.*\.py[co]$ - ^(.*/)?.*/RCS/.*$ - ^(.*/)?\..*$ - ^env/.*$ Here is my settings.py: … -
Getting this BackEnd error : 'TypeError: expected string or bytes-like object as I attempt to derive age for DOB.'
I am attempting to derive age from date of birth, and I keep getting this error : match = date_re.match(value), TypeError: expected string or bytes-like object These are the imports : from django.db import models from django.contrib.auth.models import User import datetime from django.utils.timezone import now from Self import settings This is the class creation class Identity_unique(models.Model): NIS_Identity = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now =True) First_Name = models.CharField(max_length = 100, default =0) Last_Name = models.CharField(max_length = 100, default=now) date_of_birth = models.DateField(max_length=8, default=0) patient_age = models.IntegerField(default=0) def __str__(self): Is_present = date.today() patient_age = Is_present.year - date_of_birth.year if Is_present.month < date_of_birth.month or Is_present.month == date_of_birth.month and Is_present.day < date_of_birth.day: patient_age -= 1 return self.patient_age Contact = models.IntegerField() This is the ModelForm : from django import forms from .models import Identity_unique class Identity_form(forms.ModelForm): NIS_Identity = forms.IntegerField() First_Name = forms.CharField(max_length = 100) Last_Name = forms.CharField(max_length = 100) date_of_birth = forms.DateField() patient_age = forms.IntegerField() Contact = forms.CharField() class Meta: model = Identity_unique fields = ('NIS_Identity','First_Name', 'Last_Name', 'date_of_birth', 'patient_age', 'Contact', ) I keep getting the match = date_re.match(value), TypeError: expected string or bytes-like object error each time I try to run the makemigrations and migrate commands Here is an image of the complete error : -
Forbidden (403) error with POST via AFNetworking to Django backend?
I am trying to login to my Django backend via POST request, using AFNetworking 3.0. I have obtained a csrf token and appended it to my login request, but it results in the error: "Request failed: forbidden (403)" Any ideas? AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [manager.requestSerializer setValue:csrf forHTTPHeaderField:@"csrfmiddlewaretoken"]; [manager.requestSerializer setValue:@"xxx" forHTTPHeaderField:@"Host"]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"xxx" password:@"xxx"]; [manager POST:@"xxx" parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"%@",[responseObject description]); } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"%@",[error localizedDescription]); }]; -
Display object for Django Context Processors
I'm working to add some business details as a context processor within an app called Business. I've included in it a folder titled templatetags for the init.py and business_tags.py files. My problem is while the context processor shows a result, I am unable to display the results as a loop. business_tags.py file: from django import template register = template.Library() from django.contrib.auth.models import User from ..models import Businessprofile @register.simple_tag def my_biz(request): current_user = request.user.id biz = Businessprofile.objects.filter(owner=current_user) return biz On my view file I am currently made a for/endfor for the loop: {% load business_tags %} {% my_biz request %} {% for biz in my_biz %} {{ biz }} {% endfor %} <!--end content--> How do I display the results of the context processor as a for loop? -
user_logged_in_handler() takes exactly 3 arguments (2 given) in django
i have the following views.py: from django.template import loader from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.contrib.auth.decorators import login_required from student.models import CustomUser from student.forms import UserForm from django.template.context_processors import csrf from django.shortcuts import render_to_response from django.contrib.auth.signals import user_logged_in from .models import UserSession def user_logged_in_handler(sender,request,CustomUser,**kwargs): UserSession.objects.get_or_create( user=CustomUser, session_id= request.session.session_key ) user_logged_in.connect(user_logged_in_handler) def delete_user_sessions(CustomUser): user_sessions=UserSession.objects.filter(user=CustomUser) for user_session in user_sessions: user_session.session.delete() i have the following models.py: class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL) session=models.ForeignKey(Session) Also in models.py i have class CustomUser(AbstractUser). What's wrong in my views.py as the error says when i try to access /admin/ user_logged_in_handler() takes exactly 3 arguments (2 given) -
How do you format from unix time stamp to local time in Django?
How do you format from unix time stamp to local time in Django. The time template filter does not appear to work, {{ unix_time_value|time:"TIME_FORMAT"}} What is the correct way? -
Django Integrity Error : Not Null constraint failed
I am trying to make a blog like website. Here is my models.py: class upload(models.Model): username = models.CharField(max_length=100) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) title = models.CharField(max_length=100) description = models.CharField(max_length=300,default=None) content = models.TextField(default=None,blank=True,null=True) docFile = models.FileField(default=None,blank=True,null=True) timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) def __unicode__(self): return self.title class Meta: ordering = ["-timestamp"] def get_absolute_url(self): return reverse("detail",kwargs={"id":self.id}) I have changed my models.py to include the TextField(content) which was not present before .Then I ran the command python manage.py makemigrations which executed successfully.After that when I run python manage.py migrate,I am getting IntegrityError:NOT NULL constraint failed:uploads_upload.content (uploads is the name of my app) Reading some previous SO answers to this error,I have also added null=True and blank=True also to my content attribute,still I get the same error. I am inputting the details through Django forms.Here is my forms.py: class PostForm(forms.ModelForm): #docfile = upload.docFile(required=False) class Meta: model = upload fields = [ "title", "description", "username", "content", "docFile", ] Why am I getting this error? -
Django polls with autentication
I have a poll app using django from the docs. I now want to make it advanced. I dont want a user to be able to vote twice that means the users can only vote once else it would show an error message. It works fine if it is the super user that is logged in but for any other user, they are still able to vote multiple times. Model class Question(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='question_created') question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='choice_created') question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text View def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) if Choice.objects.filter(question_id=question_id, user_id=request.user.id).exists(): context = { 'question': question, 'error_message': "Sorry, but you have already voted.", } template = 'polls/detail.html' return render(request, template, context) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): context = { 'question': question, 'error_message': "You didn't select a choice.", } template = 'polls/detail.html' return render(request, template, context) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) -
Django Admin panel interface
To create admin interface to edit some field, which is best practice? Customize default Django admin or create admin template? I want to update 1 field of a database. Now can I create new view or customize default admin panel? -
Django DateField to infinity get 'OverflowError: date value out of range'
In my Django model a DateField(representing an expiredate) could by infinite, i use as infinite date the calue of 'datetime.datetime.max', but what i get is OverflowError: date value out of range The db i'm using is postgresql. Why this error? And is there any better approach for this? -
GDAL in flexible enironment
In app engine flexible environment, I'm trying to run django on postgresql db using GIS extensions. Can run locally, and it appears to deploy to cloud successfully. However, when run from cloud I get a "ERROR: Server Error" and the log file has the error shown below. I've tried several ways of installing GDAL to make sure there's no missing header file. Also upgraded to Google Cloud SDK 171 and gsutil 4.27. Have tried including GDAL==2.1.3, which gives a build error, so removed it. THANKS, Dan LOG FILE ERROR: Traceback (most recent call last): File "/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.5/site-packages/gunicorn/util.py", line 352, in import_app import(module) File "/home/vmagent/app/mysite/wsgi.py", line 22, in application = get_wsgi_application() File "/env/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/env/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/env/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/env/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/env/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/env/lib/python3.5/site-packages/django/contrib/auth/models.py", line … -
Django-Allauth : no social buttons on account creation view?
I've installed django-allauth and activated Facebook/Instagram/Google/Twitter. These are all visible and useable from the "login" view, but the "signup" view contains only the classic "email/password/confirmpassword" fields. Looking at the signup template, I see that there are no social accounts there. This is confusing to me, are users supposed to create an account first with email, and then use their social accounts to login ? Why can't they just signup with their social accounts ? Am I missing something ? -
Django Rest Swagger: 'APIGroupAction' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am getting this issue while integrating django-rest-swagger==2.1.2 with existing project djangorestframework==3.5.3 . I tried using quickstart with class based views which mention serializer_class in them: schema_view = get_swagger_view(title='Pastebin API') then, I tried with few futhis way as wellnction based views as: @api_view() @renderer_classes([SwaggerUIRenderer, OpenAPIRenderer]) def schema_view(request): generator = schemas.SchemaGenerator(title='Pastebin API') return response.Response(generator.get_schema(request=request)) In both cases, it is giving the same error as : 'APIGroupAction' should either include a serializer_class attribute, or override the get_serializer_class() method. Any help regarding this will be appreciated. -
Python method from view.py not getting call on django template
I am trying to call a python view method res() on django template but its not getting call. This is my View class make_incrementor(object): def __init__(self, start): self.count=start def __call__(self, jump=1): self.count += jump return self.count @property def res(self): self.count =0 return self.count def EditSchemeDefinition(request, scheme_id): iterator_subtopic = make_incrementor(0) scheme_recs = scheme.objects.get(id=scheme_id) view_val = { 'iterator_subtopic': iterator_subtopic, "scheme_recs": scheme_recs, } return render(request, "edit.html", view_val) I am Trying to Increment the count and later resetting it to 0 after a level But its reset method is not getting call from the Django template. This is my edit.html page <td id="subTopic" class="subTopic"> {% for strand in scheme_recs.stand_ids.all %} {{ iterator_subtopic.res }} {% for sub_strand in strand.sub_strand_ids.all %} {% for topic in sub_strand.topic_ids.all %} {% for subtopic in topic.sub_topic_ids.all %} <input id="subTopic{{ iterator_subtopic }}" class="len" value="{{ subtopic.name }}"> <br> {% endfor %} {% endfor %} {% endfor %} {% endfor %} </td> my {{ iterator_subtopic.res }} is not getting the call and the value of iterator_subtopic is not get set to 0 again. The Function and its call is working fine on Terminal but not rendering in django template. Please correct me where i am doing wrong. Thanks in advance. -
creating nested dictionary in python
I want to create a nested dictionary in such a form: { catagory_name: {1: abc, 2: efg}, category_name: {1: pqr, 2: stu}, category_name: {1: vwx, 2: ijk, 3: lmn} } Where I will fetch category1_name, category2_name and category3_name from a table1 and then I will for loop it to execute new query and fetch values abc, efg, pqr, stu and vwx, ijk, lmn from next table based on Ids fetched from table1. Something like this: categories = cat.getAllCatagories() for value in categories: categoriesData = {} subCategories = cat.getSubCategoriesByCategoryId(value.id) for val in subCategories: categoriesData[values.name] = val.name context = {'categoriesData': categoriesData} return render(request, 'demo/test/industries_catagories.html', context) Now I want to access this categoriesData dictionary in my template of Django framework and list it form of tree structure. Any ideas will be very much appreciated. Sources I referred SO question are very complicated. -
Django-haystack faceting on foreign field
Is it possible to facet on a foreign field attribute via the search index. search_indexes.py class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='/home/wilkinj33/bargainforest/bargainforestenv/motorclass/templates/search/indexes/product_text.txt' ) title = indexes.EdgeNgramField(model_attr='title') retailer = indexes.CharField(model_attr='retailer', faceted=True) price = indexes.IntegerField(model_attr='price', faceted=True) barcode = indexes.CharField(model_attr='barcode') def get_model(self): return Product def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(timestamp__lte=timezone.now()) I would like to facet the following model, name attribute. class top_category(models.Model): class Meta: verbose_name_plural = 'Top Categories' name = models.CharField(max_length=500) def __str__(self): return self.name -
How to exclude field in Django models.Model.save()
I have the following model, which when saved calculates hash_id field based on the pk: class MyTable(models.Model): something = models.CharField(max_length=255) reported = models.IntegerField(default=0, blank=True) hash_id = models.CharField(max_length=32, db_index=True, unique=True, blank=True) def save(self, *a, **kw): super().save(*a, **kw) self.hash_id = hash_fn(self.pk) super().save(*a, **kw) In one of my views I have the following lines, which are supposed to increment reported field by 1, however reported is incremented by 2, because of the overridden save method: my_table_ins.reported = F('reported') + 1 my_table_ins.save() Ideally I would like something among the lines: def save(self, *a, **kw): super().save(*a, exclude=['reported'], **kw) self.hash_id = hash_fn(self.pk) super().save(*a, **kw) -
apidoc js What to add in a put?
I have read the apidoc.js documentation and i have a dilemma. I don't exactly know the difference between @apiParam and @apiSucces, the documentation doesn't explain properly what they really do. For example i have a get and a put with these parameters in the get: """ @api {get} /locations/:id/ Location id - details @apiName GetLocation @apiGroup Locations @apiParam {integer} [id] Location id. @apiParam {string} [name] Location name. @apiParam {object} [company] Company name. @apiParam {string} [website] Location website. @apiSuccess {object[]} results List with location details """ I am using apidoc in django and this is my view: class LocationView(APIView): serializer_class = LocationSerializer permission_classes = (IsAuthenticatedOrReadOnly,) def get_object(self, pk): try: return Location.objects.get(pk=pk) except Location.DoesNotExist: raise Http404 def get(self, request, pk): serializer = LocationSerializer(self.get_object(pk)) return Response(serializer.data) def put(self, request, pk): location = self.get_object(pk) serializer = LocationSerializer(location, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): location = self.get_object(pk) location.save() return Response(status=status.HTTP_204_NO_CONTENT) What do i have to write in a PUT for modifying? Do i have to write every parameter again? or use apiSuccess? An example would be great. -
Django: Do I really need apps.py inside an app?
When creating an app with python manage.py startapp myapp, it automatically creates an apps.py file. from django.apps import AppConfig class MyappConfig(AppConfig): name = 'myapp' When I removed it, everything seems to work as before (at least my tests all passed). Is it a bad practice to remove these kind of files from the apps? Should we keep them to avoid side effects? -
Redirect to the previous page after Login in django
I read this. Django: Redirect to previous page after login But in my case it doesn't work. Also in my settings.py, I have LOGIN_REDIRECT_URL = '/home' #it means the home view I have done this in my base.html <li><a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Patient's login</a></li> and also have added this to my login.html <input type="hidden" name="next" value="{{ next }}" /> But still it doesn't redirect to the page the user was after login. Also when the user is logged in, how can I show at the top right corner on the nav bar something like "Welcome #" # being whatever the username is. And when he's logged out, it doesn't show such thing. And I'm using an CustomUser(AbstractUser) in models.py How can i do this? login.html <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" /> </form> -
select image in django admin
I have an image field and would like to use to upload image (I have managed to do this part with models.ImageField) or to have selected an image in the database. How can I do it? I would like a similar interface or something like this: -
How to check if an instance of a model already exist in database
So I defined a model Language. I need to track whoever created the language object. I also don't need multiple instances of the same language. For that reason I want to be able to check if a language already exists when a user tries to create one. If it exists then I'll just tell the user they can use the one already present. If not they can create it. I am using a custom User model. USERS = get_user_model().objects.all() from random import choice class Language(models.Model): language = models.CharField(max_length=25, unique=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.language def get_absolute_url(self): return reverse('chinemerem:language_index') def save(self, *args, **kwargs): self.language = self.language.upper() super(Language, self).save(*args, **kwargs) I can create Language instances with try/except in django shell like below. try: language, exists = Language.objects.get_or_create(creator=choice(USERS), language='german') except IntegrityError: pass But django admin throws IntegrityError when I try to create a language instance through django admin. My question: How do I implement something like the try/except block above inside my model to check if a language already exists when a user tries to create one? I've done a lot of searching and have come across pre_save from signals which I suspect might be helpful. But the django docs … -
Django passing argument to url to make it show message "user created!" on the same page i register a user
I'm trying to create my own View to register a new User in my website. I'm using this tutorial to help me with authentication: https://docs.djangoproject.com/en/1.11/topics/auth/default/# But my problem is: in the same View that i have my form that i use to create a new User, i want to, when a person sucessfully registers a new user, to display the message "user created!" First, my first View from my system is the login and its login.html is like this: <form action="{% url 'analisarlogin' %}" method="post"> {% csrf_token %} <label for="usuario">Usuário: </label> <input id="usuario" type="text" name="usuario" value=""/> <label for="senha">Senha: </label> <input id="senha" type="text" name="senha" value=""/> <input type="submit" value="Login"/> </form> <a href="{% url 'cadastro' cadastrorealizadocomsucesso=false %}">Não tem cadastro?</a> You can see that on the from the final line that i go to a url passing one argument: cadastrorealizadocomsucesso=false This is because my View called cadastro(portuguese for 'Register' in english) is like this: def cadastro(request,cadastrorealizadocomsucesso): return render(request, 'cadastro.html',{'cadastrorealizadocomsucesso':cadastrorealizadocomsucesso}) And my cadastro.html is like this: <form action="{% url 'cadastrarprofessor' %}" method="post"> {% csrf_token %} <label for="usuario">Usuário: </label> <input id="usuario" type="text" name="usuario" value=""/> <label for="senha">Senha: </label> <input id="senha" type="text" name="senha" value=""/> <label for="email">Email: </label> <input id="email" type="text" name="email" value=""/> <input type="submit" value="Cadastrar"/> </form> {% if … -
Django model blank=True, but sql always NOT NULL
I am building a Django website from a tutorial. The model is called Post and looks like this: class Post(models.Model): author = models.ForeignKey('auth.User', verbose_name='Author') title = models.CharField(max_length=200, verbose_name='Titel') text = HTMLField() created_date = models.DateTimeField(default=timezone.now, verbose_name='Erstellungsdatum') published = models.BooleanField(blank=True, verbose_name='Veröffentlichung') tags = models.ManyToManyField(Tag, blank=True) class Meta: verbose_name = 'Artikel' verbose_name_plural = 'Artikels' ordering = ['-created_date'] def publish(self): self.published = True self.save() def __str__(self): return self.title as you can see, i made some fields blank=True. The migration/sql Django is now performing looks like this: ALTER TABLE "blog_post" RENAME TO "blog_post__old"; CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "published" bool NOT NULL, "title" varchar(200) NOT NULL, "text" text NOT NULL, "created_date" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id")); INSERT INTO "blog_post" ("id", "title", "text", "created_date", "author_id", "published") SELECT "id", "title", "text", "created_date", "author_id", "published" FROM "blog_post__old"; DROP TABLE "blog_post__old"; CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id"); COMMIT; It just ignores the blank-values and makes every field NOT NULL. i saw this also in this question The problem is, that if i implement the form, i cannot uncheck the published field, because it is complaining that it has to be checked. Thanks in advance!