Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django imagefield form, how can I display image in the form
I have a Django ImageField model that I would like to add in the form to display image. How can I do that ? I tried this but the answer is incomplete. Display image from ImageField by means of form class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link"/>""") return mark_safe(html.substitute(link=value)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) there are errors. Im not sure how to complete this. NameError: name 'Template' is not defined NameError: name 'mark_safe' is not defined AttributeError: 'Template' object has no attribute 'substitute' My main goal is to have image shown in the form which has the ImageField field -
Django Form becomes Invalid When Field is Disabled
I am developing a django application for tracking a list of (music) albums that I've listened to, and when I've listened to them. I am trying to come up with how to render a form for creating a Listen (one of my models) for a specific Album (another model). The relevant part of Listen is very simple: class Listen(models.Model): """A model representing an instance of listening to an album. """ album = models.ForeignKey(Album, on_delete=models.CASCADE) listen_date = models.DateField(default=datetime.date.today, null=True) I have a generic CreateView for creating a view with no pre-populated data: class ListenCreate(generic.edit.CreateView): """View for adding a new Listen. """ model = Listen form_class = ListenForm template_name = 'tracker/generic_form.html' Then ListenForm looks like: class ListenForm(forms.ModelForm): class Meta: model = Listen fields = ['album', 'listen_date'] I've created a view that then is meant to add a listen for a specific album, where the album is deduced from an artist and album name in the URL: class ListenCreateForAlbum(generic.edit.CreateView): """View for creating a listen for a specific album. """ model = Listen form_class = ListenFormForAlbum template_name = 'tracker/generic_form.html' def get_initial(self): initial = copy.copy(self.initial) # Get the initial Album using the artist/album names in the URL initial['album'] = Album.objects.get( name__iexact=unquote_plus(self.kwargs['album_name']), artist__name__iexact=unquote_plus(self.kwargs['artist_name'])) return initial Now, … -
Django how to do aggregation on three tables
I'm doing now educational exercise about django ORM. Need to show total values of orders for particular customers for chosen Supplier on Northwind database, the database diagram can be found here: Northwind database diagram So far I did: QuerySet of ORDER_DETAILS objects that have products made by SUPPLIERS.supplierid = 1 >>> od =OrderDetails.objects.filter(product__in=(Products.objects.filter(supplier=(Suppliers.objects.get(supplierid=1))))) QuerySet of ORDERS objects that have ORDER_DETAILS products made by SUPPLIERS.supplierid = 1, without duplicated ORDERS Objects >>> o = Orders.objects.filter(orderdetails__in=od).distinct() Firstly I'm not sure if those two statements are correct? Secondly I have QuerySet of ORDERS objects that are about products manufactured by chosen supplierid and can't find a way to aggregate it to get total values of orders for particular customers. -
How to hash text with md5 in django? [duplicate]
This question already has an answer here: python django unsalted md5 password hash format 3 answers I need to generate some key or 'token' based in the combination of some email and password sended. I want this in MD5 but I don't know what plugins or libriries or something help me to do this... The equivalent of what I want in php is the next: <?php $email = $_POST['email']; $pass = $_POST['pass']; $token = MD5($email.'-'.$pass); ?> How can I do this in Django? -
Django template renders all my files at once
I am stuck with this issues for a while now. It goes like this: I have a model with lectures. I want that for every lecture to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files would be displayed and downloadable as well. The Issue is that every lecture displays all the files that have ever been uploaded in the admin panel. Here is my code: class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.OneToOneField('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> … -
Override the default UserAttributeSimilarityValidator error message in django
I am trying to override the default UserAttributeSimilarityValidator error message in django, but i don't know how? -
Is it possible to monkey patch Django's reverse?
Some of our urls include #. These are used for reverse lookup, both using reverse and the {% url template tag (which uses reverse internally). Django 1.8 used to leave it alone, 1.11 now encodes it to %23. Is it possible to put a monkey patch wrapper somewhere and have it be used everywhere without fail? Here's the wrapper I have: def patch_reverse(func): def inner(*args, **kwargs): print "inner reverse" url = func(*args, **kwargs) return url.replace("%23", "#") return inner from django.urls import base base.reverse = patch_reverse(base.reverse) The print statement is so I can see if it's actually running. I've tried putting it in settings, the __init__ of the first installed app, and in the urls of the first installed app. Nothing works. -
Regrouping in a Django template after the first regroup
I'm trying to create a page that has a group of photos, categorized by event, then within the event, by date. Currently, in my view, I am doing this: photos = Photo.objects.all().order_by('event') Then, in my template, I am doing this: {% regroup photos by event as event_list %} {% for event in event_list %} <h6 class="event-title"> {{ event.grouper|safe }} ({{ event.grouper.date }}) </h6> {% for photo in event.list %} <img data-src="{{ photo.thumbnail.url }}" alt="{{ event.grouper|safe }} ({{ event.grouper.date }})" class="img-responsive img-thumbnail" /> {% endfor %} {% endfor %} Is there a way I can group the photos once again by photo.date_captured? Would it be better to do this in the view? -
How do I grab the first objects from a Django queryset?
execution_list = JobExecution.objects.filter(job__name=job_name).order_by('-build_id')[:50] last = execution_list.pop(1) print last.id I've also tried execution_list[0], which throws another queryset error. How do I i just grab the first object from the queryset? I am aware that I can just append .last() to the query, but the problem is I need the full list as well as the first item. What am I doing wrong here? Error: 'QuerySet' object has no attribute 'pop' -
Django Multiple Files Upload Using Ajax without forms
I have an aplication in Django 2.0 where one user can upload many images of their diplomas at the same time but also, I need to make this with ajax so the page will not reload. This is my models.py class diploma(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE, null=True) diploma=models.ImageField(default='nopic.png', null=True) def __str__(self): return self.diploma And this is my file input in my template upload.html <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <input type="file" id="images" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif"> <a onclick="uploadWithAjax()"> Upload Images </a> If you notice, there's no Form html tag. Just an 'a' link that calls the function uploadWithAjax(). This is my script with the uploadWithAjax() function function uploadWithAjax() { var files = $('#images')[0].files; $.ajax( { type: "POST", url: "/UploadImages/", data: "", //I DON'T KNOW WHAT DATA I HAVE TO PUT HERE success: function(result) { alert('IMAGES UPLOADED'); } }); } I Think I have to send the 'files' variable in the 'data' atribute of ajax, but I'm not sure becouse there are files and dont normal inputs. Please help. This is my ajax.py file, where I recive the images def UploadImages(request): diplomas = request.FILES['images'] #I don't know if this is correct I didn't finish the view becouse I don't know how to continue or how … -
Using django orm to update a table without deleting relations
I have this two related django models class Item(models.Model): item_nbr = models.IntegerField(primary_key=True) created = models.DateTimeField(auto_now_add=True) item_nbr_desc = models.CharField(max_length=155) class SetItem(models.Model): set_id = models.CharField(primary_key=True, default='', max_length=12) set_nbr = models.IntegerField() items = models.ForeignKey(Item) Im running an script (periodically) to read the Item table from another database and to update the django db database. Im using the django orm framework in this task script.py from app.models import Item item_table = pd.read_sql(__) item_table = some_transformations(item_table.copy()) #I remove all the Items that will be updated Item.objects.filter(item_nbr__in=item_table.item_nbr.unique()).delete() item_table_records = item_table.to_dict('records') item_instances = [] fields = item_table.keys() for record in item_table_records: kwargs = { field: record[field] for field in fields } item_instances.append(Item(**kwargs)) Item.objects.bulk_create(item_instances) # update the new rows the problem is that the setItem table its deleted each time that I delete the Items related (because the on_delete=models.CASCADE behavior). I want to update the items not erasing the setItem related rows, and i don't want to change the on_delete default behavior because just in this script I need to upload a whole table, its possible that i want to delete a Item in another context and i hope that the cascade behavior is working. what can i do? its there a bulk update function that might perform … -
Django REST framework queryset object has no attribute pk
I am building a larger Django-based web app, but I have a blocking issue with an API view that should return some data. I the application I have a model (mail.models.Message) and a matching serializer and viewset. For a reporting feature, I need to get filtered set of results and have therefoer created a seperate rest_framework.views.APIView for the purpose of the reporting. The model is located in one app and the reporting is in another app. Here is the model: class Message(models.Model): class Meta: ordering = ('-timestamp',) get_latest_by = 'timestamp' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) from_address = models.CharField("From", max_length=511, blank=True, default="", db_index=True) from_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) to_address = models.CharField("To", max_length=511, blank=True, default="", db_index=True) to_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) subject = models.TextField(blank=True, default="", db_index=True) client_ip = models.GenericIPAddressField("Client IP", db_index=True, null=True) mailscanner_hostname = models.CharField(max_length=255, db_index=True) spam_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) mcp_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) timestamp = models.DateTimeField(db_index=True) size = models.FloatField(default=0) token = models.CharField(max_length=255, null=True) mailq_id = models.TextField("Mailqueue identification", null=True) whitelisted = models.BooleanField(db_index=True, default=False) blacklisted = models.BooleanField(db_index=True, default=False) is_spam = models.BooleanField(db_index=True, default=False) is_mcp = models.BooleanField(db_index=True, default=False) is_rbl_listed = models.BooleanField("Is RBL listed", db_index=True, default=False) quarantined = models.BooleanField(db_index=True, default=False) infected = models.BooleanField(db_index=True, default=False) released = models.BooleanField(db_index=True, default=False) def __str__(self): … -
Django Markdownx preview shown only after reloading page
I want django-markdownx to show maths formulas and equations and therefore integrated 'python-markdown-math' with it. Everything works as usual apart from the fact that I need to reload the page to get a preview of the typed mathematical formulas or symbols. The issue is only occurring when I type mathematical formula not others texts or upload image. Maths related stuffs (like $$..$$) seems to get skipped in preview and is shown only when I reload/refresh the page. Parts of my code: # settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'mdx_math', ] MARKDOWNX_UPLOAD_MAX_SIZE = 5 * 1024 * 1024 # 5 MB MARKDOWNX_SERVER_CALL_LATENCY = 1000 MARKDOWNX_IMAGE_MAX_SIZE = { 'size': (500, 500), 'quality': 90, 'crop': True, } MARKDOWNX_MEDIA_PATH = 'markdownx/' # models.py class MyModel(models.Model): content = MarkdownxField() @property def get_content(self): return mark_safe(markdownify(self.content)) # in my template <head> <title>MathJax TeX Test Page</title> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]} }); </script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> </head> <body> <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" name="" value="submit"> </form> {{ form.media }} </body> </html> Please help me find the problem which is causing such a behaviour. Note: Reloading … -
functools has no 'lru_cache' installing Django
$ pip install django Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-capC7C/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-capC7C/django/ -
How can I formulate this ForeignKey scheme?
I'm finding some difficulty resolving this problem in designing my Django models. The essential setup is a bipartitie graph (allowing for parallel edges), where the vertices on both sides of the graph express a lot of common logic. I am having trouble creating a model which allows for both vertices to be shared within the same database, and allows querying of all the edges incident to a vertex. I considered using an inheritance scheme, wherein vertices in a partition inherit from a parent Vertex class, but I kept tripping up, and really started perseverating on whether Django had some hidden, native and concise means of doing this. The current setup is about: class Vertex(models.Model): PARTITION_CHOICES = ( ('a': 'type a'), ('b': 'type b') ) partition = models.CharField(choices=PARTITION_CHOICES) # A bunch of other logic... class Edge(models.Model): ref_a = models.ForeignKey(Vertex, limit_choices_to={'partition': 'a'}, related_name='edges') ref_b = models.ForeignKey(Vertex, limit_choices_to={'partition': 'b'}, related_name='edges') # More logic... The obvious issue here is that both these foreign keys have the same related name, therefore clash. Tips from the wise? -
SQL error when running Django Migration
Environment: Ubuntu/Apache I am getting the following error when running a migration. Below the error is the migration file. The migration runs fine on a dev machine, but is erroring out when trying to deploy. The error is coming up within the Django code, so I don't have a lot to go on in order to sort this out. A summary of the migration is that it is removing null=True from three ManyToManyField fields and is changing the upload_to value for the remaining fields shown. Django (1.11.9) and psycopg2 (2.7.3.2) versions match on both machines. Is it possible to tell from this error message which field (if a specific field is the problem) is causing the error? Running migrations: Applying manager.0035_auto_20180119_1138...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, … -
Django Pipeline 1.6 & Sass
Javascript compresses fine and straight CSS works. But SASS doesn't seem to work at all What I'm using 1.7.11 Django 1.6.13 django-pipeline 2.7.9 Python I installed ruby-sass on debian apt-get -y install ruby-sass And it runs from the commandline using the default SASS_BINARY command /usr/bin/env sass -h Usage: sass [options] [INPUT] [OUTPUT] Description: Converts SCSS or Sass files to CSS. Here are my django settings.py pipeline settings # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = ['assets'] STATIC_ROOT = '/app/static' PIPELINE_STORAGE = STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_ENABLED': True, 'COMPILERS': ('pipeline.compilers.sass.SASSCompiler'), 'JAVASCRIPT': { 'application': { 'source_filenames': ( 'assets/javascripts/*', ), 'output_filename': 'javascripts/application.js', } }, 'STYLESHEETS': { 'application': { 'source_filenames': ( 'assets/stylesheets/application.scss' ), 'output_filename': 'stylesheets/application.css', 'extra_context': { 'media': 'screen,projection', }, }, } } -
All my files are rendered instead of selected ones
So I have this FileField which allows users to upload many files in the admin panel. Everything is fine. But when I want to see the files in the template, for each lecture, then each each lecture displays all the files from other lectures as well. Each lecture is supposed to show its particular uploaded files. So my guess its either the view, either the template. <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> {% endif %} {% endfor %} {% endfor %} </ul> {% endfor %} </ul> </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), 'files': FileUpload.objects.order_by('files'), } return render(request, 'courses/courses.html', context) -
Conditional HTML table td cell
I have the following HTML table td with Django tags. If the value of the tag is false I want the td value to be a red 'X' image. If the value of the tag is true I want the td value to be a green check image. Does anybody have any simple examples that will help me out? {% for sport in all_sports %} <tr class="sportrow {% cycle '' 'altrow' %}"> <td><a href="show/{{ sport.id }}">></a></td> <td>{{ sport.skill }}</td> <td>{{ sport.skilllevel }}</td> <td>{{ sport.yearswithsport }}</td> <td>{{ sport.certified }}</td> <td>{{ sport.new }}</td> </tr> {% endfor %} -
MultiValueDictKeyError when I trying to post image
When I trying to add image from admin panel all OK, but when I trying to add image from site, I have this error: image of error. views.py: def new_detail(request): if request.user.is_authenticated: if request.user.is_superuser: if request.method == 'POST': car = request.POST['car'] author = request.user detail = request.POST['detail'] price = request.POST['price'] description = request.POST['description'] image = request.FILES['images'] detail = Detail(car = car, author = author, detail = detail, price = price, description = description, images = image) detail.save() return redirect('/new_detail/') else: return redirect('/login/') return render(request, 'shop/new_detail.html') new_detail.html: {% extends 'base.html' %} {% block content %} <div class="content container"> <div class="row"> <div class="col-md-8"> <div class=".signin"> <form action="" method="POST"> {% csrf_token %} <h3>Автомобіль: </h3> <select name="car"> <option selected>Audi A8 D2 3.3 TDI</option> <option>Audi A8 D2 3.7</option> ... ... ... <h3>Ціна: </h3><textarea name="price"></textarea> <h3>Фотки: </h3><input type="image" name="images" /> <p> <input type="submit" value="Опублікувати" /> </form> </div> </div> </div> models.py: from django.db import models class Detail(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE,) car = models.CharField(max_length=100) detail = models.TextField() description = models.TextField() price = models.CharField(max_length=30) images = models.ImageField(upload_to='details', null = True, blank = True) def __unicode__(self): return self.detail def __str__(self): return self.detail When I trying to post Detail without image, I have the same problem. Before this wasn't. -
Django concatenate list queries from two models
As a Django newbie, I am trying to return JSON Objects from two models with each object containing the username, id, ticketID. Right now the code is simply putting the lists together without indexing. I should point out that there is a relationship between user and ticket so that can be traversed also. {"username":"Paul","id":2}, {"username":"Paul","id":2}, {"username":"Ron","id":19}, {"id":"1c6f039c"}, {"id":"6480e439"}, {"id":"a97cf1s"} class UsersforEvent(APIView): def post(self, request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) value = body['event'] queryset = Ticket.objects.filter(event = value) referenced_users = User.objects.filter(ticket_owner__in=queryset.values('id')) result_list = list(itertools.chain(referenced_users.values('username', 'id'), queryset.values('id'))) return Response((result_list)) -
Django RestFramework: two way ForeignKey relation
There are two models Parent and Children. class Parent(models.Model): name = models.CharField(max_length=128) children = ? class Children(models.Model): name = models.CharField(max_length=128) parent = ? If we need the children instances to have parent as link to model Parent we can use ForeignKey in Children and vice versa. If parent A has children B and C and we want A to have ids of children B and C and children B and C to have id of parent A. i.e. A.children = (B.id, C.id) and B.parent = A.id, C.parent = A.id. How can we achieve this? parent = models.ForeignKey(Parent, related_name='children') can this be used? -
NoReverseMatch at /signup/
when the user registers, does not show the page that the confirmation email was sent and does not send the confirmation email.django -
Django: relation "django_site" does not exist in app with psql using sites framework
after switching from sqlite to postgres for local dev db, I am unable to migrate my app. Several fixes and approaches I've attempted have not resolved (ex: Django: relation "django_site" does not exist). python: 3.6.3 Django Version: 1.11.9 psql (PostgreSQL): 10.1 err: File "/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 installed apps: DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'widget_tweaks', 'mptt', 'channels', 'honeypot', 'gunicorn', 'djangosecure', # Allauth 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) LOCAL_APPS = ( 'users.apps.UsersConfig', #because of a signal 'common', 'geo', 'community', 'objects', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS in .env file: SITE_ID=1 solutions I have attempted: Cleared all migrations and migration files and ran: $ ./manage.py makemigrations then I have attempted sequential and manual migrations of apps starting with django.contrib, such as: $ ./manage.py migrate sites (first) then applying additional migrations. but regardless of how I order app migrations does not change err or allow migration to complete. I have also tried migrations with --fake-initial. it looks like it is calling a site object before creating … -
Where should user specific model filters live in Django
I am designing a school app where users will be provided with model objects wrt their positions and roles. Now generally this seems to be handled by custom manager methods. However, they also need to be user specific, and user is in the request. So, how do I design a system without breaking the separation of concerns, i.e., MVC. I also intend to use Guardian app for object permissions in addition to the default authorization backend. I am not sure how to coordinate them either.