Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Add Toggle Button
I need to add a toggle button as I have two fields for a blog post is_draft and is_published. As only one of them should be true at once, how can I toggle between them? -
How to show multipul pdf's in django view
Is it possible to show multiple PDF files in the Django view, rather than just one? My current view shows just one class PdfView(View): def get(self, request, *args, **kwargs): for pdf in pdfs: with open('/path/to/pdf/file/' + pdf.title + '.pdf', 'r') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=' + pdf.title + '.pdf' return response I'd like to open as many pdf's as needed, but keep running into HTTP ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION edit: here is the traceback Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 86, in run self.finish_response() File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response self.write(data) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 217, in write self._write(data) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 328, in write self.flush() File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 41] Protocol wrong type for socket -
Django REST Framework - Contact Form?
I've built a Django based web-application with the REST framework and I now want to implement a contact form. This will just take a message and send an email to an admin. It should be a generic POST endpoint ie. website/contact as there are several pages which should use it ie. "Contact us" or "Support". How do I make this "safe" to use online, to stop spammers. I don't think a captcha is enough as if someone reads the Javascript + finds out the endpoint - they could abuse it? How should I do this? Help is greatly appreciated. -
How can I add a class atribute to django auth login form?
I've just install Django's default authentication app. It is working and everything but I am wondwering how could I change the css of the form. Say I have this: <form ...> <input type = "text" class = "input-class" placeholder = "user"> <input type="submit" value="login" /> </form> which would show a pretty form following the class in the text input. And then, I have the simple ugly login.html template for Django auth: <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </div> What I want to do is to get the second form with the css classes of the first. Is there a way of doing so without messing with models and forms? And, if not, can someone please show me the way? Thank you very much -
Static file not found
I am using Saleor and I am trying to add a new static folder called fonts into the static folder. When I add a file to static/images I can reference the file, but if I create a folder called fonts: static/fonts and add the same file to it, the file is not found in the browser. I have tried "npm run build-assets" and cleared Cached images and files in the browser but the font file is still not found. Works: <link href="{% static 'images/font-awesome.css' %}" rel="stylesheet" type="text/css"> Does not work: <link href="{% static 'fonts/font-awesome.css' %}" rel="stylesheet" type="text/css"> Any idea how to make new folders load into static files? BTW I feel like this must be a nodejs thing. -
Django (imagekit) uploading error: No such file or directory error - 502
Uploading large images, around 5+mb, gives me a 502 error in Django Admin. Nginx tells me its unable to open the file. Seems to be Nginx or Django image-kit related, not 100% sure. Someone familiar with this issue and a possible cause or fix? Seems similar to this question. I'm using Postgress, Gunicorn but this doesnt seem to have anything to do with it. Its running on a lightsale instance (AWS). Versions: Django==1.11.9 django-imagekit==4.0.2 Pillow==5.0.0 Nginx Errors: 2018/02/15 15:25:30 [error] 9532#9532: *2727 open() "/home/martijn/sunstudies-env/static/CACHE/images/image/NIU_2759_60_61_62_63_fused/e1f01586ba89638395c70565844891f2.jpg" failed (2: No such file or directory), client: 145.89.53.228, s$ 2018/02/15 15:25:30 [error] 9532#9532: *2725 open() "/home/martijn/sunstudies-env/static/CACHE/images/image/Luzzu_Marsaxlokk/7e015267fb3f426a7e78f378a84d3885.jpg" failed (2: No such file or directory), client: 145.89.53.228, server: tes$ $/1.1", upstream: "http://127.0.0.1:8000/adminschools/schoolimage/add/", host: "test.sunstudies.nl", referrer: "https://test.sunstudies.nl/adminschools/schoolimage/add/" Image Model: class Image(models.Model): key = AutoSlugField(always_update=True, unique=True, populate_from='alt') title = models.CharField(max_length=35, blank=True, null=True) alt = models.CharField(max_length=120) description = models.CharField(max_length=255, blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) large = ProcessedImageField(upload_to='image', processors=[ResizeToFit(1820, 1024, False)], format='JPEG', options={'quality': 70}, validators=[image_validator]) medium = ImageSpecField(source='large', processors=[ResizeToFit(1024, 680, False)], format='JPEG', options={'quality': 70}) small = ImageSpecField(source='large', processors=[ResizeToFit(270, 180, False)], format='JPEG', options={'quality': 70}) tiny = ImageSpecField(source='large', processors=[ResizeToFit(45, 25, False)], format='JPEG', options={'quality': 20}) Nginx Settings: server { #increase max file size to 20mb client_max_body_size 20M; proxy_read_timeout 300s; proxy_connect_timeout 75s; ... } ... … -
Running python script inside a functional test in Django
The project that I'm recently working on load initial data by running a script: python manage.py shell < add_initial_data.py I'm making functional tests now and have to call this command to load initial data in the test database. I'm trying to use subprocess.call and call_command to run that script but I can't find the option to redirect the script file to shell. Is there a way to do that? I've tried with subprocess.call(['python', 'manage.py', 'shell', '<', 'add_initial_data.py']) and call_command('shell', '<', 'add_initial_data.py') but gives error not recognizing < add_initial_data.py -
Django source files not updating when changing pages
Using Django 1.11 with Viewflow-Pro 1.04 This is probably a very simple question, but I've spent hours googling and reading and have come up completely empty. Each page of my app has various CSS/javascript files that it loads with script and link tags. However, when a user clicks a link and it redirects them to another page, the source isn't refreshed - it is still using the source from the previous page (which is often similar, but not the same). Refreshing the page fixes it, as it pulls the correct source. But basically I'm having to refresh the page every time I get redirected to a new page. This has proven hard to debug, since a lot of pages have the same source and so they "seem" to work correctly - but I think it only happens with links. If my view.py redirects users (using return render or similar) then it doesn't happen. It is just if a user clicks a link to jump from one part of my site to another. Anyone have a clue what it could be? I would include code samples, but it's affecting my entire project - if some specific code would be helpful let … -
while running command Heroku logs Errros are below
2018-02-15T18:19:55.377507+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=shoppingwave.herokuapp.com request_id=551a7986-4cd6-4b43-9b9a-9f1eb46a5bc4 fwd="157.50.221.99" dyno= connect= service= status=503 bytes= protocol=https -
connecting to mariadb via django on windows 7
I am trying to use the Mariadb as my primary database for this django application I am building. I tried following the instructions on https://www.digitalocean.com/community/tutorials/how-to-use-mysql-or-mariadb-with-your-django-application-on-ubuntu-14-04 Although the link says its applicable to Ubuntu, I feel it can be applied to windows7 as well. I might be wrong. I went to settings.py and changed the following lines: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'live', 'USER': 'rdsuser', 'PASSWORD': 'gz#]5p%DS2', 'HOST': '172.19.45.116', 'PORT': '3306' } } I saved the above changes, then cd back to my project directory with manage.py in it, and typed python manage.py makemigrations and get the message "No changes detected". Ok, weird. I then went back over to my settings.py and noticed this: INSTALLED_APPS = [ 'scovilleapp', #name of the app I added 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Everything looks good. Then I went back to the super folder (the one with manage.py in it) and typed python manage.py migrate But I get this error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migratiosn table <<1142, "Create command denied to user 'rdsuser' @SRP-WKSTN06' for table 'django_migrations'. Do I need to ask my administrator to grant me permissions? Im using windows7, python3, django version 2.0.1 Thanks -
Django disallowed host error
This is the error I get when I visit 127.0.0.1:8000 in browser DisallowedHost at / Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. Before you yell at me and tell that you should add the it in your ALLOWED_HOSTS fields in settings.py, I already did that ad indicated here. Settings.py field (I know if I put * then else everything is redundant, but still it gives me the same error. ALLOWED_HOSTS = ['*','0.0.0.0','127.0.0.1'] This is my wsgi.py file import os from django.core.wsgi import get_wsgi_application # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wordtutor.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "wordtutor.settings" application = get_wsgi_application() How can I solve this? Edit : Python3.6 Django 2 -
Django/Python How do I get my receiver to add a value to a field relative to a previous addition - instead of indiscriminately adding to the value?
Python3.6.4; Django 2.0. Long time first time, please be gentle I'm creating a tracking application that accepts multiple work logs to a work order. I'm trying to track time spent on a workorder by obtaining a time delta from each log and sending it to the work order model to hold the aggregate time. The problem is, each time I'm updating an existing log it adds the entire time to the work order instead of just the difference. So if a log was previously 12-2:00 (feeds 2 hours to WorkOrder), and you changed it to 12-1:30 it was feed an additional 1.5 hours to WorkOrder, instead of subtracting 30min Is there a way I can check to see a time was previously sent to WorkOrder? I tried updating update_labor_hours to check if the timedelta was < or > the original time, but I couldn't really figure it out. Any help is appreciated! from django.utils.timezone import now from datetime import datetime, date, timedelta from django.db import models from django.db.models.signals import post_save # Create your models here. class WorkOrder(models.Model): labor_hours = models.DurationField(blank=True, null=True) class WorkLog(models.Model): work_order = models.ForeignKey(WorkOrder, on_delete=models.PROTECT) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) def _time_spent(self): return datetime.combine(date.today(), self.end_time) … -
static files don't visable in production | DJANGO
I am little bit confused. I use django-el-pagination application in my project. This app use next javascript in template: <script src="{% static 'el-pagination/js/el-pagination.js'%}"></script> In works perfect in django development server, but in production it show 404. In production I install this app. Here below my settings.py file: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') Also I did python manage.py collectstatic command. What I forget to do? -
Filter Inline using formfield_for_manytomany
I'm trying to filter results from a ManyToManyField in Django (1.11.3) admin. I have these two models: class Info(models.Model): info_id = models.AutoField(primary_key=True) fil_id = models.IntegerField() name = models.CharField(max_length=255) class Data(models.Model): fil_id = models.IntegerField() info = models.ManyToManyField(Info) and here is what I use to filter info ManyToManyField: class InfoInline(admin.TabularInline): model = Data.info.through extra = 1 class DataAdmin(admin.ModelAdmin): inlines = [InfoInline,] def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "info": kwargs["queryset"] = Info.objects.filter(fil_id=321) return super(DataAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Data, DataAdmin) My problem is that the inline isn't filtered, even that the default select box contains only filtered results. Please, see attached photo. -
DRF - serializer drops nested serializers
TL;DR: DRF drops the inner serialized object when validating the outermost serializer. I'm using django 2.0, django-rest-framework 3.7.7, python 3. I want to build a REST endpoint that performs a search in the database, using some parameters received in a POST (I want to avoid GET calls, which could be cached). The parameters should act like ORs (that's why I set all fields as not required), and I'm solving that using django Q queries when extracting the queryset. I have the following django models in app/models.py: class Town(models.Model): name = models.CharField(max_length=200) province = models.CharField(max_length=2, blank=True, null=True) zip = models.CharField(max_length=5) country = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=100) birth_place = models.ForeignKey(Town, on_delete=models.SET_NULL, null=True, blank=True, related_name="birth_place_rev") residence = models.ForeignKey(Town, on_delete=models.SET_NULL, null=True, blank=True, related_name="residence_rev") And I wrote the following serializers in app/serializers.py: class TownSerializer(serializers.ModelSerializer): class Meta: model = models.Town fields = ("id", "name", "province", "zip", "country") def __init__(self, *args, **kwargs): super(TownSerializer, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = False class PersonSerializer(serializers.ModelSerializer): birth_place = TownSerializer(read_only=True) residence = TownSerializer(read_only=True) class Meta: model = models.Person fields = ("id", "name", "birth_place", "residence") def __init__(self, *args, **kwargs): super(PersonSerializer, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = False Then I wrote a view to provide the REST interface, … -
NoReverseMatch Exception In Django Admin When Trying to Change Product
So when I create products in the Default Django Admin and Save then it works fine, the issue is when I go back to change them I get the following error:NoReverseMatch at /admin/main/apparel_product/6/change/ Reverse for 'main_apparel_picture_change' with arguments '(u'6',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I know it has to do with the end of the URL "6/change/" for this model. I can edit all other models except for this model. models.py: from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Apparel_Product(models.Model): product_name = models.CharField(_("Name"), max_length=255) # album_cover = models.ImageField( # _("Album Cover (240px x 240px)"), upload_to='media/', default='media/None/no-img.jpg') product_gender_type = models.CharField(_("Gender"),max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')]) product_brand = models.CharField(_("Brand"),max_length=25) product_description = models.CharField(_("Description"),max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Apparel Product") verbose_name_plural = _("Apparel Products") def __str__(self): return self.product_name @python_2_unicode_compatible class Apparel_Picture(models.Model): master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_caption = models.CharField(_("Caption"), max_length=255) product_photo = models.ImageField(_("Picture"), upload_to='media/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Picture") verbose_name_plural = _("Pictures") def __str__(self): return self.product_caption @python_2_unicode_compatible class Apparel_Price(models.Model): master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_price = models.CharField(_("Price"), max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at … -
can django admin leverage rest framework filters?
I have setup my models to use: import rest_framework_filters as filters class FoundationIPFilter(filters.FilterSet): foundation_ip_team_group = filters.RelatedFilter(FoundationIPTeamGroupFilter, name='foundation_ip_team_group', queryset=FoundationIPTeamGroup.objects.all(), lookups='__all__') technology = filters.RelatedFilter(TechnologyFilter, name='technology', queryset=Technology.objects.all(), lookups='__all__') class Meta: model = FoundationIP fields = '__all__' when i use the rest api to do complex foreign key filtering on FoundationIP, everything works fine. ie, this works: <myurl>/tracker/foundationip/?technology__name=sec11lpp when i use the same filtering in the admin interface, i get all results returned or i get error "filtering by not allowed" <myurl>/admin/tracker/foundationip/?technology__name=sec11lpp i think it's because the admin somehow isn't using the same filters as rest_framework, ie not loading the filters i have in filters.py. how can i get the admin to do this, ie use the same filters? my admin models look like: class FoundationIPAdmin(admin.ModelAdmin): list_display = ["id", "name", "technology", "foundation_ip_team_group", "design_type"] list_display_links = ["id"] list_filter = ["name", "technology", "foundation_ip_team_group"] list_editable = ["name", "design_type", "foundation_ip_team_group"] list_max_show_all = 200 class Meta: model = FoundationIP -
Using Dynamic Variable to populate Form label/verbose name
I am new to Django and the community. Thanks so kindly for assistance. I want to populate a form for model Score with dynamic labels/verbose names from another model : Question. Essentially, each user has 5 current questions which they are going to score in a form as either "yes" or "no" I have the data for a User's current five questions saved in a dictionary and can pass this dictionary into the view or template, but do not know how to use a dictionary to population the labels/ verbose names for the form. Thanks so much for any help. #Model class Score(models.Model): yesno = ((0,"No"),(1,"Yes"),) oneScore =models.IntegerField(choices=yesno,default='none') twoScore =models.IntegerField(choices=yesno,default='none') threeScore =models.IntegerField(choices=yesno,default='none') fourScore =models.IntegerField(choices=yesno,default='none') fiveScore =models.IntegerField(choices=yesno,default='none') author = models.ForeignKey('auth.User') date_created = models.DateTimeField(blank=False, null=False) #Model class QuestionManager(models.Manager): def current_for_user(self,user): question1 = Question.objects.filter(author=user,statementNumber=1).order_by('-id').first() question2 = Question.objects.filter(author=user,statementNumber=2).order_by('-id').first() question3 = Question.objects.filter(author=user,statementNumber=3).order_by('-id').first() question4 = Question.objects.filter(author=user,statementNumber=4).order_by('-id').first() question5 = Question.objects.filter(author=user,statementNumber=5).order_by('-id').first() question_list = {"1":question1, "2":question2, "3":question3, "4":question4, "5":question5} return question_list class Question(models.Model): statementNumber=models.IntegerField(choices=NUMBER, default='1',verbose_name="The number of the statement") text = models.CharField(max_length=500,help_text="Enter your text", verbose_name="New Statement") author = models.ForeignKey('auth.User') date_created = models.DateTimeField(blank=False, null=False) objects=QuestionManager() #Form class ScoreForm(forms.ModelForm): class Meta: model = Score fields = ('oneScore','twoScore','threeScore','fourScore','fiveScore','bigScore') #View def score(request): user = request.user questions = Question.objects.current_for_user(user) if request.method == "POST": questions … -
How to generate coverage report while running coverage.py
normally I just run: coverage run manage.py test to my django tests and then coverage xml to generate the reports. However I am now using Tox, and have two commands setup in my tox.ini commands = coverage run python manage.py test api coverage xml The issue here is that if any of the unittests fail, Tox exits out and the actual coverage xml command doesn't get executed. I'm trying to push results to Jenkins and so this doesn't work for me. Ideally I would like a way using coverage CLI to run the coverage AND generate the xml in one command, but I can't seem to figure out how to do that. Note: I have tried consolidating the two commands in my tox.ini to coverage run python manage.py test api; coverage xml and same result, tox exits after the initial tests have failed. -
Django-Filters include checkbox in results on every filter
I have my filters working correctly, but I want to also filter on a checkbox that's in my result set, is this possible with Django filters? My filter.py is the following: class UserFilter(django_filters.FilterSet): class Meta: model = Employee fields = [ 'employeeusername', 'employeefirstname', 'employeelastname', 'statusid', 'positiondesc' ] My search form is the following: <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> 3-4 User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Title {% render_field filter.form.positiondesc class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> In my result set I have the following: <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Title</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.positiondesc }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor … -
ModelForm parameter hasattr(obj, 'form') and not issubclass
I try to filter my ModelForm, by passing a parameter to it. I'm using Django 1.11.3. Here is my code admin.py file: class ColorInlineForm(forms.ModelForm): def __init__(self, *args, **kwargs): parameter = kwargs.pop('parameter') super(ColorInlineForm, self).__init__(*args, **kwargs) # below, instead on 321 I want to use parameter value self.fields['color'] = forms.ModelMultipleChoiceField(queryset=Color.objects.filter(par_id=321)) class Meta: model = Color exclude = ('system',) class ColorInline(admin.TabularInline): form = ColorInlineForm(instance=Color,parameter=444) model = Car.color.through class CarAdmin(admin.ModelAdmin): inlines = [ColorInline,] exclude = ('color',) admin.site.register(Car, CarAdmin) But I get this error: if hasattr(obj, 'form') and not issubclass(obj.form, BaseModelForm): TypeError: issubclass() arg 1 must be a class -
Override save for model
class Employee(models.Model): id = models.AutoField(primary_key=True) number_in_order = models.IntegerField(default=1) image = models.ImageField(upload_to='employees_photo/') name = models.CharField(max_length = 30, default='') position = models.CharField(max_length=60, default='') description = models.TextField(blank=True, default='') def __str__(self): return "%s" % (self.name) def save(self, *args, **kwargs): self.number_in_order = self.id super(Employee, self).save(*args, **kwargs) Why number_in_order field does not appropriates the value of id field -
Django No module named 'django.db.migrations.migration'
I had a custom user model in my project. I wanted to delete it and return default user model by deleting all tables in my database and deleting migrations. After this, I tried to run python manage.py makemigrations command but it writes: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/contrib/contenttypes/apps.py", line 9, in <module> from .management import ( File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/contrib/contenttypes/management/__init__.py", line 2, in <module> from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ModuleNotFoundError: No module named 'django.db.migrations.migration' I have no idea what I did wrong. -
Invalid use of group function when using extra
I have seen it is a django issue on https://groups.google.com/forum/#!topic/django-users/ly3ykSVx0B8 but the solutions they suggested on a linked resource are a bit complicated for my level. Basically, class Records(models.Model): task=models.CharField(max_length=10) unitcost=models.IntegerField() totalapplied=models.IntegerField() So, sample data is: Installation 3 30 Moving 4 10 I basically want to return Installation 90 Moving 40 For that, I turned to extra which works: Records.object.extra(select={'total':'SUM(unitcost * totalapplied)'}).values('task','total') The generated query groups on 'total' as well, generating a mysql query. Is there an easier work around that can be applied like a class instance or something since I have similar models. -
Wagtail admin app name?
The wagtail admin at /admin doesn't seem to set an app_name resolve('/admin/pages/3/').app_name returns and empty string For the django-admin I get 'admin' Is it possible for to set an app name for the wagtail admin, ie wagtail_admin ? I'm using a middleware that restricts access by IP, it does this by checking the app_name - since wagtail returns no name, it makes this a bit tricky :/