Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Show Graph from Mysql table in Django?
I have a MySQL table of methods. method_name,time,count are columns and method_name, time are composite primary keys. Time formates are different like 201608(this like month),20160817(this like day),2016081211(this like hour). -
process of "python manage.py runserver" - it never finish
I'm new with Django. When I runserver, seem like I had make wrong anything, I have try for 3, but it still not done. Please help me! python manage.py runserver [27/Aug/2016 10:52:07] "GET / HTTP/1.1" 200 1767 Not Found: /favicon.ico [27/Aug/2016 10:52:08] "GET /favicon.ico HTTP/1.1" 404 1933 [27/Aug/2016 11:12:23] "GET / HTTP/1.1" 200 1767 -
DRF + React is Session auth usable?
I am trying to use Session auth in Django with React. All my GET REST calls are being reject with status 403. I probably have to send sessionidin headers, but sessionid cookie is HTTP only, so my JS code gets a null value when reading it. If I set the cookie to not be HTTP-only anymore, I can read it and send it in headers, but still seing the same problem. Note: the view which includes the React app has a path /app, the REST api path is /api. Could this be the problem? -
what is the "proper" way to use django REST framework?
I went through the tutorial and I am working my way through the docs so I think I have a good understanding of how the system works and I can think of a few different ways to use it but I am curious about the "proper" way to use it because my instincts might be leading me the wrong way. 1) Should I setup an API and then have my other apps just interact with that? In this case say it is a blog, would I create an API app /api that would define the models and the api structure which would be responsible for creating, modifying and destroying objects. Then I would create another app which will display views and forms for authors to actually create blogposts and which would send http requests to the api. This view would also be responsible for letting other users view the blog posts by interacting with the API and retrieving the posts. 2) Would it be better to take care of all of this within the same API app somehow? Should these scenarios all be covered from within the same views as the REST framework viewsets, etc It feels like I have β¦ -
Is there any way to get login-user information in javascript (Django)?
I made a board application and implementing comment function using django framework. I use jquery & ajax to GET and POST comments. Now I want to add Edit and Delete function. As you can see in image, there is edit and delete button. What I'm trying to do is to show those buttons only for the comment that current user had posted. This is part of my ajax getting comments from my comments API. $.ajax({ url: commentURL, type: "GET", success: function(data){ var numOfComments = data.length; $(commentCountElement).html(numOfComments); data.forEach(function(comment){ /* Get data from API results */ var commentUsername = comment.author_name; var commentContent = comment.content; var commentCreatedAt = comment.created_at; var commentID = comment.id; /* Create html li */ var listElement = $("<li>").addClass("comment-box"); /* Create div comment-meta */ var commentMetaDiv = $("<div>").addClass("comment-meta"); $(commentMetaDiv).append($("<span>").text(commentUsername)); $(commentMetaDiv).append($("<span>").addClass("date").text(commentCreatedAt)); /* Create div comment-content */ var commentContentDiv = $("<div>").addClass("comment-content"); $(commentContentDiv).text(commentContent); /* Append */ $(listElement).append(commentMetaDiv); $(listElement).append(commentContentDiv); $(commentUnorderedListElement).append(listElement); }); }, error: function(data){ console.log(textStatus); return false; } }); Now, I have to compare current login user with comment.author_name so that I can add button depending on that result. But I have no idea how I can get current user's infos in js. Need your help. thanks -
Object.values returns a dictionary, what do you use to simply return a value?
I am relatively new to Django, and I have been experimenting with the object model. I have been having trouble pulling a single value from my database based on the user selecting a scenario name from a dropdown and then hitting a submit button. This is what I am working with. if request.method =='POST' and 'submitdropdown1' in request.POST: entry = Scenario.objects.values().get(scenario_name=scenario_name) r = entry.get('project_cost') Values() returns a dictionary so: r = 'Decimal ("200")' I would like for: r = 200 What should I use besides Values()? -
ajax return variable to django temmplate
Currntly the data is flow between python view and Django using dict type. But I want to avoid page refresh and hence thinking of using Ajax calls for posting form data from template to view. But the issue is when view returns the data, it goes to Ajax function and need to render using Ajax and jquery. Is there possiblity of ajax forwading the variable to template as if it came from view so that i can access them using {{ }}. -
Django debug: how to know which template is in use for a specific URL?
How can I know which template is in use for a specific URL when debugging? For example, what is the template that was used when visiting /login? -
Uploading contents of Django FileField to a remote server
In a Django project of mine, users upload video files. Initially, I was uploading them directly to Azure Blob Storage (equivalent to storing it on Amazon S3). I.e. in models.py I had: class Video(models.Model): video_file = models.FileField(upload_to=upload_path, storage=OverwriteStorage()) Where OverwriteStorage overrides Storage in django.core.files.storage, and essentially uploads the file onto Azure. Now I need to upload this file to a separate Linux server (not the same one that serves my Django web application). In this separate server, I'll perform some operations on the video file (compression, format change), and then I'll upload it to Azure Storage like before. My question is: given my goal, how do I change the way I'm uploading the file in models.py? An illustrative example would be nice. I'm thinking I'll need to change FileField.upload_to, but all the examples I've seen indicate it's only to define a local filesystem path. Moreover, I don't want to let the user upload the content normally and then run a process to upload the file to another server. Doing it directly is my preference. Any ideas? Thanks in advance. Kind of a beginner here, so apologies if this is an obvious question. -
Django request.user becomes anonymous after redirect
In my Django app I create a User from django.contrib.auth.models, and I am using request.user in multiple view functions without a problem. In one of my view functions I change the user password, save the user, and redirect the client to another view function. Once I try to get the user from the request in that function, the user is Anonymous. After using User.set_password() or redirecting, does it take the user out of the session ? views.py from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from .models import Profile from .forms import ProfileForm, PasswordForm def sign_in(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): if form.user_cache is not None: user = form.user_cache if user.is_active: login(request, user) return HttpResponseRedirect( reverse('home') # TODO: go to profile ) else: messages.error( request, "That user account has been disabled." ) else: messages.error( request, "Username or password is incorrect." ) return render(request, 'accounts/sign_in.html', {'form': form}) def sign_up(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(data=request.POST) if form.is_valid(): form.save() user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) new_profile = Profile.objects.create(user=user) login(request, user) messages.success( β¦ -
How to fix a python import error in jenkins
I am having module import errors in Jenkins despite setting my path and python path based on questions here on stack overflow I have tried this Jenkins: putting my Python module on the PYTHONPATH and this Python module import failure in Jenkins This same command runs on my local machine without any import issues but fails on Jenkins The command #!/bin/bash export PYTHONPATH=$WORKSPACE:$PYTHONPATH export PATH=$WORKSPACE:$PATH export DJANGO_SETTINGS_MODULE=myapp.settings.test echo "Working directory: " pwd echo "path: " echo $PATH echo "Python path: " echo $PYTHONPATH /home/adminuser/.virtualenvs/myapp/bin/python myapp/manage.py jenkins --project-apps-tests --enable-coverage --settings=myapp.settings.test The build error Working directory: /var/lib/jenkins/jobs/myapp_QA_TESTS/workspace path: /var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games Python path: /var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/home/adminuser/.virtualenvs/myapp/bin:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace: -------- USING TEST SETTINGS ------ Traceback (most recent call last): ...... File "/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/accounts/models.py", line 18, in <module> from apps.security.tokens.utils import TokenUtil ImportError: No module named security.tokens.utils My file structure overview myapp/ βββ apps β βββ __init__.py β βββ accounts β βββ security βββ myapp β βββ __init__.py β βββ celery.py β βββ settings β βββ urls.py β βββ wsgi.py βββ manage.py view into the module directories myapp/apps/security/tokens βββ __init__.py βββ utils.py myapp/apps/accounts/ βββ __init__.py βββ models.py I have tried even appending the workspace directory and the virtualenv path to both PATH and PYTHONPATH, i also even added the module directory β¦ -
ModelForm displays ForeignKey table values, not choices
I'm creating a model form, where the Category field in model Site is a foreign key referencing Category in model Category: models.py: from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible # for python 2 support class Site(models.Model): Category = models.ForeignKey('Category') def __str__(self): return self.Name CATEGORY_CHOICES = ( ('AU', 'Automobiles'), ('BE', 'Beauty Products'), ('GR', 'Groceries'), ) class Category(models.Model): Category = models.CharField(choices=CATEGORY_CHOICES,max_length=2) def __str__(self): return '%s' % (self.Category) forms.py: from django.forms import ModelForm from sites.models import Site class NewSiteForm(ModelForm): class Meta: model = Site fields = ['Category'] newsite.html: <!DOCTYPE html> <form method="post" action=""> {{ form}} </form> It gives me a Category dropdown that lists values already stored in my Category database, rather than listing the contents of the choices tuples defined in the Category model. so I'm getting this: <!DOCTYPE html> <form method="post" action=""> <tr><th><label for="id_Category">Category:</label></th><td><select id="id_Category" name="Category"> <option value="" selected="selected">---------</option> <option value="1">AU</option> <option value="2">BA</option> <option value="3">BE</option> <option value="4">BO</option> <option value="5">PH</option> <option value="6">CO</option> <option value="7">CC</option> <option value="8">CB</option> <option value="9">CE</option> <option value="10">CS</option> <option value="11">CA</option> <option value="12">EA</option> <option value="13">EC</option> <option value="14">FA</option> <option value="15">GR</option> <option value="16">HA</option> <option value="17">HE</option> <option value="18">HG</option> <option value="19">IN</option> <option value="20">JE</option> <option value="21">LT</option> <option value="22">MS</option> <option value="23">MU</option> <option value="24">MI</option> <option value="25">OF</option> <option value="26">OU</option> <option value="27">PC</option> <option value="28">SH</option> <option value="29">SO</option> <option value="30">SP</option> β¦ -
Django send email with form data filled in my user
I am trying to create a send mail option after the user fills in form. this email should have all customer's form data and sent to administrators only. Following the Django Docs and I am able to send mails however I can not customize a mail template. See code subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>', msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Django Charfield null=False Inegrity Error not raised
I have a model: class Discount(models.Model): code = models.CharField(max_length=14, unique=True, null=False, blank=False) email = models.EmailField(unique=True) discount = models.IntegerField(default=10) In my shell when I try and save a Discount object with no input, it doesn't raise an error. What am I doing wrong? > e = Discount() > e.save() -
Is it possible to have all lists in one table/model in Django?
I'm using Django and every example I see uses a separate table per list. Is it not advisable to use one table for all lists? Are there any reasons not to do this? Thanks -
Is it possible in django model form to show certain fields if user select a related field?
I have a user model field with choices asking about employment, if person select the choice employed then only I want to show fields asking about employer details in user inerface, any possibilities? Thank you in advance. -
Complex query in Django: unraveling M2M models
I'm trying to structure a complex query. There's more to these models, but these are the relevant connections. Desired query: (Evaluating for a given Student) List of Assessments that are tied to this Section AND are of type 'Class' OR are connected to a Score instance with this_student as the student What I have so far (missing the last bit): Assessment.objects.all().filter(section=this_section).filter(Q(Type='Class')|Q()).order_by('-Date') Models: class Section(models.Model): Name = models.CharField(max_length=30,default='.',unique=True) class Student(models.Model): LastName = models.CharField(max_length=30) sections = models.ManyToManyField(Section) class Assessment(models.Model): AsstChoices = ( ('Class', 'Class'), ('Individual', 'Individual') ) Type = models.CharField(max_length=30,default='Class',choices=AsstChoices) section = models.ForeignKey(Section, on_delete=models.CASCADE) class Score(models.Model): Value = models.DecimalField(decimal_places=2,max_digits=6) assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) Comment = models.TextField(blank=True)#optional) Evidence = models.FileField(blank=True,null=True, upload_to='evidence/')#optional) -
Ajax and Django, sending me to just a json string?
I had a index page where the user could select a few things on a form (not backed by a model) and then hopefully send off those parameters to the next form. I read that passing post data from one form to the next isn't ideal (So my design is probably not) though i just was trying to accomplish a quick proof of concept. Since it wasn't ideal, I thought AJAX on the index form that could come back with the results of the selected params from that form would be the key. I haven't done much Ajax especially in django and so I used this website here to get some bearings: How to submit form without refreshing page using Django, Ajax, jQuery? I got the code I thought implemented correctly... yet when I click submit on the form it it shows me a page with just a json string on it. views.py: def change_detection_index(request): #this is a good attempt at an ajax call... if request.method == 'POST': form = ChangeDetectForm(request.POST) message = 'something wrong!' if form.is_valid(): points = form.cleaned_data.get('points') delta = form.cleaned_data.get('delta') #frefresh the list with this info... ajax way. message = str(points) + " " + str(delta) # β¦ -
AWS S3ResponseError 400
I''m trying to set up my Django Application to AWS. My EC2 configurations is Ubuntu 14.04 , Apache2 , Django 1.8 and python 3.4 So I tried to move static files to S3 following this tutorial : https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ After following tutorial, I finally run 'python manage.py collectstatic' in my project and got an error : boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request My S3 Bucket policy is below : { "Version": "2008-10-17", "Statement": [ { "Sid": "PublicReadForGetBucketObjects", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::MY_BUCKET_NAME/*" }, { "Effect": "Allow", "Principal": { "AWS": "MY_USER_ARN" }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::MY_BUCKET_NAME", "arn:aws:s3:::MY_BUCKET_NAME/*" ] } ] } My COR Configuration is below : <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> In my 'settings.py' : INSTALLED_APPS = ( ... , 'storages', ...) # FOR AWS AWS_STORAGE_BUCKET_NAME = 'MY_BUCKET_NAME' AWS_ACCESS_KEY_ID = 'MY_ACCESS_KEY_ID' AWS_SECRET_ACCESS_KEY = 'MY_SECRET_ACCEESS_KEY' AWS_S3_SECURE_URLS =False AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATIC_URL = "http://%s/" % AWS_S3_CUSTOM_DOMAIN STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' What am I missing to make it? Please help me. -
Zinnia rewriting urls does doesn't work
I'm trying to customize the url of entries in zinnia to show slugs of entries only, ie .../blog/slug. I've been following closely the documentation here - I've overwritten the get_absolute_url method, I've added the view and configured the urls and registered the _base model in django settings - yet the error persists: zinnia_customized models.py: from django.db import models from zinnia.models_bases.entry import AbstractEntry class EntryWithNewUrl(AbstractEntry): """Entry with '/blog/<id>/' URL""" @models.permalink def get_absolute_url(self): return ('zinnia:entry_detail', (), {'slug': self.slug}) class Meta(AbstractEntry.Meta): abstract = True zinnia_customized views.py: from django.views.generic.detail import DetailView from zinnia.models.entry import Entry from zinnia.views.mixins.entry_preview import EntryPreviewMixin from zinnia.views.mixins.entry_protection import EntryProtectionMixin class EntryDetail(EntryPreviewMixin, EntryProtectionMixin, DetailView): queryset = Entry.published.on_site() template_name_field = 'template' project urls.py: urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), url(r'^admin/tools/', include('admin_tools.urls')), url(settings.ADMIN_URL, include(admin.site.urls)), url(r'^users/', include('anpene.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), url(r'^blog/', include('zinnia_customized.urls', namespace='zinnia')), url(r'^comments/', include('django_comments.urls')), ] zinnia_customized urls.py: blog_urls = [ url(r'^', include('zinnia.urls.capabilities')), url(r'^search/', include('zinnia.urls.search')), url(r'^sitemap/', include('zinnia.urls.sitemap')), url(r'^trackback/', include('zinnia.urls.trackback')), url(r'^blog/tags/', include('zinnia.urls.tags')), url(r'^blog/feeds/', include('zinnia.urls.feeds')), url(r'^blog/authors/', include('zinnia.urls.authors')), url(r'^blog/categories/', include('zinnia.urls.categories')), # url(r'^blog/', include('zinnia.urls.entries')), url(r'^blog/', include('zinnia_customized.urls.entries')), url(r'^blog/', include('zinnia.urls.archives')), url(r'^blog/', include('zinnia.urls.shortlink')), url(r'^blog/', include('zinnia.urls.quick_entry')), ] urlpatterns += patterns('', url(r'^', include(blog_urls), name='blog') ) zinnia_customized app urls/entries.py: from django.conf.urls import url from django.conf.urls import patterns from zinnia_customized.views import EntryDetail urlpatterns = [ url(r'^(?P<slug>[\w-]+)/$', EntryDetail.as_view(), name='entry_detail'), ] zinnia_customized admin.py: from β¦ -
Wagtail translate the page slug (fully translate url)
My Wagtail settings are working correctly, I'm able to go to the same page (translated) using the /en/ and /fr/, but i wanted to fully translate the url so that i could do /en/home /fr/vin I'm currently using this plugin to make my wagtail Page translatable, but i can't manage to make the slug part work -
django 'Key Error' with admin
Im getting this error in the admin when I try to click families. Error during template rendering In template /Library/Python/2.7/site-packages/django/contrib/admin/templates/admin/change_list.html, error at line 91. manager 81 {% endif %} 82 {% endblock %} 83 84 <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %} novalidate>{% csrf_token %} 85 {% if cl.formset %} 86 <div>{{ cl.formset.management_form }}</div> 87 {% endif %} 88 89 {% block result_list %} 90 {% if action_form and actions_on_top and cl.show_admin_actions %}{% admin_actions %}{% endif %} 91 {% result_list cl %} 92 {% if action_form and actions_on_bottom and cl.show_admin_actions %}{% admin_actions %}{% endif %} 93 {% endblock %} 94 {% block pagination %}{% pagination cl %}{% endblock %} 95 </form> 96 </div> 97 </div> 98 {% endblock %} 99 trace KeyError at /admin/family/family/ u'manager' Request Method: GET Request URL: http://127.0.0.1:8000/admin/family/family/ Django Version: 1.8.5 Exception Type: KeyError Exception Value: u'manager' Exception Location: /Library/Python/2.7/site-packages/django/db/models/fields/related.py in __call__, line 687 Python Executable: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Python Version: 2.7.10 ['/Users/levi/django_projects/Home_Teaching', '/Applications/PyCharm.app/Contents/helpers/pydev', '/Users/levi/django_projects/Home_Teaching', '/Applications/PyCharm.app/Contents/helpers/pydev', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', Python Path: '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/levi/Library/Python/2.7/lib/python/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages'] Server time: Fri, 26 Aug 2016 15:55:03 -0500 Models from django.db import models CHILD_CHOICES = ( ('FI', 'First'), ('SE', 'Second'), ('TH', 'Third'), ('FO', 'Fourth'), ('FI', 'Fifth'), β¦ -
-bash: createdb: command not found
I'm using a Mac and I already have installed PostgreSQL in my computer using the dmg provided by PostgreSQL (and not by Postgres.app). I have installed it because I will go to use it with Django, and for to get the correct functionality with the framework, I had to do the next commands: export PATH=/Library/PostgreSQL/9.5/bin/:"$PATHβ sudo ln -s /Library/PostgreSQL/9.5/lib/libssl.1.0.0.dylib /usr/lib sudo ln -s /Library/PostgreSQL/9.5/lib/libcrypto.1.0.0.dylib /usr/lib $ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old $ sudo ln -s /Library/PostgreSQL/9.5/lib/libpq.5.dylib /usr/lib Then I executed the command: ./manage.py migrate Getting at the terminal a message like this: And knowing that I needed to create a user "erikb" in PostgreSQL. I can enter in terminal the command: sudo su - postgres To enter to PostgreSQL, but when I wanted to create a DB o a new user, it send me the next error: -bash: createuser: command not found Does anyone know which could be the problem? Regards. -
Django CustomField inheritance from models.CharField -- unexpected keyword argument
My application needs few attributes that are required for the fields, so I went and followed the code to create custom fields. This is my CustomCharacterField: class CustomCharField(models.CharField): def __int__(self, success_order=None, *args, **kwargs): self.success_order = success_order super(CustomCharField, self).__int__( *args, **kwargs) def get_success_order(self): return int(self.success_order) Here is my models.py class NameModel(models.Model): name = fields.CustomCharField(max_length=250, unique=True, success_order=1) Here is the traceback: File "/home/kt/Documents/phc/phc/Forms/models.py", line 204, in <module> class SchemeModel(models.Model): File "/home/kt/Documents/phc/phc/Forms/models.py", line 220, in SchemeModel scheme_name = fields.CustomCharField(verbose_name="Scheme", max_length=250, unique=True, success_order=1) File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'success_order' -
Error in SqlaLchemy model relationship for version 0.7.8
I am using sqlalchemy version 0.7.8. Here is Recording Request model (to which i have to make a relation from TiedRecordingRequest model) class RecordingRequest(QueryMixin): __tablename__ = 'recording_request' # column definitions id = Column(Integer, primary_key=True, nullable=False) batch_id = Column( Integer, ForeignKey('request_batch.id'), nullable=False ) status_id = Column( Integer, ForeignKey('request_status.id'), nullable=False ) recordingword_id = Column( Integer, ForeignKey('recording_words.id'), nullable=False ) text = Column(String(2000), nullable=False) location = Column(String(1500), nullable=True) active = Column(Boolean, default=1) # relation definitions batch = relationship('RequestBatch') status = relationship('RequestStatus') recordingword = relationship('RecordingWords') Here is TiedRecordingRequest model class TiedRecordingRequest(QueryMixin): """ This class contains the tie request against parent request from which they are created. """ __tablename__ = 'tied_recording_request' id = Column(Integer, primary_key=True, nullable=False) recording_request_id = Column( Integer, ForeignKey('recording_request.id'), nullable=False) tied_recording_request_id = Column( Integer, ForeignKey('recording_request.id'), nullable=False) tied_recording_request = relationship('RecordingRequest') Problem is in the last line tied_recording_request = relationship('RecordingRequest') Gives Error sqlalchemy.exc.InvalidRequestError: Table 'tied_recording_request' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object. When i Change Above line to this tied_recording_request = relationship( 'RecordingRequest', primaryjoin="TiedRecordingRequest.tied_recording_request_id == RecordingRequest.id",) Then it gives an error sqlalchemy.exc.InvalidRequestError: Table 'tied_recording_request' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object. When β¦