Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin - create custom html page for model and pass values from js to db
I have a model, that describes polygon on map. I need a way to create that polygons by clicking on google maps inside Django admin and then save that polygons coordinates in db. So, I need to perform following steps: Create a new html template with map. Somehow pass this template in Django in page of editing model Pass values from js in html page to django database after finishing editing How can I pass custom html with js to model editing page and then save data from js in django db ? I dont look for polygons creation logic, but for a way to connect it with django. -
Django rest framework group by fields and add extra contents
I have a Ticket booking model class Movie(models.Model): name = models.CharField(max_length=254, unique=True) class Show(models.Model): day = models.ForeignKey(Day) time = models.TimeField(choices=CHOICE_TIME) movie = models.ForeignKey(Movie) class MovieTicket(models.Model): show = models.ForeignKey(Show) user = models.ForeignKey(User) purchased_at = models.DateTimeField(default=timezone.now) I would like to filter MovieTicket with its user field and group them according to its show field, and order them by the recent booked time. And respond back with json data using Django rest framework like this: [ { show: 4, movie: "Lion king", time: "07:00 pm", day: "23 Apr 2017", total_tickets = 2 }, { show: 7, movie: "Gone girl", time: "02:30 pm", day: "23 Apr 2017", total_tickets = 1 } ] I tried this way: >>> MovieTicket.objects.filter(user=23).order_by('-booked_at').values('show').annotate(total_tickets=Count('show')) <QuerySet [{'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 7}]> But its not grouping according to the show. Also how can I add other related fields (i.e., show__movie__name, show__day__date, show__time) -
python filter none values
I have: 1. models.py class Post(models.Model): ROOT_CHOICES = ( ('Manufacturing', 'Manufacturing'), ('Transportation', 'Transportation'), ('Installation', 'Installation'), ('Operation', 'Operation'), ) root1 = models.CharField(max_length=250, choices=ROOT_CHOICES, default='Manufacturing') root2 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) root3 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) root4 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) 2. views.py def post_detail(request, slug): post=get_object_or_404(Post, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post=post comment.save() return redirect('data:post_detail', slug=post.slug) else: form=CommentForm() template = 'data/post_detail.html' context = {'form':form,'post':post} return render(request, template, context) 3. html <div class="col-sm-3"> <div class="post-parameters"> <p class="text-parameters"> Root: {{ post.root1 }}, {{ post.root2 }}, {{ post.root3 }}, {{ post.root4 }}</p> </div> </div> It looks like this, right now, in my html file: Root:Manufacturing, None, None, None which is correct. However I would like not to show the ,if any, None values e.g. Root:Manufacturing -
[Django]django.db.utils.IntegrityError
my app named mainsite I have the table class named Weather in models.py class Weather(models.Model): tpr = models.CharField(max_length=5) wet = models.CharField(max_length=5) ur = models.CharField(max_length=5) li = models.CharField(max_length=5) observe_time = models.DateTimeField(default=None) I don't want my observe_time set any deafult value So I set to None . I have made migrations. when I made migrate Then the traceback happen: File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards field, File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 179, in add_field self._remake_table(model, create_fields=[field]) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\sqlite3\schema.py", line 147, in _remake_table self.quote_name(model._meta.db_table), File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 111, in execute cursor.execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\User\Anaconda3\lib\site-packages\django\db\utils.py", line 98, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise raise … -
Users created posts not being returned to template? Django
the user is able to create a post and it will be shown the in the list. I've also created a users profile/summary page where the user can edit/delete their posts. Currently, it's showing blank and I'm not quite sure why? Model class Aircraft(AircraftModelBase): user = models.ForeignKey(User) manufacturer = SortableForeignKey(Manufacturer) aircraft_type = SortableForeignKey(AircraftType) View def upload_overview(request): uploaded_aircraft = Aircraft.objects.filter(user=request.user) return render(request,'account/upload_overview.html',{'UploadedAircraft':uploaded_aircraft}) Template <div class="container"> <div class="row aircraft"> {% if UploadedAircraft %} {% for upload in UploadedAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ upload.aircraft.get_absolute_url }}"><img src="{{ upload.aircraft.image.url }}" width="200px" height="200px" alt="{{ upload.aircraft.title }}"/></a> <h3 class="name"><a href="{{ upload.aircraft.get_absolute_url }}">{{ upload.aircraft.name }}</a></h3> </div> </div> {% endfor %} {% else %} <h2 class="text-center">No uploaded aircraft posts..</h2></div> {% endif %} </div> -
Reload the table without refreshing the page in Django
Have small table that needs to be updated every 10 seconds with new data. Entire website is working in Django. JSON is parsing data into 1 table and rewriting the data every 10 seconds in database. The website is showing the data from the database. The procedure I need is to refresh the front-end table with new data every 10 seconds - it would be the AJAX I assume, can you help me write the code for it? It would not append data to the table, just keep refreshing it. Example - The table in the database has fixed 10 rows of data and it is being refreshed by JSON. The front-end would always show 10 rows, so every 10 seconds, the table (front-end) would always show 10 rows with the new data. Here are the python files views.py def prices(request): prices = Price.objects.all().order_by('id') return render(request, 'prices.html', {'prices':prices}) prices.html <div class="col-md-8"> <table class="table table-striped"> <thead> <tr> <th>TYPE</th> <th>NAME</th> <th>PRODUCT</th> <th>VALUE</th> </tr> </thead> <tbody> {% for price in prices %} <tr> <td>{{ price.type }}</td> <td>{{ price.name }}</td> <td>{{ price.product }}</td> <td>{{ price.value }}</td> </tr> {% endfor %} </tbody> </table> </div> urls.py urlpatterns = [ url(r'^prices/', product_views.prices, name='prices'), url(r'^admin/', admin.site.urls), ] -
Validation fails on ModelForm
Hi I'm trying to teach my self Django while making a small Task management app. I have a Model class Task(models.Model): track = models.ForeignKey(Track, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100) description = models.CharField(max_length=265, blank=True) done = models.BooleanField(default=False) def __str__(self): return self.title and related ModelForm class TaskForm(forms.ModelForm): class Meta: model = Task fields = ['track', 'title', 'description', 'done'] When form is posted taskForm.is_valid() is returning False. This is post_task method: def post_task(request): form = TaskForm(request.POST) if form.is_valid(): form.save(commit=True) else: print(form.errors) return HttpResponseRedirect('/') and the form tag on the page: <form action="post_url" mehod="post"> {% csrf_token %} {{ task_form.as_p }} <input type="submit" value="Add"/> </form> Even though I've filled in all the data I'm getting validation error, this is the console print: <ul class="errorlist"><li>track<ul class="errorlist"><li>This field is required.</li></ul></li><li>title<ul class="errorlist"><li>This field is required.</li></ul></li></ul> All values have been passed in the request: [23/Apr/2017 12:34:38] "GET /post_url/?csrfmiddlewaretoken=VqUx3EM9yGFzS88kYRtTWtniaCV8ZukxymylPILlxHBohtfEyhD3epOKOjKNIVCU&track=1&title=testTitle&description=testDescription HTTP/1.1" 302 0 Thanks! -
Transform Data from Django ORM to custom CSV format
Given the following models: class Stream(models.Model): name = models.CharField(max_length=32) label = models.CharField(max_length=32) ... class Data(models.Model): class Meta: ordering = ['timestamp'] timestamp = models.DateTimeField(db_index=True) # in UTC ! data = models.FloatField() stream = models.ForeignKey(to=Stream, editable=False) ... I need to output results in the following (CSV) format: Example output: Timestamp,A,B,C,D 2017/03/03:00:01:00,4,2,1.9,3 2017/03/03:00:01:15,4,3,1.8.3 ... A,B,C and D are streams labels. Values are from Data.data field. -
Django server doesn't response during request
I have function named as validate_account() that return boolean. It goes to db, and do some manipulation with duration of 7 seconds. So, when I make another requests to server, it doesn't response during these 7 seconds for any request. How can I fix it? Maybe by starting new process? @login_required @csrf_protect def check_account(request): username = request.session['current_account'] account = get_object_or_404(Account, username=username) # takes 7 seconds login_status = validate_account(account.username, account.password) response = { 'loginStatus': login_status } response = json.dumps(response) return JsonResponse(response, safe=False) -
PDF file without content in Django
Hello friends, I want to ask you for help. I created a web form that generates PDF files. Everything is fine. Automatically Send PDFs via Email is OK. Unfortunately, the form fields that are not added to the models.Model are not included in the PDF (contents). PDF documents display (postal_code) as blank field. I don't know what to do. Where is the problem? model.py class Order(models.Model): name = models.CharField(max_length=50) forms.py CHOICES=[('item1','1xx'), ('item2','2xx')] class OrderCreateForm(forms.ModelForm): postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Order fields = ['name', 'postal_code'] form.html <form action="." method="post" class="order-form"> {{ form.as_ul }} <p><input type="submit" value="Send"></p> {% csrf_token %} </form> tasks.py from celery import task from oferty.models import Order from django.template.loader import render_to_string from django.core.mail import EmailMessage from django.conf import settings import weasyprint from io import BytesIO @task def order_created(order_id): order = Oferta.objects.get(id=order_id) subject = 'New nr {}'.format(order.id) message = 'Hallow, {}!\n\nBlaBlaBla.\ BlaBlaBla {}.'.format(order.imię, order.id) email = EmailMessage(subject, message, 'admin@myshop.com', [order.email]) html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') email.send() pdf.html <html> <body> <h1>Test</h1> <p> {{ order.name }}<br> {{ order.postal_code }} </p> </body> </html> Do you give me any hint of which way ? Your help would be … -
Handling exception through a decorator in Django
I am trying to create a error handling decorator in django and where the logging happens in the decorator in case of an exception and the exception is raised back to the decorated function which then sends an error http response. But when I try do this, If I add a Except block in the decorated function after the exception from decorator is raised back, then only the except block of the decorated function is getting executed and the except block of the decorator is left unexecuted. MyDecorator.py def log_error(message): def decorator(target_function): @functools.wraps(target_function) def wrapper(*args, **kwargs): try: return target_function(*args, **kwargs) except Exception as e: print('except block of the decorator') exceptiontype, exc_obj, exc_tb = sys.exc_info() filename = traceback.extract_tb(exc_tb)[-2][0] linenumber = traceback.extract_tb(exc_tb)[-2][1] mylogger(message=str(e),description='Related to Registration',fileName=filename,lineNumber=linenumber, exceptionType = type(e).__name__) raise return wrapper return decorator Decorated function @log_error('message') def action(self, serializer): try: .................. .................. .................. .................. return Response(status=status.HTTP_200_OK, data={ "message":'link sent successfully'}) except Exception as e: print('except block of the decorated function') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={"message" : 'error sending link'}) This is printing the line except block of the decorated function and not the line except block of the decorator If I remove the Except block from the decorated function then the except block of … -
Django - Authentication credentials were not provided
I'm working with an endpoint that seems to be built on Django. Attempting to setup basic aJax communication to it via POST I wrote: jQuery.ajax({ type: "POST", url: "http://API-ENDPOINT-URL", data: "", dataType: "json", crossDomain: false, beforeSend: function(xhr){ xhr.setRequestHeader('Authorization', 'Token <TOKEN THAT I WAS PROVIDED>' ) }, success: function(results) { reqListener(results) } }); With those code a few things happened: I first got a CORS error since I'm trying to build on my local server. I installed this chrome extension to bypass it. (I have no access to the server to enable CORS) 2.I get this error in the console: XMLHttpRequest cannot load http://API-ENDPOINT-URL. Response for preflight has invalid HTTP status code 401 looking at the Chrome console for the network request I see this comes back: {"detail":"Authentication credentials were not provided."} What am I missing? Am I incorrectly sending the authentication token? -
Unable to import django.db in models.py
i have a Django project with a chat app inside it, this is the project file: gadgetry: |__src: |__chat(the app): | |__rest_framework | |__serializers.py | |__models.py | |__views.py | |__chatbotx1(folder contain python files): | |__gender.py |__chatbot: |_settings.py when i use check and makemigrations there are no error and the project is working when i try to visit website, but when i click on a button to activate the chatbotx1-> gender.py file i get this error: chat.models.DoesNotExist: arabic_names matching query does not exist. i think the problem in importing of the models in my app because in: serializers.py from chat.models import chat, user_info, arabic_names (C0111:Missing module docstring) from chat.rest_framework import serializers (E0401:Unable to import 'chat.rest_framework') gender.py: from chat.models import arabic_names (Unable to import 'chat.models') models.py: from django.db import models (Unable to import 'django.db') class arabic_names(models.Model): Name= models.TextField(default='defult name') Gender= models.TextField(default='defult gender') def __unicode__(self): return self.Name ,self.Gender wsgi.py import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'chatbot.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() PS: I am using Django10,Python3.5,MySQL -
Django: execute longer sql queries using models
I'm working with the following django models and can't quite figure out how to convert a raw sql query I'm working with into a simpler Django ORM filter statement. I've looked over the Django query documentation but haven't made much progress. Here are my relevant models: class Posted_By(models.Model): author = models.ForeignKey('Redditor', models.DO_NOTHING, db_column='author') id = models.ForeignKey(Comment, models.DO_NOTHING, db_column='id', primary_key=True) class Meta: managed = False db_table = 'posted_by' def __str__(self): return self.author, self.id class Posted_In(models.Model): subreddit = models.ForeignKey('Subreddit', models.DO_NOTHING, db_column='subreddit') id = models.ForeignKey(Comment, models.DO_NOTHING, db_column='id', primary_key=True) class Meta: managed = False db_table = 'posted_in' def __str__(self): return self.id, self.subreddit And here is my (postgres) sql query: select subreddit from posted_in, posted_by where posted_by.author = 'keanex' and posted_by.id = posted_in.id group by subreddit order by count(subreddit) desc limit 3; Thanks so much for the help. -
"relation App_Class does not exist" works locally but not when deployed to heroku
Error in Heroku When deployed (runs perfectly fine locally), even though I run migrations locally and then migrate in Heroku a relation isn't formed. Thinking there is something in the Heroku migrations but I cannot figure it out. Any help would be appreciated! The code snippit below is what gives me the error "relation 'books_studentclasses' does not exist" def add_classes(request): student = request.user.pk try: student_chk = StudentClasses.objects.get_or_create(student=request.user) except: HttpResponseRedirect('/my_classes/add_classes') These are the important models... class UniversityStateClass(models.Model): university_class = models.CharField(max_length=40, unique=True, verbose_name='Class', blank=True, null=True) class StudentClasses(models.Model): student = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name='student', primary_key=True, blank=True) classes = models.ManyToManyField(UniversityStateClass, verbose_name='classes', blank=True) -
Django FileField Model that doesn't upload but returns path of the file
I am using Django to build an app where I ask the user to choose some files from his/her computer and the app will process them and write an output file in the same directory. If I use the FileField model in Django, it uploads the file to the MEDIA_ROOT directory. That's not what I want. I would like the file to remain where it is and I need the path to the file where it is instead. I have been looking at the FileField code: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#FieldFile Does anyone know of a hack around this where the upload_to is disabled and the storage method that is being used returns the path instead? From what I could make out, the storage method reads the file and writes it into the upload_to directory. The FileField class uses the FieldFile class and the FileDescriptor class. Does anyone know which method actually performs the read and therefore has the actual path of the file? Been trying to read the code but I am not at an advanced stage yet and I can't understand all of it. Thanks in advance. -
ADD multiple objects with form
I'm trying to do something which I would think is quite common, but I'm just really unsure how to realise it. I have modal 'Requirement'. Every requirement has there own name and unique code. I want to show form with REQUIREMENTS_CHOICES list with checkboxs. User can select checkboxes which requirements they need. How to make it in Django? models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('Name'), max_length=250, choices=REQUIREMENTS_CHOICES) REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) -
Favorites are not being returned back to template? Django
On the list the page the user is able to select which aircraft that they want to favourite. I've set it up correctly, but it doesn't seem to be returning anything. Does anyone know where the error could be? Accounts/view.py @login_required def add_aircraft_to_favorites(request, aircraft_id): aircraft_in_favorites = FavoritedAircraft.objects.filter( user__id=request.user.id, aircraft__id=aircraft_id).count() > 0 if aircraft_in_favorites: return JsonResponse({'error': 'already favorited'}, status=409) aircraft = Aircraft.objects.get(pk=aircraft_id) favorited_aircraft = FavoritedAircraft.objects.create( user=request.user, aircraft=aircraft) return JsonResponse({'favorited_aircraft': favorited_aircraft.id}, status=201) @login_required def remove_aircraft_from_favorites(request, aircraft_id): FavoritedAircraft.objects.get(user__id=request.user.id, aircraft__id=aircraft_id).delete() return JsonResponse({}, status=204) View for summary page def account_overview(request): fav_aircraft = FavoritedAircraft.objects.get(user__id=request.user.id) return render(request, 'account/account_overview.html', {'favAircraft':fav_aircraft}) List Template (user can view and favorite their posts) .... </div> {% if user.is_authenticated %} <button class=" favorite btn btn-default {% if aircraft.id in favorited_aircraft_ids %}added{% endif %}" data-aircraft-id="{{ aircraft.id }}"><span class="add">Add</span><span class="remove">Remove</span> Favorite</button> {% endif %} </div> ........ {% block js %} <script> var favorited_aircraft_ids = {% if favorited_aircraft_ids %}{{ favorited_aircraft_ids | escapejs }}{% else %}[]{% endif %}; </script> <script src="{% static 'js/aircraft/favorite.js' %}"></script> {% endblock %} Summary page Template (favorites displayed here) <div class="row aircraft"> {% if favAircraft %} {% for favorite in favAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ favorite.aircraft.get_absolute_url }}"><img src="{{ favorite.aircraft.image.url }}" width="200px" height="200px" alt="{{ favorite.aircraft.title }}"/></a> <h3 class="name"><a href="{{ … -
Dango - navigate hyperlink to a folder on disk
I would like to click on a hyperlink in my Django template that navigates to an arbitrary URL such as file:///C:/my_dir/folder This URL works if I paste it directly into the address field of a browser, but does nothing if I click on a hyperlink in my Django app that resolves to that URL. I've also tried implementing it using the template - view protocol for Django but in my view neither of these seem to work return HttpResponse(html_filepath)orreturn render(request, html_filepath, context) -
Is it possible to create a google map location from external app?
I'm tired goggling to get my answer. Actually i have a Django apps where have an entry form like google map new location creation form. I wanna entry this form and want to save data to my database along with to create new location to maps.google.com. I used some plug-ins which stores value to database but they actually doesn't create new location to google map. I need some suggestion. -
Django how to tie device to user using token
I have a django app that uses the Django REST Framework with the Django OAuth Toolkit and django-rest-framework-social-oauth2. Each user has a raspberry pi that can come with a preloaded token. When users login to the website for the first time they are asked to enter the token that they got and is associated with the device. The device then should be tied to the user and is supposed to download configuration linked to the user profile. I was thinking that I could create an oauth client_id/secret for each device, and only give the user the client_id, and tie the credentials to their account once they enter it. The device could then access an API endpoint and see user specific data. Is there any way to do this? Any other suggestions to solve this problem would also be welcome! -
Range Slider in Django form to select integer value
I want to select duration as an integer between 2 to 24 hours. I tried to use rangeslider.js but It is showing me text input box. models.py class AppointmentDetail(models.Model): duration = models.PositiveIntegerField(default=12, help_text='value 2 to 24', validators=[MaxValueValidator(24),MinValueValidator(2)]) Forms.py class AppointmentForm(forms.ModelForm): class Meta: model = AppointmentDetail fields = [duration] widgets = {'duration': forms.TextInput(attrs={'class': 'duration-input'}),} HTML File. <!Doctype HTML> <html> <head> <script src="jquery.min.js"></script> <script src="rangeslider.min.js"></script> <script> $(function (){ $('.duration-input').rangeslider({ }); }); </script> </head> <body> <p> Duration: {{form.duration}} </p> </body> </html> -
how to convert a text to dict in order to iterate it in python?
What i am trying to do is to iterate. I have this line of code in one column in a table in my database: [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] i assign this to a variable order so i have: order = [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] then i want to iterate it. I am trying the follow: for o in order.items(): product = o['item'] ... it doesn't work. How can i convert it? for order in orders: ord = order.shopping_cart_details # [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] temp = {'order_id': order.id, 'movies': ord['item'], 'created': order.created} full_results.append(temp) i get string indices must be integers -
Multiple object types references in Django
We are currently running with the following configuration to avoid other issues so for the question, let's assume this is a must and we can not change the Models part. So, at first, we had the following models: class A(Model): b = ForeignKey(B) ... set of fields ... class B(Model): ... Then we added something like this: class AVer2(Model): b = ForeignKey(B) ... ANOTHER set of fields ... Assuming an object in B can only be referenced by either A or AVer2 but never both, is there a way to run a query on B that will return, in runtime, the correct object type in the query result (and the query has both types in it)? You can assume that an object of type B holds the information regarding who's referencing it. I am trying to avoid costly whole-system code changes for this. Thanks! -
What to do to run makemigrations/migrate on heroku when deploying changed models from github?
I have deployed app from github repository to the heroku account of my customer as collaborator but this time I had to add some new models. However I realized that when I deploy my changes from github heroku does not run makemigrations and migrate. I I read some answers on stackoverflow and understood this is how it is supposed to be. However my question is what should I do ? What is the best practise to deploy change models to heroku app. (I assume it is not deleting and recreating my app again since customer already has data there.)