Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 :/ -
How top automaticly generate pages in Django?
I am try to make an internet shop with Django but i have a problem. I made a template to show products from certain category for now that looks like : {% for item in products %} .............. .............. {% endfor %} That works until i have only few products. But when it will be the hundreds of products how can i automatically generate pages for products ? For example for 10 products in a page? And in the bottom numbers for pages [1][2][3]...[100]. -
does overriding an abstract base class attribute affect other child class?
If I change the attribute of a abstract base classes field using , Classname._meta.get_field(fieldname).attribute = 'value' will it affect the other child classes fields too? -
Only able to login ONCE with Selenium and Django Testing
I'm testing using Django's tests and Selenium so I can run tests with a live browser. But it won't let me log in more then once. I am using Django's StaticLiveServerTestCase to access both static and media files live. I login by going to the page. I've tried putting the login code both in setUpClass to run once at the beginning and setUp to run each time. Both only let me log in once. Here's the code: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.contrib.auth.models import User from selenium import webdriver @override_settings(DEBUG=True) class LoginTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() # create user cls.user = User.objects.create_user( 'Testing User', 'somewhere@wherever.com', 'pwd') # initalize webdriver cls.driver = webdriver.Chrome() # doesn't work on FireFox either cls.driver.set_window_size(1280,800) cls.driver.implicitly_wait(5) # login - send username and password to login page cls.driver.get(cls.live_server_url+'/accounts/login/') cls.driver.implicitly_wait(10) username = cls.driver.find_element_by_name('login') username.clear() username.send_keys(cls.user.username) password = cls.driver.find_element_by_name('password') password.clear() password.send_keys("pwd") password.submit() # eubmits form @classmethod def tearDownClass(cls): cls.driver.quit() # quit after tests have run super().tearDownClass() def test_login_one(self): # this test PASSES self.driver.get(self.live_server_url) # go to home page login_menu = self.driver.find_element_by_id('login_menu') self.assertTrue( # if logged in username is in text of #login_menu self.user.username in login_menu.text ) def test_login_two(self): # this test FAILS self.driver.get(self.live_server_url) # go to home page login_menu … -
Django-el-pagination not working, pagination not showing up
So I tried installing django-el-pagination, but apparently, it doesn't want to load on my web page. Every package is installed but it won't show. Here is what I did: def index(request): course_list = Course.objects.all() page = request.GET.get('page', 1) paginator = Paginator(course_list, 1) try: courses1 = paginator.page(page) except PageNotAnInteger: courses1 = paginator.page(1) except EmptyPage: courses1 = paginator.page(paginator.num_pages) context = { 'courses1': courses1, 'courses': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div id="crs"> <h3>All courses</h3> <ul> {% paginate courses1 %} {% for course in courses1 %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} {% show_pages %} </ul> </div> -
Django Populate the admin model fields with the data
This is my model.py. I have registered this model with the admin panel. I want to populate my model with data. That data will come from another model and I will perform some calculations on it and put that data in this model. Any help guys. class Sectorcapitalratios(models.Model): sectorserialnum = models.IntegerField(db_column='SectorSerialNum', primary_key=True) # Field name made lowercase. sectorname = models.CharField(db_column='SectorName', max_length=50, blank=True, null=True) # Field name made lowercase. years = models.CharField(db_column='Years', max_length=15) # Field name made lowercase. debttoequityratio = models.FloatField(db_column='DebtToEquityRatio', blank=True, null=True) # Field name made lowercase. debttocapital = models.FloatField(db_column='DebtToCapital', blank=True, null=True) # Field name made lowercase. debttototalassets = models.FloatField(db_column='DebtToTotalAssets', blank=True, null=True) # Field name made lowercase. timestamp =models.DateTimeField(auto_now_add = True) #This will create the time class Meta: db_table = 'sectorcapitalratios' unique_together = (('sectorserialnum', 'years'),) #def __str__(self): # return self.sectorserialnum Admin.py class CapitalratiosResource(resources.ModelResource): class Meta: model = Capitalratios skip_unchanged = True report_skipped = False import_id_fields = ('ticker','years') class CapitalratiosAdmin(ImportExportModelAdmin,admin.ModelAdmin): resource_class = CapitalratiosResource list_display = ('ticker','years','debttoequityratio','debttocapital','debttototalassets') #Register the Capital Ratios model and admin with the admin admin.site.register(Capitalratios, CapitalratiosAdmin) -
Django relation "myapp_mymodel" does not exist error
I initially attempted to change the name of the CharField "NewsItem.markdown" to "NewsItem.name" and change its max length. I made migrations and migrated as per usual, however this led to an error telling me that "main_NewsItem.markdown" does not exist. After struggling with this (flushing database, dropping database and recreating it etc. with no change in the error message) I decided to delete that model all together and create a new one named "News_item". I again made migrations and migrated as per usual. This resulted in the following error: Environment: Request Method: GET Request URL: http://46.101.55.192/admin/main/newsitem/ Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (relation "main_newsitem" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "main_newsitem" ^ ) was the direct cause of the following exception: File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/koan/koansite/koansiteenv/lib/python3.5/site- packages/django/utils/decorators.py" in _wrapped_view 142. … -
Error in db with modeltranslation in django
I want to add internationalization to a project, so I use django-modeltranslation app. However, after following all the steps of configuration and running migrations, when I enter in my admin the model is registered, but when I click on it: "Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user." Here's the code (note I have put it all in a file for clarity): INSTALLED_APPS = [ 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nuggets', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Trans', 'USER': 'postgres', 'PASSWORD': 'c1l2a3u4', 'HOST': '127.0.0.1', 'PORT': '5432', } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('es', gettext('Spanish')), ) #Models code from django.db import models class News(models.Model): title = models.CharField(max_length=255) text = models.TextField() #Admin code from django.contrib import admin from .models import News from modeltranslation.admin import TranslationAdmin class NewsAdmin(TranslationAdmin): pass admin.site.register(News, NewsAdmin) #translation.py code from modeltranslation.translator import translator, TranslationOptions from .models import News class NewsTranslationOptions(TranslationOptions): fields = ('title', 'text',) translator.register(News, NewsTranslationOptions) ]2]2 I have tried before createing the models, after, … -
Django: Loop over 2 objects in same loop in template
I have two models that are related, and I need to create a table that takes from both objects. In my models: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) chamber_type = models.CharField(max_length=50) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class ChamberProperties(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=20) property_value = models.CharField(max_length=100) The structure is strange, but it's too late to just add properties and values to the chamber model. I'll have to live with the fact that they are two separate models. In my table I need the following structure: chamber_name(obj A) - property_value(obj B) - customer(obj A again) I tried zipped lists, but I don't seem to be able to unpack it: class ChambersView(generic.DetailView): template_name = 'pages/chambers.html' def get(self, request): user = User.objects.get(username=request.user) customer = Customer.objects.get(user=user) chambers_list = list(Chamber.objects.filter(customer=customer)) chamber_properties = list(ChamberProperties.objects.filter(chamber__in=chambers_list).order_by('id')) objects_list = zip(chamber_properties, chambers_list) form = ChambersFilterForm(request=request) return render(request, self.template_name, {'filter_form':form, 'objects_list': objects_list}) If I unpack it in python it works: for properties, chambers in objects_list: print("-----------------------------------------------------------") print("Property is: ", properties.property_value, "and the chamber is:", chambers.chamber_name) print("-----------------------------------------------------------") But when I go to my HTML template: <div class="card-body p-1"> <table class="table table-hover"> <tr class="table-active"> <th>Chamber</th> <th>Property Value</th> <th>Customer</th> </tr> {% for properties, chambers in objects_list %} <tr> <td><a href="{% url 'chamber' chamber.id %}">{{chambers.chamber_name}}</a></td> …