Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Integrating django-taggit and django-autocomplete-light outside admin
I want to integrate django-taggit outside admin and use django-autocomplete-light for auto-completion. As per the documentation, here, it appears as if it is possible to generate suggestions for tagging outside admin. However, I am unable to generate any suggestion following the instructions. #forms.py class ProblemDetailsTagForm(autocomplete.FutureModelForm): class Meta: model = Problem fields = ['topic_tags'] widgets = { 'topic_tags': autocomplete.TaggitSelect2('tag_autocomplete') } #models.py class Problem(CreateUpdateDateModel): topic_tags = TaggableManager() #urls.py url(r'^tag-complete/$', views.TagAutocomplete.as_view(), name='tag_autocomplete'), I have checked if my code matches to the documentation but no help. -
how to merge two different annotate in django?
I have two models like this: class Item(models.Model): title = models.CharField(max_length=128) class Order(models.Model): item = models.ForeignKey(Item) user = models.ForeignKey('users.User',null=True) gift_code = models.CharField(max_length=20,default='') I need to annotate two different query: Order.objects.filter(gift_code__isnull=False, gift_code__gt='').values('item__title').annotate(the_count=Count('item__title')) Order.objects.filter(gift_code__isnull=False, gift_code__gt='', user__isnull=False).values('item__title').annotate(the_count=Count('item__title')) the problem is I can't find a way to merge this two query. I tried this method, but both value was the same: all_gift = Count('item__title') used_gift = Count('item__title', filter=Q(user__isnull=False)) gifts = Order.objects.filter(gift_code__isnull=False, gift_code__gt='').values('item__title').annotate(all_gift=all_gift).annotate(used_gift=used_gift) the actual output: [{'item__title': 'title', 'used_gift': 500, 'all_gift': 500},...] my expected output is: [{'item__title': 'title', 'used_gift': 60, 'all_gift': 500},...] -
Context manager decorator never runs __exit__ if setUp fails inside test
I'm trying to solve a bug in django. The bug involves a class called TextContextDecorator which can be used a class decorator and/or context manager. As the bug description mentions, when using TextContextDecorator as class decorator enable is called just before Test.setUp, and disable is called after Test.tearDown.unfortunately, tearDown is not called in the event of a failure inside setUp. This can result in unexpected behaviour. One of the proposed solutions is that to use addCleanUp inside the setUp of TestContextDecorator, but I'm having difficulties in calling that function inside of decorator class. Here is the sample code provided to reproduce the bug.. class example_decorator(TestContextDecorator): some_var = False def enable(self): self.__class__.some_var = True def disable(self): self.__class__.some_var = False class Example1TestCase(TestCase): def test_var_is_false(self): # some_var will be False self.assertFalse(example_decorator.some_var) @example_decorator() class Example2TestCase(TestCase): def setUp(self): raise Exception def test_var_is_true(self): # won't be hit due to exception in setUp self.assertTrue(example_decorator.some_var) class Example3TestCase(TestCase): def test_var_is_false(self): # some_var will be True now due to no cleanup in Example2TestCase self.assertFalse(example_decorator.some_var) So far i have used try and except inside the setUp of TestContextDecorator and that seems to solve the bug but i'm not sure if its the best way to do it. Here are the changes … -
How add two model filed in class Meta:
I'm necessary add new field in User model. I create new model 'UserProfile', make inline and re-registration and add in model = User, UserProfile. Arises problem: AttributeError: 'tuple' object has no attribute '_meta' How fix this problem? Models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) avatar = models.ImageField(upload_to='images/users', blank=False) def __unicode__(self): return self.userenter code here forms class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, help_text='Please enter your email', widget=forms.TextInput(attrs={'placeholder': 'example@gmail.com'}), validators=[RegexValidator(regex=r'([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}', message='Incorrect email')]) first_name = forms.CharField(max_length=30, required=True, validators=[RegexValidator(regex='[a-z]', message='Incorrect name')]) class Imagefield(UserProfile): avatar = forms.ImageField(required=True) class Meta: model = User, UserProfile fields = ('username', 'first_name', 'avatar', 'password1', 'password2', ) -
Error: could not determine PostgreSQL version from '10.1' failed with error code 1 in /tmp/pip-build-07yg4mvk/psycopg2/
I want to push my Django app on heroku server and I installed my all rquirements.txt file which given below asgiref==1.1.2 asn1crypto==0.24.0 attrs==17.4.0 autobahn==17.10.1 Automat==0.6.0 beautifulsoup4==4.6.0 braintree==3.19.0 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 chromedriver-installer==0.0.6 constantly==15.1.0 cryptography==2.1.4 defusedxml==0.5.0 dj-database-url==0.4.2 Django==1.11 django-allauth==0.33.0 django-amp-tools==0.1.1 django-crispy-forms==1.5.0 django-filter==0.11.0 django-registration-redux==1.2 djangorestframework==3.7.1 gTTS==1.2.2 gTTS-token==1.1.1 gunicorn==19.7.1 hyperlink==17.3.1 idna==2.6 incremental==17.5.0 numpy==1.13.3 oauthlib==2.0.4 opencv-python==3.3.0.10 Pillow==5.0.0 psycopg2==2.7.4 PyAudio==0.2.11 pycparser==2.18 PyJWT==1.5.3 pyOpenSSL==17.5.0 python-decouple==3.1 python-social-auth==0.3.6 python3-openid==3.1.0 pyttsx==1.1 pytz==2017.3 requests==2.7.0 requests-oauthlib==0.8.0 selenium==3.7.0 six==1.11.0 social-auth-app-django==1.2.0 social-auth-core==1.4.0 SpeechRecognition==3.7.1 txaio==2.8.2 urllib3==1.22 virtualenv==15.1.0 whitenoise==3.3.1 zope.interface==4.4.3 After this I run this command git-push heroku maste I am getting Error: could not determine PostgreSQL version from '10.1' remote: remote: ---------------------------------------- remote: Command python setup.py egg_info" failed with error code 1 in /tmp/pip-build-07yg4mvk/psycopg2/ remote: ! Push rejected, failed to compile Python app. I have been unable to figure this out, please help. -
JSONB output from object.query() results in syntax error on raw sql
I am quite new to django and JSONB and I use this following syntax to excecute a search on JSONB data fields: obj=SomeModel.objects.filter(data__0__fieldX__contains=search_term) .. and it works as intended. Now, I print out the obj.query for the above statement and I get: SELECT * FROM "somemodel_some_model" WHERE ("somemodel_some_model"."data" #> ['0', 'fieldX']) @> '"some lane"' However, when I excecute the above using: obj=P2A_SomeModel.objects.raw(`query statement above`) I get an error: django.db.utils.ProgrammingError: syntax error at or near "[" LINE 3: #> ['0', 'fieldX']) @> '"some lane"' I presume I am not escaping the "[", and I have tried using a backslash before, but it does not seem to help. -
How can i generate pdf from a table in django using print button
Mainly i want to generate a pdf of output table in django framework by clicking the print button.Can any one help? or give some effective link or code ? -
How to display relevant information to instance of a ModelFormSet
I am using a ModelFormSet to allow the user to edit any of the entries on my Election model. I am generating the following formset in the view: election_formset = modelformset_factory(Election, fields=('CandidateReg','VotingOpen','FlipGrid')) The formset is of this model: class Election(models.Model): Name = models.CharField(max_length=20) # Allow to register / vote when True CandidateReg = models.BooleanField(default=True) VotingOpen = models.BooleanField(default=False) Description = models.CharField(max_length=255, null=True, blank=True) FlipGrid = models.URLField(null=True, blank=True) Complete = models.BooleanField(default=False) def __str__(self): return self.Name I'm rendering it in the template as follows: <div class="card-body"> <h4>Toggle election settings:</h4> <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} <!-- <h4> Display the Name field of the Election being edited </h4> --> <p>Allow candidates to register: {{form.CandidateReg}}</p> <p>Allow voting: {{form.VotingOpen}}</p> <p>Videos link: {{form.FlipGrid}}</p> {% endfor %} </form> </div> What I want to do is render the value in the Name field of the Election instance that is relevant to the below form (as indicated in the above template). I don't want the user to be able to edit the name, however. Is there a convenient way to do this? -
uWSGI + builded Go .so not working
I've build Go module with go build -buildmode=c-shared -o output.so input.go to call it in Python with from ctypes import cdll lib = cdll.LoadLibrary('path_to_library', 'output.so') When django project is served via uWSGI the request handler that calling Go library freezes, causing future 504 in Nginx. After getting in "so called freeze", uWSGI is locked there and only restarting helps to enliven app. No logs AT ALL! It just freezes. Everything works correctly when i run in python interpreter on the same machine. My thoughts: i've tried to debug this and put a lot of log messages in library, but it won't give much info because everything is fine with library(because it works in interpreter). Library loads correctly, because some log messages that i've putted in library. I think it some sort of uWSGI limitation. I don't think putting uwsgi.ini file is somehow helpful. Additional info: Go dependencies: fmt github.com/360EntSecGroup-Skylar/excelize log encoding/json OS: CentOS 6.9 Python: Python 3.6.2 uWSGI: 2.0.15 What limitations can be in uWSGI in that type of shared object work and if there a way to overcome them? -
Can't find file that got created in Command prompt
I'm trying to install the version module in Python 3. I am running the command pip install version. It then shows me an Import error cannot import name 'izip_longest'. I already know that I have to take out the i of izip in python 3, but I cannot find the file, where I can change it. It tells me the file (version.py) would lay in 'C:\Users\myname\AppData\Local\Temp\pip-build-p619-k9v6\version\version.py', but the folder pip-build-p619-k9v6 does not exist in my Temp directory. Any Ideas how I can get access to the file? Thanks -
Move file on django storage s3
I'm using django-storages with amazon s3, with a configuration close to this guide: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html Now I have a situation where I want to rename a lot of files when the model is saved, before implemented the s3 storage backend I simply called os.rename: os.rename(initial_path, new_path) Since that obviously doesnt work with django-storages, is there a a way of doing that differently using the storage's capabilities? -
django: how to specify database dynamically for factory boy
I am setting up a Django application with a lot of databases, and some of them are using the same models (they are not replicas). I already configured my routers and everything is working great. The problem appears when making the tests as I want to use factory-boy. On a different project I could setup the database inside Meta but now, I have to select on which database to create an instance dynamically (if not, I would have to create a DjangoModelFactory for each database, which wouldn't be pretty). Is there an (easier) way to specify the database dynamically for each creation? -
How can I relate a model to a celery task result?
I'm using django 1.11, with django-celery-results installed to store celery task results in the database. I'd like to have my model as: class Thing(model.Model, StatusMixin): # My model fields here task_result = ForeignKey('django_celery_results.TaskResult', SET_NULL, blank=True, null=True, related_name='thing') @property def status(self): """Current processing status of the task assigned to this model :return: the processing status, determined by checking the task_result """ # I want more complicated monitoring, but minimum example something like: return 'succeeded' if task_result.success else 'failed' So that I can launch a processing task that manipulates the contents of Thing... but when querying for Thing in the meantime, elegantly serialise out the processing status via the relation. Question: How and where should I set and save the task_result field in my model? I'd thought of something like this (where the task is executed): from tasks import my_task def my_view(request): # General view stuff to initialise a thing # ... thing_instance.save() # Launch an async task async_result = my_task.delay(thing.id) # Set the task result thing.task_result = TaskResult.objects.get(task_id=async_result.id) thing.save() But I'm struggling to understand the celery task.delay() method's inner workings - can I be certain the task result will be immediately available for use in the example above? -
Quickest way to get element by index in QuerySet
I'm trying to create time-efficient searching function for my system in Django considering that there are approximately 5 million objects. This is how i set query up: objects_found = (Model.objects.extra(where=["CHAR_LENGTH(attribute) > 300"])).filter(attribute__trigram_similar=message) I know that this QuerySet is yet not completely evaluated, and that's exactly what i don't want. For example, to complete evaluate the set up QuerySet like this: list(objects_found) It takes around ~60 seconds. If i want to get first item of the set up QuerySet in a classical way, it will still take ~60 seconds, since complete query is done: objects_found[0] But if i utilize methods like first(): objects_found.first() It takes around ~9 seconds, meaning that full QuerySet is not evaluated. Let's consider that objects_found has 500 objects. What if i need to do something like this: objects_found[40] or this: objects_found[:15] in a time efficient way? Therefore instead of searching through all 500 objects, the code will only search through 40 or 15 objects. Is there any implementation in Django QuerySet for this to be done? -
Django-importing excel file into django models
I need user to upload an excel file via the form provided and i need to process that uploaded excel file to save the data in my model. models.py class Patient_Record(models.Model): Patient_id=models.IntegerField(unique=True) Patient_sex=models.CharField(max_length=1,choices=Gender) Patient_name=models.CharField(max_length=20) Patient_sugar=models.DecimalField(decimal_places=3,max_digits=6) Patient_chlorestrol=models.DecimalField(decimal_places=3,max_digits=6) Patient_iron=models.DecimalField(decimal_places=3,max_digits=6) Patient_haemoglobin=models.DecimalField(decimal_places=3,max_digits=6) def __str__(self): return self.pat_name I have simple form to upload the file. <form method="POST" class="post-form" action="../Uploaded_file" enctype="multipart/form-data" name="myfile">{% csrf_token %} {{ upload_form.as_p }} <input type="submit" value="Upload" name="Upload" class="btn btn-primary"> </form> Can someone help me with the code to parse a excel file using POST to this model. I tried using many different methods but couldn't succeed in it. -
In django-tables2, change number of rows depending on screen size?
When using django-tables2, I limit the number of rows to display using the paginate parameter. For instance, if I have the table my_table, then in views.py I change the number of rows as follows: RequestConfig(request, paginate={'per_page':10}).configure(my_table) My problem is in my app I want the number of rows shown per page to depend on how big the user's screen is. For instance, 10 rows for mobile devices, but 25 rows for desktop screens. I am imagining doing in views.py what you can do with style sheets using the media rule (e.g., @media(max-height: 480px) {do something}). Related general discussion Interestingly, I haven't seen a lot of discussion of adapting table row count to media type, but there is obviously tons of more general discussion of responsive media-sensitive design: Responsive design with media query : screen size? https://developer.mozilla.org/en-US/docs/Web/CSS/@media -
How to represent foreign key lookup table in Django unit test?
I'm building three Django models that will allow users to create lists of items that represent activities (e.g. movies, concerts, and sporting events) they want to attend. Since each user can include one or more items (i.e. activities) in a list and multiple users may have the same item (activity) in one of their lists, there's a many-to-many relationship between lists and items: The 'list_type' table is a foreign key lookup table that identifies what types of activity items (movies, etc.) are stored in a list. I pre-populate this table via a Django migration when I run my initial migrations that create my tables. # list/models.py class ListType(models.Model): LIST_TYPES = ( (1, 'Movie'), (2, 'Concert'), (3, 'Sport'), ) type = models.CharField(_('type'), max_length=16) class Meta: db_table = 'list_type' class List(models.Model): user = models.ForeignKey(User) type = models.ForeignKey(ListType, help_text=_('Type of list')) name = models.CharField(_('list'), max_length=128, help_text=_('Name of list')) class Meta: db_table = 'list' unique_together = (('user', 'type', 'name'), ) class Item(models.Model): # value contains the pk of a movie, concert, or sporting event record lists = models.ManyToManyField(List, related_name='items'). value = models.IntegerField(_('item'), help_text=_('Item in list')) class Meta: db_table = 'item' I've been trying to represent the Type table with a factory-boy factory: import factory … -
Django 2.0 not reading POST request correctly (from Unity)
I'm receiving POST requests in a Django app using Python 3.5 (not from a web form, but from a Unity app). My goal is to send image data. I can confirm that Unity is generating the image correctly, and according to their docs I am sending it over correctly. The POST request hits my local server, but Django request.POST and request.FILES are always empty no matter how I structure the request from Unity. However, if I read request.body into a .txt file, I can see what look like perfectly normal requests: --pGBzDSypIQO4aFVbs4sjTmbBN5OpW3Huawm0D0ib Content-Disposition: file; name="drawing"; filename="drawing.png" Content-Type: multipart/form-data ‰PNG IHDR ð ð :R¼ IDATxìØÁ 0±¶ûïœÐ1” // etc... Also tried other headers or sending dummy POST data. Even the simplest form-data fails to populate request.POST: --hwlDqmtVKZ2EPkOJ7GuauDZNlYdE4nf4yNbGt9WR Content-Disposition: form-data Content-Type: text/plain; encoding=utf-8 a=b Does this look improperly formatted to anyone else? No matter how I send stuff as far as I can tell, Django's request.POST does not populate. Any suggestions? Something look out of place in those requests? Know how a Django request needs to look in order to be readable? Would love to know, thanks! -
Image paths in ReactJS not handled by Django
I have recently integrated react with our django application. I have set up the webpack configurations as shown below. I created a Django base template for our React templates to be rendered in. However, I do have an issue with images not showing up or not found by django. (the images urls are set in ReactJS scripts). The webpack setup: webpack.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var ip = 'localhost' var baseConfig = require('./webpack.base.config.js') baseConfig.devtool = "#eval-source-map" baseConfig.entry = { App1: [ 'webpack-dev-server/client?http://' + ip + ':3000', 'webpack/hot/only-dev-server', './chalktalk-react/App1', './assets/scss/main.scss', './assets/scss/fonts-icon.scss', './assets/scss/fonts-site.scss' ], }; baseConfig.output.publicPath = 'http://' + ip + ':3000' + '/assets/bundles/'; baseConfig.plugins = baseConfig.plugins.concat([ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new BundleTracker({filename: './webpack-stats-local.json'}), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('developement'), ENDPOINT: JSON.stringify('https://private-44a4c-chalktalkupdate.apiary-mock.com') } }), ]); baseConfig.module.loaders.push( { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader'] } ); baseConfig.resolve.extensions.push('.js') module.exports = baseConfig; webpack.base.config.js var webpack = require('webpack'); var path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const extractSass = new ExtractTextPlugin({ filename: 'style.css', disable: process.env.NODE_ENV === 'development' }); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { context: __dirname, entry: { // Add as many entry points as you have container-react-components here App1: './chalktalk-react/App1', vendors: ['react'] … -
App can't connect to Postgres anymore
I have a Django application that uses Postgres in production, and I'm not sure what happened along the way of me making changes, but the app is crashing because it appears as though it can't connect to the Postgres database. I'm getting this error in the logs Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.4/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: failed to create a backend connection DETAIL: executing failover on backend It was literally working at 3 this morning, super fast speeds, and than when I wake up this morning it decides it doesn't want to connect anymore. Here is my settings configuration file that I use in production. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'socialauto', 'USER': 'socialauto', 'PASSWORD': 'sa48921', 'HOST': '66.175.220.49', 'PORT': '5433', # PGPool } } It's been working for almost a year now, and the only thing I did with it was perform a pg_dump yesterday. At a loss what it could be -.- -
Django & algolia - conditional statements using
I'm hoping this isn't too obscure a question - I'm integrating the Algolia search platform into one of my projects to be able to search seamlessly and effortlessly yadda yadda. Essentially, I'm looking for a mixture of layouts for premium and low position of a business directory within the #hit-template element for Algolia ... Using {% if %} inside verbatim doesn't quite work...so there's clearly something I'm not understand/missing. Could it be purely in the javascript that I need to edit certain things? Not sure! What is {% verbatim %} ?? Not sure?! Can I have a mixture of javascript and html inside a script of type="text/template" ? {% verbatim %} <script id="hit-template" type="text/template"> {% if _highlightResult.is_premium %} <div class="card text-center mb-3"> <div class="crop-height bg-image-card card-header" style="background-image: url('{{ MEDIA_URL }}{{ get_image_url }}'); height: 160px !important;"></div> <div class="card-header" style="color: #fff !important; background-color: {{ brand_colour }} !important; font-size: 1.3rem;"> {{{ _highlightResult.name.value }}} </div> <div class="card-body"> <p class="card-text" style="color: {{ business.brand_colour }} !important;"><a href="https://www.google.co.uk/maps/search/{{ google_maps_location }}" style="color: {{ brand_colour }};"><i class="fas fa-map-marker fa-2x" data-fa-transform="down-6"></i></a></p> <p class="card-text"><small>{{ get_full_address }}</small></p> <p class="card-text p-2">{{ description }}</p> <a href="{{ absolute_url }}" class="btn btn-primary" style="background-color: {{ brand_colour }} !important; border-color: {{ brand_colour }} !important; color: #fff;">Visit Website</a> </div> … -
Error: could not determine PostgreSQL version from '10.1'
my postgres version is 9.6 and psycopg 2 version is 2.7.2 after running command - git push heroku master i am getting this Error: could not determine PostgreSQL version from '10.1' -
How to write a path for categories in Django
I have a little problem. I want to create detail path like /category/subcategory/post/id. Of course I want to use slugs. The template looks like this: For the categories I've create a view and url, but I can't do it for subcategories. Maybe someone can help me and know the solution? My views.py from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): kategorie = Kategoria.objects.filter(parent=None).order_by('name') firmy = Firma.objects.filter().order_by('publish')[:5] context = {'kategorie': kategorie, 'firmy': firmy} return render(request, 'ogloszenia/index.html', context=context) def detale_firmy(request, slug, id): numer_id = get_object_or_404(Firma, id=id) detale_firmy = get_object_or_404(Firma, slug=slug) return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy, 'id': id}) def kategoria_lista(request, slug): #this is code for creating category slug kat_lista = get_object_or_404(Kategoria, slug=slug) return render(request, 'ogloszenia/lista_kategorii.html', {'kat_lista': kat_lista}) My urls.py is: from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<slug>/<id>/', views.detale_firmy, name='detale_firmy'), path('<slug>/', views.kategoria_lista, name='kategoria_lista'), ] in index.html I have: {% for kategoria in kategorie %} <li> <b><a href="{% url 'kategoria_lista' slug=kategoria.slug %}">{{kategoria.name}}</a></b> {% if kategoria.children.count > 0 %} <ul> {% for sub in kategoria.children.all %} <li>{{ sub.name }}</li> {% endfor %} </ul> {% endif %} </li> {% endfor %} And how to include the code to have for example /administracja-i-polityka/administracja-rzadowa/post_name/id ?? My models.py is: … -
Django 1.8 migration strange behaviour
I am trying to modify an existing School app which has sub-apps like students, class, scores etc using django 1.8. My class model: class Class(Object): student = models.ForeignKey(School, related_name='school_student') section = models.CharField() roll = models.IntegerField() When I run python manage.py makemigrations class, I am getting a message No changes detected in app 'class'. But when I run python manage.py makemigrations, the changes are detected and the migration files are created under the school directory but not in the class directory. But when to the above model if I add a meta class. class Meta: unique_together = ('student', 'roll') And now if I run python manage.py makemigrations class, the changes are detected and the migration files are created under the class directory. Can someone tell me why such behaviour? -
Django tree query spanning multi model relation
Please consider code the following code. I'd like to create something like a tree structure (it will be in a table) related to a specific loged-in user. I'd like to have an overviewpage in which all categories are shown for which this user has items in the subcategories. My query works, but gives me all subcategory records and all posible items in those subcategories (so not just the subset for which the user has records. I have another way working by starting with the itemmodel and then going up in the tree, but thats not what i'm looking for (this makes creating a dynamic set of tables far to depended on the django template layer). I've looked at select_related and prefetch, but I can't get close to a solution. Any help would be appriciated. models.py: from django.db import models from model_utils.models import TimeStampedModel from django.conf import settings User = settings.AUTH_USER_MODEL class MainCat(TimeStampedModel): name = models.CharField(max_length=100, unique=True) rank = models.IntegerField(default=10) icon_class = models.CharField(max_length=100, null=True, blank=True) class SubCat(TimeStampedModel): name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(null=True, blank=True) icon_class = models.CharField(max_length=100, null=True, blank=True) main_cat = models.ForeignKey(MainCat) class Item(TimeStampedModel): user = models.ForeignKey(User, blank=True, null=True) item_name = models.CharField(max_length=100, null=False, blank=False) sub_cat = models.ForeignKey(SubCat, blank=True, null=True) …