Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tables change header by variable
Using django-tables2 I try to have 2 dimensions table. I tried to make this using accessors with the docs here But it doesn't work at all. I don't seen any example and I don't know if it's possible. Has anyone has an idea? Here my code : #views.py def visualiserTableResult(request): choix= request.POST['type_donnees'] sample = Sample.objects.all() antibiotique = Antibiotique.objects.all() data = [] for s in sample: for a in antibiotique: echantillon = Echantillon.objects.filter(antibiotique_id=a.antibio_id).filter(sample_id=s.sample_id).values( 'echantillon_id') if choix == "CMI": res = Resultats.objects.filter(echantillon_id=echantillon).values_list("res_CMI") if choix == "SIR": res = Resultats.objects.filter(echantillon_id=echantillon).values_list('res_SIR', flat=True) if choix == "diametre": res = Resultats.objects.filter(echantillon_id=echantillon).values_list('res_diametre', flat=True) data.append({s: {a: res}}) table = GeneralTable(data) RequestConfig(request).configure(table) return render(request, 'resistance/visualiserTableResult.html', {'table': table}) #tables.py class GeneralTable(tables.Table): sample = tables.Column(accessor=('s')) antibiotique = tables.Column(attrs={'th': {'antibiotique': 'a'}}) class Meta: attrs = {'class': 'paleblue'} #models.py class Echantillon (models.Model): echantillon_id = models.IntegerField(primary_key=True) antibiotique = models.ForeignKey('Antibiotique', on_delete=models.CASCADE) sample = models.ForeignKey(Sample, on_delete=models.CASCADE) resistance = models.ManyToManyField( 'Type_resistance', through='Resultats' ) class Resultats (models.Model): resultats_id = models.IntegerField(primary_key=True) echantillon = models.ForeignKey('Echantillon', on_delete=models.CASCADE) resistance = models.ForeignKey('Type_resistance', on_delete=models.CASCADE) res_CMI = models.DecimalField(max_digits=5, decimal_places=2,null=True) res_SIR = models.CharField(max_length=10, null=True) res_diametre = models.DecimalField(max_digits=5, decimal_places=2, null=True) comment = models.TextField(null=True) I want to have a table with values of "antibiotique" in headers and result for each sample.I hope that someone have an idea -
django tag 'get_recent_articles' received too many positional arguments
I am trying to make a recent article list in the sidebar of my blog. So I make a tag in templatetags. I use django1.8 and python2.7. templatetags/blog_tags.py from ..models import Article,Category from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def get_recent_articles(num=5): return Article.objects.all()[:num] base.html {% load blog_tags %} <!DOCTYPE html> ... <div class="widget widget-recent-posts"> <h3 class="widget-title">recent</h3> {% get_recent_articles as article_list %} <ul> {% for article in article_list %} <li> <a href="{{ article.get_absolute_url }}">{{ article.title }}</a> </li> {% endfor %} </ul> </div> When I runserver,Template error,Traceback display the problem line is {% get_recent_articles as article_list %} TemplateSyntaxError at /blog/index/ 'get_recent_articles' received too many positional arguments How do I solve this error? Please give me some advices. Any help will be much appreciated. -
Django tables2 dispalys time as am/pm instead of 24H standard
I'm currently working on a website in Django, where data from a MySQL database is shown with Django-Tables2. The issue is that all TIME fields in the database gets converted into am/pm instead of 24 hours as the standard should be from what I've gathered. I've seen multiple of people with the opposite issue but none of those solutions has worked. After googling and trying for almost a week, I'm not asking the community. Is there a way to force the time standard for the TimeFormat fields in Django to correspond to the same format as the MySQL TIME (unlimited/24 hours)? It would be very helpful as I'm currently displaying time intervals, and 00:25 which should be 25 minutes is shown as 12:25 pm. -
Login through REST API in Django
I have a Django REST API server for my project. It uses built-in login system on http://127.0.0.1:8080/api-auth/login/. I have additional Django project, that interacts with REST server and manage info from it. To view data, firstly I need to log in. So I created a form in forms.py: class LoginForm(forms.Form): username = forms.CharField(label='username', max_length=50) password = forms.CharField(widget=forms.PasswordInput()) And html template: <form action="{% url 'todolist:login' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Login" /> </form> And appropriate view in views.py: class LoginView(View): def get(self, request, *args, **kwargs): form = LoginForm() return render(request, 'login.html', {'form': form}) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): post_data = {'username': form.cleaned_data['username'], 'password': form.cleaned_data['password']} response = requests.post('http://127.0.0.1:8080/api-auth/login/', data=post_data) return HttpResponseRedirect('/todolists/') But I get 403 Forbidden. What is a proper way to manage authorization? -
What is the correct way to auto-create related model objects in django-registration?
I'm a total Django newbie and apologize in advance if I'm not using the correct terminology. I'm using django-registration to register user on my web-app. I've successfully adapted it work with my custom user model GeneralUser. Conceptually, each GeneralUser has a Business, another model that I've defined. Whether this is the correct decision or not, I've decided that I never want to register a user without a related Business object. I've read countless threads on customizing django form, and finally after a few days of unsuccessful attempts, came upon an answer that helped reach a solution. However, I am unsure that my code is correct/safe. This is my adaptation, followed by the linked-answer: my adaptation: class GeneralUserForm(UserCreationForm): business_name = forms.CharField(required=True) class Meta: model = GeneralUser fields = ['username', 'email', 'password1', 'password2', 'business_name'] def save(self, commit=True): user = super(UserCreationForm, self).save(commit=True) business = Business(name=user.business_name, owner=user) # notice: no if-block user.save() business.save() # notice: returning only a user-instance return user This code successfully creates a user and a business object, and creates the relationship. Looking at the original answer code though, I wonder if there isn't something critical I'm missing: Answer I based my code on: class UserCreateForm(UserCreationForm): job_title = forms.CharField(max_length=100, required=True) age … -
pass username in url after login - django
My default project folder is startup with login app in it. login app urls.py:- url(r'^$', views.LoginFormView.as_view(), name='index'), url to login page. inside Login app views.py: LoginFormView(TemplateView): .......... ......... if user is not None: if user.is_active: login(request, user) # messages.add_message(request, messages.INFO, 'Login Successfull.') return redirect('indexClient') login form submitted and redirect to user profile page. startup urls.py:- url(r'^client/', views.IndexClientView.as_view(), name='indexClient'), startup views.py:- class IndexClientView(TemplateView): template_name = 'startup/index-client.html' I need the url to replace client with username entered in login form. -
Django1.6 rawquery: while fetching timezone aware datetime field from postgres gives same value but with timezone as UTC
I am trying to fetch datetime field from postgres using django1.6 raw query because of some complexity in querying. The datetime field is saved in postgres at timezone +5:30. When i tried like following it gives result with utc timezone but the datetime value is same as +5:50 I tried like following: a=Request.objects.raw("SELECT id,request_time from app_request") for i in a: print i.request_time 2017-05-08 20:33:52.128000+00:00 2017-05-08 20:33:52.815000+00:00 Values is postgres is: 2017-05-09 02:03:52.128+05:30 2017-05-09 02:03:52.815+05:30 It causes wrong value display in the browser. How can I solve this? -
TypeError: unorderable types: Study() < int()
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe C:/Users/Administrator/Desktop/pythonworke/untitled/20170508/cmp.py Traceback (most recent call last): File "C:/Users/Administrator/Desktop/pythonworke/untitled/20170508/cmp.py", line 10, in <module> if study < -10: TypeError: unorderable types: Study() < int() -
How to save a checkboxed values to ManyToManyField in django with a through relationship?
I'm currently working on a fairly simple django project and could use some help.Currently I am stuck on saving form using checkboxes. I have the following models with a ManyToMany and through relationship: class ProfileMatch(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,unique=True) profiles = models.ManyToManyField(UserProfile,blank=True) def __unicode__(self): return "Profile id: %s" %(self.user.id) I created a HTML form for this with checkbox .Selected profiles_id should save with associate user_id <form action="." method="POST" class="post-form">{% csrf_token %} <thead> <th>Select</th> <th>Profile-ID</th> </thead> <tbody> {% for user in userprofiles %} <tr> <label class="checkbox"> <input type="checkbox" name="user" data-toggle="checkbox" value="{{ user.pk }}"> </label> <td>{{ user.profile_id }}</td> </tr> {% endfor %} </tbody> </table> <button type="submit" class="save btn btn-default">Add Selected </button> </form> And a simple view to save the form: def PremuiumUserProfileSelectList(request, pk): match = ProfileMatch.objects.get(pk=pk) if request.method == 'POST': if request.POST.getlist("user", None): checked = request.POST.getlist("user", None) premium_user = User.objects.get(pk=pk) m = match(user=premium_user, profiles=checked) m.save() else: return render(request, "premiumuser/selected_list.html", context) else: return render(request, "premiumuser/selected_list.html", context) This doesn't saves the form.Form fields were rendered and all selected profiles_id's are showing in a list .How do I save this Form ?I want to save all selected checkbox values in associated user.How do I save it? -
Django Directory Structure
I am new to learning Django and I know how important setting up an application directory structure can be for future additions. At the moment, I am creating an API using the Django REST Framework and have a few questions on how to structure a Django project for future success. I want the API to feed out possibly in the future to other sources that may need to grab data. I also will be building a front-end CRUD like system to display and update data. How would you suggest structuring the directories in the future possibility of adding more front-end like systems that are all powered by the Data API? Doing some research already, it seems like these are possibilities I have seen. project manage.py project settings.py urls.py api models.py serializers.py views.py crudapp files here... project manage.py project settings.py urls.py api models.py serializers.py views.py crudapp files here... I am really trying to understand how Django and Python should have these modules setup. If I have separate modules/apps setup, they can all access the models in the API app for any sort of app I build in the future? Any clarification or experience on this would be greatly appreciated. The main … -
Inventory design management - FIFO / Weighted Average design which also needs historical inventory value
I have a database with the following details: Product Name SKU UOM (There is a UOM master, so all purchase and sales are converted to base uom and stored in the db) Some other details has_attribute has_batch Attributes Name Details/Remarks Product-Attribute Product (FK) Attribute(FK) Value of attribute Inventory Details #This is added for every product lot bought & quantity available is updated after every sale Product (FK) Warehouse (FK to warehoue model) Purchase Date Purchase Price MRP Tentative sales price Quantity_bought Quantity_available Other batch details if applicable(batch id, manufactured_date, expiry_date) Inventory Ledger #This table records all in & out movement of inventory Product Warehouse (FK to warehoue model) Transaction Type (Purchase/Sales) Quantity_transacted(i.e. quantity purchased/sold) Inventory_Purchase_cost(So as to calculate inventory valuation) Now, my problem is: I need to find out the historical inventory cost. For example, let's say I need to find out the value of inventory on 10th Feb 2017, what I'll be doing with the current table is not very efficient: I'll find out current inventory and go back through the ledger for all 1000-1500 SKU and about 100 transactions daily (for each sku) for more than 120 days and come to a value. taht's about 1500*100*120. It's Huge. … -
Crispy django forms results in internal server error when accessed via uwsgi
I have a simple form in django, which I'm trying to display with crispy forms. Django Django-1.11.1, uwsgi 2.0.15, nginx 1.10.3-1, django-crispy-forms 1.6.1. I've installed django-crispy-forms (sudo pip3 install django-crispy-forms) and I've followed their documentation, setting everything up. In the settings.py: [...] INSTALLED_APPS = [ [...] crispy_forms, ] CRISPY_TEMPLATE_PACK='bootstrap3' In my template: {% load crispy_forms_tags %} [...] <form action="{{ action }}" method="POST"> {% csrf_token %} {% crispy form %} <input type="submit" value="Submit"> </form> The form: class UploadForm(forms.Form): f = forms.FileField(label="File") comment = forms.CharField(max_length=255,strip=True,required=False) Now, once I include crispy_forms to my INSTALLED_APPS, the web application just shows Internal Server Error (via nginx & uwsgi). If I run it directly via python3 manage.py runserver, everything appears to work perfectly fine. Did I miss a step in the configuration of uwsgi, or how else can I fix this issue? -
Read json extra fields and associate with create method django rest api
How can I read extra content of JSON data to associate with my creation user model by sending something like this: { "extrafieldstring": "hey_" "username": "test", } Here's the code for my serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', ] def create (self, validated_data): c = extrafieldstring???+validated_data['username'] user = User.objects.create(username=c) user.set_password(User.objects.make_random_password()) user.save() return user I don't want to include another model to do this task. Is it possible to do this? -
I want to know the way django websites consume RAM or computer memory
I am about to develop a website. And, I expect to get a lot of traffic in it. It is in python (Django). I wonder if my web application uses 2 MB of RAM for one service(like if I run it in my PC directly in terminal, it consumes 2 MB of RAM) then if I get 1000 users on my website in a particular time, will my website need 2000 MB of RAM (2MB per user * 1000 users)? Does it go this way? -
Mezzanine With Django Sitetree admin page throw no reverse match
I add django-sitetree module to my django mezzanine app But when I try to add sitetree item, it throws error NoReverseMatch at /en/admin/sitetree/tree/1/item_add/ Reverse for 'sitetree_treeitem_add' with arguments '()' and keyword arguments '{'tree_id': u'1'}' not found. 1 pattern(s) tried: [u'en/admin/sitetree/tree/((?P<tree_id>\\d+)/)?item_add/$'] When I trace it to mezzanine source code, it occurs when it tries to do translate_url function with sitetree_treeitem_add. It tries to find it on my app.urls configuration which is not in there. Is there any django-sitetree spesific urls that I need to add to my app.urls? Because I tried to find it on django-sitetree url, I cant find one Mezzanine == 4.2.3 Django-sitetree == 1.8.0 -
Cannot convert django admin instance into and integer for math operations
I'm quite new to python and I have django admin instances which I am getting from a queryset and I would like to convert them to integers so that I can apply math operations on them. An example is person.height == Person.objects.get(height = 140). I want to use it as follows; def getHeight(): cm = 0 if person.height == Person.objects.get(height = 140): cm = 1 else: cm = 0 return cm Now when i do the following in_centimetres = getHeight() print(in_centimetres) print type(in_centimetres) I get the following as outputs: <persons.admin.operable instance at 0x7fac04bf29e0> and <type 'instance'> I want to be able to get 0 or 1 so that I can perform math operations with that value. -
Django REST api returns an integer (`3`) but AngularJS reads it as `%203`. How do I make Angular read it as 3?
This is my DRF view which gets called at /posts/{id}: class PostViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericViewSet): serializer_class = PostSerializer permission_classes = (IsAuthenticated, IsActualOwnerDelete,) def get_queryset(self): # new drops from location. return Post.objects.filter(location=self.request.user.userextended.location).order_by('-createdAt') def perform_create(self, serializer): serializer.save(actualOwner=self.request.user) @list_route(permission_classes=[IsAuthenticated]) def mymostrecent(self, request): me = request.user try: # this gets the most recent post's ID post = me.post_mine_set.latest('id') did = post.id except Drop.DoesNotExist: did = 0 return Response(did) Now with Angular, when I do to the URL /drops/mymostrecent: return $http.get("/api/drops/mymostrecent") .then(function(response) { console.log(response); $location.url('/posts/ ' + response.data); }) What gets logged is this: Object {data: 3, status: 200, config: Object, statusText: "OK"} But the URL becomes this: /posts/%203 It still works and shows the correct html page, but how do I get rid of the %20 in the URL? -
Virtualenv for Django dev, better to be at Project or App level?
With Django, Is it better to have a virtualenv created at project level. Or, is it better to have a virtualenv per app within a single project? -
Django reloading static files on every page
I'm looking at my elastic-beanstalk's HTTP request logs for my Django app and I can see that for every new page request (/login, /password_reset, etc.) the client's browser is requesting the whole static folder again and again (css, js, and fonts). My understanding was that these files only load once until the user clears cache. I have a base.html that extends to all pages: <head> <meta charset="utf-8" /> {% load staticfiles %} <script src="{% static 'js/jquery.min.js' %}"></script> <!-- <script src="{% static 'js/bootstrap.min.js' %}"></script> --> <script src="{% static 'js/flat-ui-pro.js' %}"></script> <link type='text/css' rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" /> <link type='text/css' rel='stylesheet' href="{% static 'css/flat-ui-pro.css' %}" /> <link type='text/css' rel='stylesheet' href="{% static 'css/custom_css.css' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> Is there something I should be doing to prevent this? Some more information that might be related: in my settings.py file: ######## Depolyment Security ############# SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' -
How to gracefully handle OperationalError 2003 and change database with .using()
Suppose you have a Django 1.11 app, the-app on site the-site. In the-site/settings.py you have the following databases: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'the-site_webapp', 'USER': 'tester', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'remote-db1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'remote-db1', 'USER': 'tester', 'PASSWORD': '', 'HOST': '<ip1>', 'PORT': '3306', }, 'remote-db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'remote-db2', 'USER': 'tester', 'PASSWORD': '', 'HOST': '<ip2>', 'PORT': '3306', }, } where remote-db2 contains a restricted subset of remote-db1 and can therefore stand in it's stead. There is also the following router information: DATABASE_ROUTERS = [ 'the-app.routers.DefaultRouter', 'the-app.routers.the-appRouter',] Pointing to the-app/routers.py: class MasterRouter(object): ''' http://stackoverflow.com/questions/13988432/how-to-use-db-router-in-django-1-4 ''' def __init__(self, app_label, db_name): super(MasterRouter, self).__init__() self.app_label = app_label self.db_name = db_name def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name #return self.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or obj2._meta.app_label == self.app_label: return True return None def allow_syncdb(self, db, model): if db == 'default': return model._meta.app_label == self.app_label elif model._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, *args, **kwargs): if db in ['remote-db1']: return False class DefaultRouter(MasterRouter): def __init__(self): super(DefaultRouter, self).__init__('default', 'default') class the-appRouter(MasterRouter): def __init__(self): super(the-appRouter, … -
Does using pip3 in the virtual environment prevent a successful push to Heroku. /app/.heroku/python/bin/pip?
Using Ubuntu 16.04 Going through Python Crash Course chapter 20, I've been using pip3 to install packages instead of pip, and python3 instead of python so that the programs would be interpreted correctly in the terminal, otherwise I would get an error when I try to import a library, because it would otherwise automatically be installed in a python 2.7.1 folder. I've also installed some other modules like wheel so that I wouldn't get an error message installing Django. I had done exactly what it said to do on https://devcenter.heroku.com/articles/heroku-cli to get heroku on my machine. I did this outside the virtual environment, since it didn't work with it on. After I use pip freeze > requirements.txt, this fills up in requirements.txt: dj-database-url==0.4.2 dj-static==0.0.6 Django==1.11 django-bootstrap3==8.2.3 gunicorn==19.7.1 pkg-resources==0.0.0 psycopg2==2.7.1 python-dateutil==1.5 pytz==2017.2 requests==2.14.1 static3==0.7.0 I've followed every step in the book besides those substitutions. When I run: git push heroku master, I get: Counting objects: 52, done. Delta compression using up to 4 threads. Compressing objects: 100% (44/44), done. Writing objects: 100% (52/52), 11.65 KiB | 0 bytes/s, done. Total 52 (delta 7), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected … -
how to set the domain to point to my server and load the webpage
I'm using apache 2.4 with Django on an ubuntu 16.04 server. I already have a domain name baranshopcenter.ir. but I only can access the website by using ip address, not the domain name. so The main question is, how to set the domain to point to my server and load the website? What I'v already done: I have purchased a cloud server from parspack.com and then they told me that I have to add these name servers to my profile on nic.ir, where I bought my domain: ns1.parspack.co ns2.parspack.co after some googling! I find out that I have to do some configuration in my server too. So, more specific question is, Where and how should I configure my server. Thanks in advance. There may be some useful information about my domain at intodns.com -
memcache on django is not working
I have a race condition in Celery. Inspired by this - http://ask.github.io/celery/cookbook/tasks.html#ensuring-a-task-is-only-executed-one-at-a-time I decided to use memcache to add locks to my tasks. These are the changes I made: python-memcached # settings for memcache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } After this I login to my shell and do the following >>> import os >>> import django >>> from django.core.cache import cache >>> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.base') >>> cache <django.core.cache.DefaultCacheProxy object at 0x101e4c860> >>> cache.set('my_key', 'hello, world!', 30) #display nothing. No T/F >>> cache.get('my_key') #Display nothing. >>> from django.core.cache import caches >>> caches['default'] <django.core.cache.backends.memcached.MemcachedCache object at 0x1048a5208> >>> caches['default'].set('my_key', 'hello, world!', 30) #display nothing. No T/F >>> caches['default'].get('my_key') #Display nothing. I also tried updating the MIDDLEWARE in settings but it was of no use. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.CacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', ] What am I doing wrong? Any help will be appreciated. -
Properly Verifying HTML POST against Database
I have a site that I am building using Django 1.9 and python 2.7. On my site, I have a checkout page where users select values from 1. select 2. radio 3. checkbox fields. Each value selected has a specific dollar amount attached in the value part of the input parameter. I have created items for each possible selection inside my database and want to verify that the information was not edited by using a browsers code editor before submitting the final cost value. Here is what one of my options in a select menu looks like: <option name="apartment" value="600" id="4p4rtm3nt">Apartment Building</option> I have an object inside my DB (MySQL) with the value, name, and id all matching this option. What would be the most productive/safest way to verify that this information has not been changed when calculating my cost of all items? Personal idea I am thinking of just pulling the id, name, & value from the POST and then making sure they all match the object inside my DB. This just seems extensive and inefficient... How have some of y'all done it? I tried looking at some websites with checkout pages and can't seem to figure out their … -
How to force migrations to a DB if some tables already exist in Django?
I have a Python/Django proyect. Due to some rolls back, and other mixed stuff we ended up in a kind of odd scenario. The current scenario is like this: DB has the correct tables DB can't be rolled back or dropped Code is up to date Migrations folder is behind the DB by one or two migrations. (These migrations were applied from somewhere else and that "somewhere else" doesn't exist anymore) I add and alter some models I run makemigrations New migrations are created, but it's a mix of new tables and some tables that already exist in the DB. If I run migrate it will complain that some of the tables that I'm trying to create already exist. What I need: To be able to run the migrations and kind of "ignore" the existing tables and apply the new ones. Or any alternative way to achieve this. Is that possible?