Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validation errors don't appear in Django form
I am trying to create a form where the users will enter their emails. Typically the validation errors for email(empty field or not proper format) are displayed by the browser. Using the basic form example, everything shows correctly: <form action="/notify-email/add/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> In my case, if there are no validation errors I use an ajax request to save the email and show a modal with a thank you message.But if there are validation errors I can see them when only if I hover. Also, the modal is shown even if there are errors in validation. This is my models.py: from django.db import models class NotifyEmail(models.Model): email = models.EmailField(max_length=255) date_added = models.DateField(auto_now_add=True) time_added = models.TimeField(auto_now_add=True) def __str__(self): return self.email This is the form based on the model: from django import forms from landing.models import NotifyEmail class NotifyEmailForm(forms.ModelForm): class Meta: model = NotifyEmail fields = ["email"] def __init__(self, *args, **kwargs): super(NotifyEmailForm, self).__init__(*args, **kwargs) self.fields['email'].widget = forms.EmailInput(attrs={'placeholder': 'Email', 'required': True}) My views.py: from django.shortcuts import render from django.http import JsonResponse from .forms import NotifyEmailForm def add_notify_email(request): if request.method == "POST": form = NotifyEmailForm(request.POST) if form.is_valid(): form.save(commit=True) print("Email Added.") return JsonResponse({'msg': 'Data saved'}) else: … -
setting permission for only one object using Django-guardian and Flatpages
I'm trying to use Django-guardian to apply permissions to specific flatpages. we have a number of flatpages on our site, and in most cases the django-auth works for what we need. However, we want to add object level permissions to some of the flatpages and specific users. for example, i have a user YOUNGTEMP and i want to give this user access to edit a subset of the total flatpages we have on the site. I have installed Django-guardian, and using the shell given change_flatpage permissions to this user for the appropriate sites. this user has no other permissions at all, as i don't want them to see anything but this one site from the admin. I can verify by looking at the DB that the permissions are there, as well as that they appear in the admin when i log in as a SU. Why then when i log in as this user YOUNGTEMP does the admin site tell me i have no permissions to edit anything? I followed the excerpts from the readthedocs.io page here to assign permissions in the shell to make sure it wasn't a problem with my overridden admin, which looks like this: imports*... class … -
Download links of protecting file after completing payment process in Django apps
What is best method of giving download links of protecting file after completing payment process with stripe in Django apps? With Ajax Call or any other method? -
Better way to create class dict entries from a loop than locals()
I've been told it's bad form to use locals() to dynamically create variables in Python. However, I'm writing a class (using Django and Wagtail), and I really do need these things to go in the class dict, a.k.a. the class statement's local variables, not in a separate data structure: class BlogPage(Page): for language in languages: locals()['body_' + language] = RichTextField(blank=True) I don't think I can set these after the class statement with setattr, either, because Django's metaclass processing will already have happened by then. Is there a better way? -
Django Calculated Fields
I am making a website for which you can sell goods online and I am using Django. I am unsure how to proceed with a section. The four models involved are Good_For_Sale An item would be listed on the sale which lists type, description and other specs, but relevant it would list a price Customer A customer should be able to fill out a form and order an item on sale Orders A customer may order an item and this is stored in an orders fields It can store order status at the time Invoice Once the goods are delivered then the invoice is produced and sent for payment Requirement would be that one invoice may be for many orders and invoice is issued after the goods are delivered Invoice would be issued every 14 days (ie on the 14th and 28th of each month an invoice would be issued for all delivered orders) What I am having problems is: How to calculate an invoice total based on the basis of all delivered orders in the past 14 days How to calculate tax (assume mixed item supply where tax status is stored at good_for_sale level) Code Models.Py class Orders(models.Model): date … -
Using django flatpages without the Site framework
I'm currently working on flatpages for my website, however, I find it unnecessary having to configure my source code with SITE_ID and matching it with the database Site model, for the single reason that I wish to use flatpages on a single website. What I want is simply to lookup the url path in the database, for a match in a pages table, and output the relevant page information. Without having to configure. Is there any way I can get flatpages in the database without having to specify a site number and having an extra model in my database? The functionality of the flatpages that is prebuilt is great, I just want to remove the need for Site, and hardcoding. -
Check if user exists before creating new user djangorestframework
So far I have -> serializer: class UserSerializer(serializers.ModelSerializer): """Serializer to map the model instance into json format.""" class Meta: """Map this serializer to a model and their fields.""" model = User fields = ('id','username', 'mobile', 'password', 'first_name','last_name','middle_name','profile_pic','short_bio','friends_privacy','address_1','address_2','city','state','country','pin','verification_code','is_active','is_blocked','is_reported','date_created','date_modified') # ADD 'owner' extra_kwargs = {'password': {'write_only': True}} read_only_fields = ('date_created', 'date_modified','is_staff', 'is_superuser', 'is_active', 'date_joined',) def create(self, validated_data): mobile_ = validated_data['mobile'] password_ = validated_data['password'] username_ = validated_data['username'] motp = self.context['request'].GET['motp'] eotp = self.context['request'].GET['eotp'] email_ = self.context['request'].GET['email'] mflag = api.views.checkOTP_(mobile_,motp) eflag = api.views.checkOTP_(email_,eotp) if (mflag and eflag): user = User( username=username_, email =email_, password = make_password(password_), mobile = mobile_, ) user.set_password(validated_data['password']) user.save() return user view: class UserView2(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer model = User def get_permissions(self): # allow non-authenticated user to create via POST return (AllowAny() if self.request.method == 'POST' else IsStaffOrTargetUser()), I need to check for OTP of mobile and email and also if a user with same mobile or email already exists. If user already exists return a json response with error: already exists!. If user is new and OTP is wrong again raise an error. If user is new and OTP is correct, create an account. Problem here is I tried to add the function to check for otp … -
Filter response by POST request Django Rest-framewrok wirh foreign keys
My models: FormField: class FormField(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") fieldName = models.CharField(max_length=50) text = 'text' email = 'email' phone = PhoneNumberField() date = models.DateTimeField TYPE_OF_FIELD_CHOICE = ( (text, 'text'), (email, 'example@email.mail'), (phone, '+9123456789'), (date, '2017-01-01') ) field_type = models.CharField(max_length=25, choices=TYPE_OF_FIELD_CHOICE, default=text) def __str__(self): return self.fieldName FormPattern: class FormPattern(models.Model): formName = models.CharField(max_length=50) formFields = models.ManyToManyField(FormField) def __str__(self): return self.formName I am using REST django framework. I need to filter my response data by my POST request, that look like this: formpatterns/get_from?f_name1=value1&f_name2=value2 if f_name1 = fieldName in some FormPattern, i need to give response with this FormPattern formName. I already have serializator that work with choices and i can GET list all my FormPattern class FormSerializer(serializers.ModelSerializer): formName = serializers.CharField() formFields = serializers.SlugRelatedField( many=True, read_only=True, slug_field='field_type' ) class Meta: model = FormPattern fields = ('formName', 'formFields') my method in views.py: @api_view(['GET', 'POST']) @parser_classes((JSONParser,)) def form_list(request): if request.method == 'GET': forms = FormPattern.objects.all() serializer = FormSerializer(forms, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = FormFieldSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(FormPattern.serializer.data) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) POST just saving another FormPattern in my example. How need i edit this to get … -
getting "IntegrityError: NOT NULL constraint failed" in django 1.10 on unit test which were passing in Django 1.9
while calling Test Models save() i am getting this error self.created_by super(Test, self).save() *** IntegrityError: NOT NULL constraint failed: itests_test.created_by_id even though created_by_id is not null -
How could I use an HTML code to store data in a django based app?
So I have been trying to design an app that can take the file input from two csvs, then combine them into a dataframe and analyze them. The python function to do this is done, but there is an issue with uploading them onto the app. The django based app system that I am writing the app on has gizmos, but none of the gizmos are used for file input. So I put this code in the django template: <div class="gauge-data-upload"> <label class="control-label" for="gauge-data-upload-input">Recorded Gauge Data</label> <input id="gauge-data-upload-input" name="gauge-data-upload-input" type="file" accept=".txt,.csv"> <p class="help-block hidden">Must select file to submit!</p> </div> But I am uncertain how to link this html code to the controllers page (a page of python classes) This is what my controller for this particular django template looks like. @login_required() def add_gauge_data(request): """ Controller for the Add Dam page. """ # Handle form submission if request.POST and 'add-button' in request.POST: # Get values has_errors = False #Define Form Gizmos add_button = Button( display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes = {'form': 'add-gauge-data-form'}, submit = True ) cancel_button = Button( display_text='Cancel', name='cancel-button', href=reverse('statistics_calc:home') ) context = { 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'statistics_calc/add_gauge_data.html', context) Will I need to write … -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I find out that the authenticated user by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. consumers.py: def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) channel_session_user_from_http def ws_connect(message): message.reply_channel.send({"accept": True}) Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Next message' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
Django Models - How to add other objects of a Foreign Key
It has been difficult to find how to add in a table more them one column from other table (foreign key), see below: Models.py: class Operator(models.Model): user_id = models.OneToOneField(User) operator_name = models.CharField(max_length=100) cnpj = models.CharField(max_length=14) def __str__(self): return self.operator_name class Service(models.Model): operator_id = models.ForeignKey(Operator, on_delete=models.CASCADE) service_type = models.ForeignKey(ServiceType, on_delete=models.CASCADE) service_name = models.CharField(max_length=100) short_descrip = models.CharField(max_length=100) description = models.CharField(max_length=400) price = models.IntegerField(default=0) address = models.CharField(max_length=200) def __str__(self): return self.service_name Views.py def myagency(request): data = serializers.serialize("json", Service.objects.all()) return HttpResponse(json.dumps(data), content_type="application/json") In the JSON response I got: pk: 1 operator_id: 1 service_type: 3 ... I would like receive: pk: 1 operator_id: 1 operator_name: "operator_example" service_type: 3 ... Summarizing: I would like to include in the table "Service" the "Primary Key" and "operator_name" objects from the table "Operator". Does anybody know how to do this? Thanks! -
Issue with DecimalField,max_digits of django models
I have declared below field in models.py "marks = models.DecimalField(max_digits=2, decimal_places=2, default=3.0)" At backend table structure is | Field | Type | Null | Key | Default | Extra | | marks| float(3,1) | NO | | 1.0 | | So here default value 3.0 will try to save as 3.00 (decimal places=2) at backend and there will be no space to store left side value 3 right? For above case,when I give max_digits=3 or decimal_places=1 it is working. Please help me,what exactly happening here from django to mysql db flow? -
Django loaddata does not create m2m relations
I'm upgrade django from 1.8.4 to 1.11.6 and encountered problem. I have two models: class File(models.Model): title = models.CharField(max_length=128, verbose_name=_('title')) description = models.CharField( max_length=255, blank=True, null=True, verbose_name=_('description') ) class Task(models.Model): output_data = models.ManyToManyField( File, blank=True, verbose_name=_('output_data') ) I'm running manage.py loaddata with the following data for models above: files.json: [ { "fields": { "description": "", "title": "Data file 2", }, "model": "files.file", "pk": 2 } ] tasks.json: [ { "fields": { "output_data": [2] }, "model": "tasks.task", "pk": 1 } ] loaddata creates file and task, but not create m2m relation. Before the update everything worked fine. -
'social' is not a registered namespace when integrating social_django
I know similar questions have been asked before, but none of them seemed quite the same as my situation. The error I receive looks like this: Environment: Request Method: GET Request URL: http://web/login/auth0 Django Version: 1.10 Python Version: 3.5.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'my_app.apps.authentication'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.5/site-packages/django/urls/base.py" in reverse 77. extra, resolver = resolver.namespace_dict[ns] During handling of the above exception ('social'), another exception occurred: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/social_django/utils.py" in wrapper 37. uri = reverse(redirect_uri, args=(backend,)) File "/usr/local/lib/python3.5/site-packages/django/urls/base.py" in reverse 87. raise NoReverseMatch("%s is not a registered namespace" % key) Exception Type: NoReverseMatch at /login/auth0 Exception Value: 'social' is not a registered namespace My application is Dockerized, and I am attempting to integrate Auth0 and social_django. I am using nginx, gunicorn, and postgres in my stack. I mainly followed this tutorial to get running: https://auth0.com/docs/quickstart/webapp/django I have social_django and the sub-application, authentication installed in my main settings file: # /src/my_app/settings.py INSTALLED_APPS = … -
ImportError: cannot import name '' import two model by themselves
I have stupid problem with Django and I don't have any idea why. I create new project test, in this project I create two apps (test1, test2). I add them to INSTALLED_APPS. In this apps I've add to models: test1.models: from django.db import models from test2.models import test2 # Create your models here. class test1(models.Model): pass test2.models: from django.db import models from test1.models import test1 # Create your models here. class test2(models.Model): pass Now I want to runserver but command gave me error: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7f0881274620> Traceback (most recent call last): File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen … -
How to pass model instance to a form in a django wizard form?
I'm working with django-formtools and I need to create a 3 step form. I have the wizard working well but in the step 2 I need to render in the template the value of a model instance. views.py class PropertyWizard(SessionWizardView): def get_form_initial(self, step): initial = self.initial_dict.get(step, {}) if step == 'price': valuation = get_object_or_404(Valuation, user=self.request.user) initial.update({'valuation': valuation}) return initial If I print initial value it contains: {u'valuation': <Valuation: street test, 123>} urls.py url(r'^dashboard/properties/add/$', property_views.PropertyWizard.as_view(FORMS), name='add_property'), template.html Here I've tried this combinations: <h1>{{ initial }}</h1> <h1>{{ initial.valuation.creation_date }}</h1> But I've never seen anything. What am I doing wrong? -
Three Models in One Template
I'm new to Django and currently using version 1.11 with Python 3.6. I have three models in one template. Model 1 is my custom user which has a primary key called formattedusername. Model 2 is my access list which has a should create a 1 to many relationship with User on ntname. Model two has a foreign key to the reference table ReportList called report_id. Model 3 is my report list which has report_id as a primary key. I'm trying to create a views.py to link all three tables for one template. In my template I want to display for the current User all report_names listed in my access list model. Then another display of all available reports that the current User doesn't have access to, so the reports in Report List that don't exist in Access List. For my views.py I tried several variations of the following: def applicationdetail(request, ntname): user = get_object_or_404(User, pk=formattedusername) applicationlist = QvReportList.objects.all() applicationaccess = QVReportAccess.objects.filter(user=ntname) context = {'user' : request.user, 'applicationdetail' : applicationaccess} return render(request, 'accounts/profile.html', context=context) class IndexView(User): context_object_name = 'profile_list' template_name = 'contacts/index.html' queryset = User.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['users'] = User.objects.filter(user=formattedusername) context['reportaccess'] = QVReportAccess.objects.filter(user=ntname) context['reportlist'] = QvReportList.objects.all() … -
trying to build a blog with dynamic formating
Can someone please point me in the direction of a resource to build a blog page with editing on a website? Websites like medium.com and stack overflow allow users to dynamically generate html elements. so add a picture here make the text go around the picture. Change this text to pink. format this text here etc how you do this? Im using angular and typescript my backend is a restful one in django. I'm not so much looking for plugins although I am sure they would be good to learn from, I am more trying to learn how to do it. -
Django-I am getting an syntax error for my one of my URLs even though not touching it. Not sure why [on hold]
I am doing my URLs in urls.py but getting an error even though not touching this certain URL. Can someone please tell me what I have done wrong? url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name="contact"), ^ SyntaxError: invalid syntax Also when I comment the contact URL out, I get the same error for an exact same "about" URL but with only "about" not "contact". If you need any other code please tell me. -
Error Traceback : Identity_set_unique = Symptom.objects.get(pk=pk). This is returning a ValueError
In my health app I am attempting to allow that user to enter patient symptom data and save it. Model logic I have three models created : Unique_Identity , Symptom, and Unique_Identity_Symptom In Unique_Identity there is the symptom_relation = models.ManyToManyField(Symptom, through = 'Unique_Identity_Symptom') field that connects to the Symptom model establishing a ManyToMany relationship In the Unique_Identity_Symptom model there are the patient = models.ForeignKey(Unique_Identity, related_name = 'symptoms') and symptom = models.ForeignKey(Symptom, related_name = 'reports') fields, however I am beginning to doubt the necessity of the Unique_Identity_Symptom model. Issue : THe problem is that each time I attempt to save the inserted data using the ModelForm created for the Symptom model I get this error : ValueError at /optic/Symptom-document/U849343/ invalid literal for int() with base 10: 'U849343' Traceback: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/iivri.andre/vedic/Identity/optic/views.py" in post 113. Identity_set_unique = Symptom.objects.get(pk=pk) I have already tried this post, this, this and this but none of the answers are specific to my question. … -
Getting data from a uri django
I have a django view that takes in a json object and from that object I am able to get a uri. The uri contains an xml object. What I want to do is get the data from the xml object but I am not sure how to do this. I'm using django rest, which I am fairly inexperienced in using, but I do not know the uri until the I search the json object in the view. I have tried parsing it in the template but ran into CORS issues amongst others. Any ideas on how this could be done in the view? My main issue is not so much parsing the xml but how to get around the CORS issue which I have no experience in dealing with -
No module named django.core.urlresovers in django 2.0a1
Have recently upgraded from django 1.11.7 to django 2.0a1 and now cannot import reverse_lazy File "/home/silasi/Deprojecto/eljogo/jogos/views.py", line 8, in <module> from django.core.urlresolvers import reverse_lazy ModuleNotFoundError: No module named 'django.core.urlresolvers' -
How to add a confirmation page to an email form in django? Problems with django formtools or session data.
What I want to accomplish I want a page where user fill a form to send an email (to multiple recipients). Before sending, the user should see the hole email an all recipients and should confirm the sending or go back and edit it. What I have tried Using django formtools. https://github.com/django/django-formtools https://django-formtools.readthedocs.io/en/latest/ The Problem Formtools seems to only work if I derive the form from a model and I see no reason to do that. What I have else tried Saving the input in request.session. The Problem Recipients are a list of objects (ModelMultipleChoiceField). In request.session I can only save JSON data. Thus I can not serialize it. I could extract the email addresses of the recipients list but if the user wants to go back to the form I can not prefill the ModelMultipleChoiceField. So I ran out of ideas. -
Django model convert IntegerField to ForeingKey keeping date
i'm working ina project where I need to migrate an IntegerField to a ForeingKey to make it easier to do requests as: SKU_name, SKU_description, etc.. My models.py file has: class BasketTable(models.Model): """Basket table.""" # Generic data structure from the table internal_id = models.AutoField( primary_key=True, verbose_name="ID PK") internal_insertDate = models.DateTimeField( default=timezone.now, verbose_name="Data/Hora de Inserção") internal_updateDate = models.DateTimeField( default=timezone.now, verbose_name="Data/Hora de Atualização") # Specific fields from VTEX table List_Id = models.CharField( max_length=250, null=True, blank=True, verbose_name="ID da Lista") ListType_Id = models.CharField( max_length=250, null=True, blank=True, verbose_name="ID do Tipo de Lista") Alias = models.CharField(max_length=250, null=True, blank=True, verbose_name="Alias") SKU_Id = models.IntegerField(default=0, verbose_name="ID do SKU") Product_Id = models.IntegerField(default=0, verbose_name="ID do Produto") Quantity = models.IntegerField(default=0, verbose_name="Quantidade") I'm trying to change SKU_Id to SKU field name, setting: SKU = models.ForeignKey(SKUTable, db_column='Id', to_field='Id', null=True, verbose_name="ID do SKU") My SKU Id field has unique=True as needed according Django documentation. So, after this changes, I run python manage.py makemigrations command that results: class Migration(migrations.Migration): dependencies = [ ('products', '0013_auto_20171103_1412'), ('cil', '0016_auto_20171020_1546'), ] operations = [ migrations.RemoveField( model_name='baskettable', name='SKU_Id', ), migrations.AddField( model_name='baskettable', name='SKU', field=models.ForeignKey(db_column='Id', null=True, on_delete=django.db.models.deletion.CASCADE, to='products.SKUTable', to_field='Id', verbose_name='ID do SKU'), ), ] So, I changed this migration file to: class Migration(migrations.Migration): dependencies = [ ('products', '0013_auto_20171103_1412'), ('cil', '0016_auto_20171020_1546'), ] operations = [ …