Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django raw sql - params not being executed as expected - syntax error
I execute rawsql within a django app (pgsql 9.6 backend) like so: obj=AddModel.objects.raw(""" SELECT * FROM "codeaddmodel" \ WHERE ("codeaddmodel"."data" -> 'CodeData') \ @> '[{"street": "New Street" }]' """) and it works brilliantly. Now, I do the following, as per the django doc, and use params: term="New Street" obj=AddModel.objects.raw(""" SELECT * FROM "codeaddmodel" \ WHERE ("codeaddmodel"."data" -> 'CodeData') \ @> '[{"street": %s }]' """,[term]) and this throws the error: django.db.utils.ProgrammingError: syntax error at or near "New" I have tried for around two hours and google has failed me! -
Where I can write myself logic when I want to create other instance using Rest Framework?
Where I can write myself logic when I use Rest Framework? I have a serializers: class OrderSerializer(ModelSerializer): order_num = serializers.SerializerMethodField() price = serializers.SerializerMethodField() class Meta: model = Order fields = ('name', 'room', 'price', 'order_num') def get_order_num(self, obj): return str(now()) + "111" def get_price(self, obj): print(obj, "liao obj") return "0.10" And I have a views: class OrderCreateAPIView(CreateAPIView): serializer_class = OrderSerializer queryset = Order.objects.all() The models is bellow: class Room(models.Model): name = models.CharField(max_length=12) number = models.IntegerField() class Order(models.Model): name = models.CharField(max_length=12) order_num = models.CharField(max_length=12) price = models.CharField(max_length=12) room = models.ForeignKey(to=Room, related_name="orders") start_time = models.DateTimeField(null=True, blank=True) end_time = models.DateTimeField(null=True, blank=True) This demo is my test demo, don't care the details. And my goal is want to create a instance of room when I access the view/serializer. enter image description here You see the snapshot, I can create the Order instance success, but my goal is when create a Order, I want to create a Room instance(don't care the room's initial data, just for test we can set it constant data). and return the room's id. I don't know where to do to create Room instance logic. some friends can help me with that? -
Django How to download existing file?
in my django 'views i create a pdf file and i want to download it. The file exist (path: /app/data/4.pdf) and i launch this command: def download_line(request): if not request.is_ajax() and not request.method == 'GET': raise Http404 try: fs =FileSystemStorage('/app/data') with fs.open('4.pdf') as pdf: response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition']='attachment; filename="4.pdf"' except Exception as e: logger.warning("Download Line | Erreur : " + e.message) return response But the download doesn't start and no error. Have you got a solution? Thanks. -
Why I am getting an "(admin.E003) The value of 'raw_id_fields[N]' must be a ForeignKey or ManyToManyField." error in Django app?
I want to make a schema migration, just add 1 field to Model and to ModelAdmin. class MyModel(models.Model): some_field = models.ForeignKey(SomeModel) my_new_field = models.CharField(max_length=20, blank=True, null=True, choices=[(b'1', b'1'), (b'2', b'2')]) class MyModelAdmin(admin.ModelAdmin): list_display = ['some_field', 'my_new_field'] raw_id_fields = ('some_field', 'my_new_field',) And I got : (admin.E003) The value of 'raw_id_fields[1]' must be a ForeignKey or ManyToManyField. How can I fix that? I write an app with Python 2.7, Django 1.8 and PostgreSQL. I also use Docker containers for backend and PostgreSQL. -
Getting an http response that is impossible to occur = django
I have a form that I am processing in django. It is processing the form correctly but after the processing is done, it is throwing an http response error which could not possibly be happening... here is the form: # create a new expense form - group class CreateExpenseForm(forms.ModelForm): split_choices = (('1', 'even'), ('2', 'individual')) split = forms.TypedChoiceField( choices=split_choices ) class Meta: model = Expense fields = ['location', 'description', 'amount', 'split'] here is the view : I am going to break where the error is happening: if request.method == 'POST': form = CreateExpenseForm(request.POST) if form.is_valid(): cd = form.cleaned_data location = cd['location'] description = cd['description'] amount = cd['amount'] split = cd['split'] reference = generate_number() for member in members: if member.user.username in request.POST: new_expense = Expense.objects.create( user = member.user, group = group, location = location, description = description, amount = amount, reference = reference, created_by = user, ) print('all exepense accounted for') 'all expenses accounted for' is printing in the terminal then it throws the error now with the form, there are only two choices that split can be which are 1 and 2 I am selecting option 1 (even) so the split should be one, but none of the print message … -
redirecting every url to 500 server error django
my django application works in local development server. To deploy in heroku I had to use whitenoise for serving static files. The app is deployed successfully but now when I switch debug flag to False, i get server side error on both development and production server. This is my confiugration local_settings.py from decouple import config import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) import os from decouple import config import dj_database_url # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = ['*'] # Application definition DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', ] OUR_APPS = [ 'inventory', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + OUR_APPS SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'IMS.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_collected") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns = [ url(r'^accounts/', include('allauth.urls')), url(r'^', include('inventory.urls')), url(r'^admin/', admin.site.urls), ] handler404 = 'IMS.views.page_not_found' handler500 = 'IMS.views.server_error' if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, … -
Django crontab not executing scheduled job function
I'm using django-crontab for writing cron jobs. But, it's not working. I have below settings for cron job in my settings.py. INSTALLED_APPS = [ ...... 'django_crontab', ] CRONJOBS = [ ('*/3 * * * *', 'attendance.cron.my_scheduled_job', '>> cron_log.log'), ] # CRONTAB_LOCK_JOBS = True CRONTAB_COMMAND_SUFFIX = '2>&1' I have already added the cron job to crontab. Running python manage.py crontab show shows the cron job. Currently active jobs in crontab: 121f407963db57f1ee41ad82a335b93e -> ('*/3 * * * *', 'attendance.cron.my_scheduled_job', '>> cron_log.log') In attendance/cron.py I have this. def my_scheduled_job(): print("In cron job") It shows nothing. No cron_log.log file either. I've already checked this question. How can I get this to work ?? -
How to use googlemap geocoder for multipleMarker
I successfully run for single target marker using geocoder using This is code. But i want to mark multiple targets. I know how to do this without Geocoder but I have to use Geocoder because I only have location name list. <script type="text/javascript"> var geocoder; var map; // Location for Google Map var address =" {{ object.LocName }} "; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 18, center: latlng, mapTypeControl: true, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); if (geocoder) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { map.setCenter(results[0].geometry.location); var infowindow = new google.maps.InfoWindow( { content: '<b>'+address+'</b>', size: new google.maps.Size(150,50) }); var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map, title:address }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } else { alert("No results found"); } } else { alert("Geocode was not successful for the following reason: " + status); } }); } } </script> website back-end is Django. I can loop through in location name like this {% for object in object_list %} {{ object.LocName }} {% endfor %} Please tell me How … -
Django timesince less than values
Does the Django "timesince" filter work with less than "<=" values? I can only get it to work with greater than ">=" values. I only want to show clients created in the past week. this code does not work. {% for c in clients %} {% if c.created|timesince <= '7 days' %} <li><a href="">{{ c.name|title }}</a></li> {% endif %} {% endfor %} thanks. -
WAMP wont load localhost after integrating django project
My WAMP works fine without including the code its httpd.conf file for integrating a django project. As soon as I put the code it does not load local host. I used the code shown below in various ways, like with and without loadmodule,static , DirectoryIndex, and most possible ways. httpd.conf LoadModule wsgi_module modules/mod_wsgi.so DirectoryIndex index.py default.py wsgi.py WSGIScriptAlias /django-project /C:/wamp/www/sample/sample/wsgi.py WSGIPythonPath /C:/wamp/www/sample/ <Directory /C:/wamp/www/sample/> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> Alias /static C:/wamp/www/static <Directory "C:/wamp/www/static"> Order deny,allow Allow from all Require all granted </Directory> -
In DRF(Django Rest Framework) Docs, how to describe the Fields?
In DRF Docs, how to describe the Fields? I scan the docs did not find how to do with that. In my project, I configured the drfdocs, the bellow is one of my APIs: How to describe the Field(I mean like the 云服务器开机 describe the /api/user_productmanage/cloudserver/start/)? and whats the R in the CharField behind? -
Django custom registration model same like django.contrib.auth
Is there any way to implement the custom model and form for user registration. I want to create the model for clients having their personal information and username, password. So I am searching a way to generate password same as django's default and want to save in my custom model. -
Django TCP server with tornado
I want my django app to communicate by using a TCP/IP socket with a remote computer and I would like that socket to be available at all times. I would like to use the library tornado. Since I'm only familiar with writing views and models and such, I'm not entirely sure where to fit that into my codebase. I was thinking about writing a management command that would run the tornado's server (see http://tornado.readthedocs.io/en/latest/tcpserver.html), but how could I call .stop() on my server once the management command quits? I wouldn't want it to spawn any threads that wouldn't exit upon my management command exiting, or end up with multiple open sockets, because I just want one. Ofcourse I would also like the listener to reside somewhere in my django program and have access to it, not only within the management command code. I was thinking about importing a class from django's settings. Am I thinking in the right direction, or is there a different, better approach? -
guardar varios registros desde un form en Django
Buenas noches, quisiera me ayuden en como almacenar varios registros desde un form de Django, la idea es que tengo una lista de subscriptores a los cuales se les envia un mensaje definido por el usuario, tengo lo siguiente pero no me guarda la informacion: def EnvioMensaje(request): ListaSuscriptores= Suscriptores.objects.all() for suscriptor in ListaSuscriptores: if request.method=='POST': form=EventoForm(request.POST) if form.is_valid(): ejemplo=form.save(commit=False) ejemplo.id_suscriptor=suscriptor.id ejemplo.save() return redirect('index') else: form=EventoForm() return render(request,'template.html', {'form':form}) -
django database update using BeautifulSoup
Im very new to Django. I have been running through tutorials and decided to start on something of my own and need a little advice on the best way forward. I'm creating a simple site which runs through a small list of URLS stored in a postgreSQL table and uses Beautiful Soup to extract data from each of the URL pages and store it against the record.. (its just stats recorded on the home page of each) Ive set up the model and the relevant class listview to display them all. About to start running through the beautiful soup part and wondered where should physically put the code to run through and "scrape" the data for each site? Should it be something called when the class view is called? Some kind of Model Manager? Just a bespoke Function or something? I would like to use Ajax to update this data in intervals if possible so it needs to fit in with that. Hopefully that's not too vague. Happy to post what i have if you feel that's beneficial although it is literally just a simple model and Class ListView. Thanks! -
Execute custom python script from Django models
Trying to execute a python script from Django models and I receive the following error: " File "D:\FL\Django\mysite\uploadfileapp\models.py", line 23, in get_absolute_url Best_model_forecast_v11.main(user_avatar) NameError: name 'Best_model_forecast_v11' is not defined". The above script is located in same app directory with models.py from django.db import models from uploadfileapp.Best_model_forecast_v11 import * # Create your models here. from django.urls import reverse class User(models.Model): #the variable to take the inputs user_name = models.CharField(max_length=100) user_avatar = models.FileField() # on submit click on the user entry page, it redirects to the url below. def get_absolute_url(self): Best_model_forecast_v11.main(user_avatar) return reverse('uploadfileapp:home') -
TypeError: __init__() got an unexpected keyword argument in Django Form & Formset
In following the Django docs on "Passing custom parameters to formset forms", I get the following returned: __init__() got an unexpected keyword argument 'choices' File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in forms 144. for i in range(self.total_form_count())] File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in <listcomp> 144. for i in range(self.total_form_count())] File "/Users/emilepetrone/Envs/kishikoi/lib/python3.6/site-packages/django/forms/formsets.py" in _construct_form 182. form = self.form(**defaults) File "/Users/emilepetrone/Sites/kishikoi/kishikoi/transactions/forms.py" in __init__ 119. super(SoldTransactionForm, self).__init__(*args, **kwargs) Exception Type: TypeError at /transactions/create/sell/transactions/31tmhqsplg41jc8c/ Exception Value: __init__() got an unexpected keyword argument 'choices' Here is my view where I follow the documentation and pass 'choices' in the formset form_kwargs. class SellTransactionsView(LoginRequiredMixin, SetHeadlineMixin, UpdateView): model = Transaction template_name = "transactions/soldtransaction_form.html" headline = "Sell Transaction" fields = ['num_shares'] def get_object(self): return Transaction.objects.get( user=self.request.user, identifier=self.kwargs['identifier'] ) def get_choices(self): transaction = self.get_object() choices = Transaction.objects.filter( user=transaction.user, ).exclude(identifier=transaction.identifier) return choices def get_context_data(self, *args, **kwargs): context = super(SellTransactionsView, self).get_context_data( *args, **kwargs) choices = self.get_choices() formset = SoldFormset(form_kwargs={'choices': choices}) context.update({ "formset": formset, }) return context My Form & Formset- I'm using a forms.Form because I will be using these fields to update a different field in form.is_valid(). class SoldTransactionForm(forms.Form): old_transaction = forms.ChoiceField() num_shares = forms.IntegerField( min_value=0 ) class Meta: fields = [ 'old_transaction', 'num_shares', ] def __init__(self, *args, … -
Slugify issue in django template
I have a link in a django html template. I want to pass in a slugified string to the view for processing. I am getting an error and it is no slugifying the string. here is the code I have. Am I missing something or do i need to add something for slugify to work on the string... <p><a href="{% url 'group_home' group.group.name|slugify %}">{{ group.group.name }}</a></p> url: url(r'^(?P<groupname>[\w+]+)/$', views.group_home, name='group_home'), string example: first group here is the error: NoReverseMatch at /groups/ Reverse for 'group_home' with arguments '('first-group',)' not found. 1 pattern(s) tried: ['groups/(?P<groupname>[\\w+]+)/$'] Another question I have is how do i unslugify a string once I am in the view. -
Add shortcodes based on database fields
I'm trying to incorporate both a form builder and wysiwyg editor together by adding shortcodes. But, I'm fairly new to the concept and was wondering how it would be possible to add shortcodes based on the saved database values I obtained from the form builder? My goal is to have a dropdown of all the shortcodes based on the form values. I'm using easyformgenerator as form builder and tinymce as the editor. This is the sample plugin I added to tinymce: tinymce.PluginManager.add('shortcodes', function(editor, url) { editor.addButton('shortcodes', { type: 'listbox', text: 'Shortcodes', icon: false, onselect: function (e) { editor.insertContent(this.value()); }, values: [ { text: 'Username', value: '|USER username|' }, { text: 'Display Name', value: '|USER display_name|' }, { text: 'First Name', value: '|USER first_name|' }, { text: 'Last Name', value: '|USER last_name|' }, ], }); }); I hope you can help me by providing examples. Thanks. -
bootstrap4.0 include search form and signing in the navbar
I am trying to put the sign in tab at the right corner in the navbar, also I want to put the search form as well, but I am not getting proper alignment as shown in the figure and this my code for navbar and I am using bootstrap4.0 and I am using the following files <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> I am trying to modify the following example https://getbootstrap.com/docs/4.0/examples/jumbotron/ <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Project</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> {% url 'home' as home %} {% url 'about' as about %} {% url 'about' as contact %} <li {% if request.path == home %} class="nav-item active" {% endif %}> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> <li {% if request.path == about %} class="nav-item" {% endif %}> <a class="nav-link" href="{% url 'about' %}">About</a> </li> <li {% if request.path == contact %} class="nav-item" {% endif %}> <a class="nav-link" href="{% url 'contact' %}">Contact</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Account</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> {% if not … -
how to html escape a string before passing it to view - Django
I had a very small and quick question. I have a django url in an app that takes in a variable called groupname. groupname is passed from the html template as a link redirect. The groupname string has a space in it and it is not passing through as a string with spaces in it... how can I make it so that the string with spaces can be passed into the url. I am retty sure I have to add a _ to replace the spaces, but idk how to do that from an html template redirect. also how can i get rid of the _ in the string when I am in the view... urls.py: url(r'^(?P<groupname>[\w+]+)/$', views.group_home, name='group_home'), html template: <p><a href="{% url 'group_home' group.group.name %}">{{ group.group.name }}</a></p> sample name: first group how can I pass the sample name through the url.. and then take out the _ once in the view.. views.py: # ensure someone is logged in @login_required # individual groups home page def group_home(request, groupname): hello = 'hello' return render(request, 'groups/group_home.html') -
Django ModelFormSet KeyError
Okay. Finaly caving in and asking for a second set of eyes/guidance. I keep getting a ***KeyError on my Django model formset, specifically in the POST when I am trying to save the form(s). The specific error is *** KeyError: 'question' Now 'question' is a field in my model and form in my formset. I am used to getting the MultiValueDictKeyError when working with formsets but never a plain 'ol KeyError. Model: class RecapTextAnswer(Model): recap = ForeignKey(Recap, related_name='text_answers') question = ForeignKey(RecapQuestion) answer = TextField(null=True, blank=True) Form: class CrispyRecapTextAnswerForm(forms.ModelForm): class Meta: model = RecapTextAnswer fields = '__all__' FormSet: RecapTextAnswerFormSet = formset_factory(CrispyRecapTextAnswerForm, extra=0) request.POST <QueryDict: {'text-1-question': ['33'], 'text-MAX_NUM_FORMS': ['1000'], 'text-0-answer': ['asdf'], 'text-2-recap': ['33'], 'text-1-answer': ['This is my answer'], 'text-1-recap': ['33'], 'text-2- answer': ['asdf'], 'text-TOTAL_FORMS': ['3'], 'text-INITIAL_FORMS': ['3'], 'csrfmiddlewaretoken': ['MpsjTT0tEqkrlAm06YnJ0ODFnDrI2wotzCX0A7JKJm23YWHAPp1bzMZhZe2HtZPq', 'MpsjTT0tEqkrlA m06YnJ0ODFnDrI2wotzCX0A7JKJm23YWHAPp1bzMZhZe2HtZPq', 'MpsjTT0tEqkrlAm06YnJ0ODFnDrI2wotzCX0A7JKJm23YWHAPp1bzMZhZe2HtZPq', 'MpsjTT0tEqkrlAm06YnJ0ODFnDrI2wotzCX0A7JKJm23YWHAPp1bzMZhZe2H tZPq'], 'text-0-question': ['38'], 'text-MIN_NUM_FORMS': ['0'], 'text-2- question': ['32'], 'text-0-recap': ['33']}> View: fs = RecapTextAnswerFormSet(self.request.POST, prefix='text') if fs.is_valid(): fs.save() I can raise the error when calling fs.is_valid(), fs.forms or fs.cleaned_data -
Pycharm - cannot login with valid admin account
I created my custom user model and use to create a super user, but I cannot login with my username and password. class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.username = username user_obj.save(using=self.db) return user_obj def create_superuser(self, username, first_name, last_name, email, home_address, password, image_path): return self.create_user( username=username, email=email, password=password, ) class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(blank=True, unique=True) created_time = models.TimeField(auto_now=True) active = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() I tried to get a user in the database with my username, it succuss. AUTH_USER_MODEL ='CustomUser.User' is added to settings.py Thanks in advance if anybody can help! -
Accessing a single model between multiple apps - Django
I have a Django project with two app that are users and groups. I have a model named Friend in the users app. I want to access the model in the groups app. How can I import the Friend model from the users app within the groups app. I want to access the other models to make queries and querysets in the groups app from the models in the groups app. Here are the import statements I have right now... Imports for the views in the users app: from .forms import * from .method import * from .models import * Imports for the veiws in the groups app: from .forms import * from .models import * How can i import the users models in the groups app. I also want to import the groups models in the users models. Here is the current directory.... -
migration errors for project using django-csvimport
I am having trouble moving my Django 1.11 app to production. There's another question that looks like a similar issue, but I am unable to make the answers suggested in the comments work as desired: Django import errors for app csvimport if I comment out the code in settings.py to remove the django-csvimport library stuff like so: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', # 'csvimport.app.CSVImportConf', 'custom_app_name', ] then my migrations work fine, and the app runs(sans csvimport app). Then if I comment the csvimport APP line back in and run the migrations, they fail with the following: Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, custom_app_name Running migrations: Applying csvimport.0002_test_models...Traceback (most recent call last): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "csvtests_country" LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line …