Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: list transfer to template and to JS
In Views.py i create a list variable - mortgages_counter.append(MonthlyPaymentAmount) it is transferred to .html template as: <input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter}}'> in JQuery (separate file i have to check if each element of this list is used). value is transferred to .js file as: var mortgages_counter = $('#mortgages_counter').val(); but according to console it was transferred as a string to Jquery - like ['1234','125'] and its length is 1 because of some reason, also check like access to index [0] gives - ' and [1] - 1 etc. how to operate with this list as with LIST and NOT a string? -
Order by in django doesn't work well
I have this model in my django project: lass Archivos(models.Model): ramo = models.ForeignKey(Ramo, on_delete=models.CASCADE) anyo = models.PositiveIntegerField() semestre = models.PositiveIntegerField() tipo = models.CharField(max_length=20) detalle_tipo = models.IntegerField() extension = models.CharField(max_length=5) archivo = models.FileField(upload_to='archivo/', null=True) def __str__(self): return '%s %s %s %s %s %s' % (self.ramo, self.anyo, self.semestre, self.tipo, self.detalle_tipo, self.extension) When I try to make a query of this objects, ordering by -anyo (Year descending), the list of objects are ordering ascending. This is my query: archivos = Archivos.objects.filter(ramo=ramo.id).order_by('-anyo', 'semestre','detalle_tipo') I've try adding a Meta class in my model like this: class Meta: ordering = ['-anyo'] But the list is still ordering ascending. It doesn't matter if the query is ordering by anyo or -anyo. How to solve this? I'm using the last version of django. -
Django 1.11: pass id to url to generate detail view
I've a list of "nanas" (babysitters) that I render correctly. Now I need that when someone clicks on one of them , a detail page (for only the clicked nana opens). I think my problem is on my template for all the Nanas, in the href: <a href="{% url 'app-administrador:nana' nana.id %}"> Or in the Urls. All Nanas page: This is listing nanas View: class NanasView(View): def get(self, request): nanas = Nana.objects.all() context = {'nanas': nanas} return render(request, 'app_administrador/nanas-registradas.html', context) It's URL: url(r'^referencias_de_nanas', views.NanasReferenciasView.as_view(), name='referencias_de_nanas'), All Nanas templates: {% extends 'app_administrador/templates/base.html' %} {% load staticfiles %} {% block content %} <!-- Member Entries --> {% for nana in nanas %} <!-- Single Member --> <div class="member-entry"> <a href="extra-timeline.html" class="member-img"> <i class="entypo-forward"></i> </a> <div class="member-details"> <a href="{% url 'app-administrador:nana' nana.id %}"> <h4> <p href="extra-timeline.html">{{ nana.nombre }} {{ nana.apellido_paterno }} {{ nana.apellido_materno }}</p> {% if nana.foto %} <img src="{{ nana.foto.url }}" class="img-rounded" width="160px"/> {% endif %} </h4> <!-- Details with Icons --> <div class="row info-list"> <div class="col-sm-4"> <i class="entypo-briefcase"></i> <a href={{ nana.antecedentes_policiales }}>Antecedentes policiales</a> </div> <div class="col-sm-4"> <i class="entypo-twitter"></i> <a href="#">@johnnie</a> </div> <div class="col-sm-4"> <i class="entypo-facebook"></i> <a href="#">fb.me/johnnie</a> </div> <div class="clear"></div> <div class="col-sm-4"> <i class="entypo-location"></i> <a href="#">{{ nana.direccion }}</a> </div> <div class="col-sm-4"> … -
Need to save a model accessed throuh ForeignKey Relation
Taking the below class, with a OneToOne Relation to django's user-model, is there a need to save the user object if it gets modified? In my testings it sometimes got updated and sometimes not. Is there some configuration to control this behaviour or should I simply call save() every time. Witch would also, through signals, call MyModel every time. class MyModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def first_name(self): return self.user.first_name @first_name.setter def first_name(self, first_name): self.user.first_name = first_name # is this needed? self.user.save() -
Django: Trying to click on a link and remove an assigned client
Good morning. I am having an issue trying to remove a client from an assigned bed. I created a one-item form called "RoomUpdate" that will allow a user to add a client to a bed that is empty via a dropdown through a ModelChoiceField. When the bed is full, it does not allow the access to the drop down, instead, I have a link that states "remove client." What I want to happen is when I click that button, it assigns the default value of None to that bed in that room. What's tricky, at least to my new-ish to Django mind, is how I do this through multiple tables. Having looked for multiple answers and tried different things, I know I've lost track of what I'm doing so I definitely could use some help. models.py class Room(models.Model): room_id = models.AutoField(primary_key=True) room_number = models.CharField(max_length=5) shelter_id = models.ForeignKey(Shelter) max_occupancy = models.CharField(max_length=3) floor_location = models.CharField(max_length=3) def __str__(self): return self.room_number class Bed(models.Model): bed_id = models.AutoField(primary_key=True) room_id = models.ForeignKey(Room, related_name='beds') bed_size = models.ForeignKey(BedSize) client_assigned = models.ForeignKey(Clients, null=True, blank=True, default=None) forms.py class RoomUpdate(forms.ModelForm): client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False) #def __init__(self, *args, **kwargs): #super(RoomUpdate, self).__init__(*args, **kwargs) #self.fields['client_assigned'].choices.insert(0, ('','---------' ) ) class Meta: model = Room fields = … -
Cron log showing shows cron jobs are running but not being executed? (Django-Python)
I have a django project and I'm using django-crontab to execute a periodic task. For testing I have this task at myapp/cron.py def cronSayHello(): print("Hello") return True In settings.py I have: CRONJOBS = [ ('*/1 * * * *', 'myapp.cronSayHello', '>> /home/myuser/myproj/myapp/file.log') ] No "Hello" is being printed in file.log . Am I missing something? Also /var/log/syslog shows: Jan 3 21:44:01 brahmh CRON[21727]: (vaish) CMD (/home/myuser/myvenv/bin/python /home/myuser/myproj/manage.py crontab run b74d4d1f47748498b81b5bcf863684c3 >> /home/myuser/myproj/myapp/file.log # django-cronjobs for myproj) Jan 3 21:44:01 brahmh CRON[21726]: (CRON) info (No MTA installed, discarding output) This is being logged every minute. Why is the output discarded? -
errorlist this field is required
form = AuthorForm(self.request.POST, self.request.FILES, self.request.user) class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['file','user'] class Author(models.Model): user = models.ForeignKey(User) file = models.FileField(upload_to='authors/') With above configuration, I get the error <tr><th><label for="user">User:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select id="user" name="user" required <option value="" selected="selected">---------</option> <option value="2">admin</option> <option value="3">user2</option> I do not want to set blank=True in user field. I've passed request.user to ModelForm and I want the same to be stored in db but it's not working as expected. May I know how to pass request.user to ModelForm. -
Django can't makemigrations after changing app name and db tables
I'm working with Django 1.11.5 and using PyCharm as my IDE. I've been trying to refactor my app name from "clinicaltrials" to "cancer_trials". PyCharm updated all of my project files accordingly. I then followed the steps in this SO answer to update the appropriate database tables. However, I'm getting the following error when I try run makemigration. I can't seem to figure out what this means and/or what part I'm missing here. > python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python_3.6.1\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python_3.6.1\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python_3.6.1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python_3.6.1\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python_3.6.1\lib\site-packages\django\core\management\commands\makemigrations.py", line 150, in handle loader.project_state(), File "C:\Python_3.6.1\lib\site-packages\django\db\migrations\loader.py", line 323, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Python_3.6.1\lib\site-packages\django\db\migrations\graph.py", line 409, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Python_3.6.1\lib\site-packages\django\db\migrations\migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Python_3.6.1\lib\site-packages\django\db\migrations\operations\fields.py", line 142, in state_forwards for name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('cancer_trials', 'cancer_trials') -
Django - when best to calculate statistics on large amounts of data
I'm working on a Django application that consists of a scraper that scrapes thousands of store items (price, description, seller info) per day and a django-template frontend that allows the user to access the data and view various statistics. For example: the user is able to click on 'Item A', and gets a detail view that lists various statistics about 'Item A' (Like linegraphs about price over time, a price distribution, etc) The user is also able to click on reports of the individual 'scrapes' and get details about the number of items scraped, average price. Etc. All of these statistics are currently calculated in the view itself. This all works well when working locally, on a small development database with +/100 items. However, when in production this database will eventually consist of 1.000.000+ lines. Which leads me to wonder if calculating the statistics in the view wont lead to massive lag in the future. (Especially as I plan to extend the statistics with more complicated regression-analysis, and perhaps some nearest neighbour ML classification) The advantage of the view based approach is that the graphs are always up to date. I could offcourse also schedule a CRONJOB to make the … -
Celery / Heroku - delay() does nothing when ran in the background using Heroku run python
I am attempting to add background workers using Celery to automatically run scripts each day to update the information my website provides. I've integrated Celery with Django and Heroku, and I can import the module and use the function, but it freezes when I use the add.delay()command until I press Ctrl+C to cancel the command. I am using celery 4.1 Here is how I run the commands: heroku ps:scale worker=1 heroku run python >>>from Buylist.tasks import * >>>add(2,3) >>>5 >>>add.delay(2,3) #-- Freezes until I press Control+C If you could help me figure out where my settings are misconfigured, that would be great. I'm testing atm. the tasks.py is the sample code to get a working example, and then I'll move on to figuring out CELERY_BEAT settings project/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) # Load task modules from all registered Django app … -
pytest - make multiple tests operate on the same db
I am trying to avoid multiple creation of the same django object for multiple tests using @pytest.fixture(scope='module') syntax. from bots.models import Bot @pytest.fixture(scope='module') def forwarding_bot(): (bot, created) = Bot.objects.get_or_create( name="test_bot", user=get_user_model().objects.create_user(username='test_user'), forward_http_requests_to='https://httpbin.org/post' ) return bot def test_get_bot_by_pk(forwarding_bot): print(f'test_get_bot_by_pk: bot count: {Bot.objects.count()}') def test_get_bot_by_uuid(forwarding_bot): print(f'test_get_bot_by_uuid: bot count: {Bot.objects.count()}') When I run pytest I get this output: test_get_bot_by_pk: bot count: 1 test_get_bot_by_uuid: bot count: 0 I understand the reason for this. The fixture function indeed gets fired once per module, but since its code creates a db object - only the first test finds it in DB. The question is - how do I make several tests operate on the same db and the same fixture? I am new to pytest so this is a challenge to me. -
How to use "django-autocomplete-light" in inline form
I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well. This is a picture of my form. At first glance, it works as desired: Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures). This is my form template where I suspect the error, because the first field works correctly as desired. <div class="container"> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <!-- Medication Table --> <table class="table"> {{ medication.management_form }} {% for form in medication.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle "row1" "row2" %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Submit Form"/> <script type="text/javascript" src="{% static '/js/core/jquery.3.2.1.min.js' %}"></script> {{ form.media }} <!-- script for add, delete, update --> … -
How to apply CSS to the email in django
How to apply CSS to HTML email in Django -
getting NoReverseMatch for a correct url and correct arguments
I have looked thoroughly my code and yet I am still stuck at this point where I get the NoReverseMatch error for correct url and correct parameters. Here is my URLConfig url(r'profile/$', views.agent_profile, name='agent_profile'), url(r'profile/(?P<pk>[A-Za-z0-9]+)/$', views.change_profile, name='change_profile'), url(r'assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$', views.assign_profile, name='assign_profile'), the view handling that request is : def assign_profile(request, pk, profile): agent = Agent.objects.get(pk=pk) # profile = Profile.objects.filter(designation=profile) # profile.agents = agent return render(request, 'portfolio/change_profile.html', {'agent': agent}) and the url in the template is called as follow: <li><a href={% url 'portfolio:assign_profile' pk=agent.code_agent profile="super_agent" %}>Super Agent</a></li> and the error is as follow: NoReverseMatch at /portfolio/profile/1/ Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$'] Request Method: GET Request URL: http://localhost:8000/portfolio/profile/1/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'assign_profile' with keyword arguments '{'pk': '1', 'profile': 'super_agent'}' not found. 1 pattern(s) tried: ['portfolio/assign/(?P<pk>[A-Za-z0-9]+)/profile/(?P<profile>[A-Za-z0-9]+)/$'] Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\admin\\PycharmProjects\\trial', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Wed, 3 Jan 2018 14:35:49 +0000 -
django.core.exceptions.ImproperlyConfigured Should I replace to use reverse_lazy() instead of reverse()?
I got an error,django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. When I searched this error messages,django reverse causes circular import was found and read it.Should I replace to use reverse_lazy() instead of reverse()?Or should I fix another point of the codes?Traceback says Unhandled exception in thread started by .wrapper at 0x102e9e378> Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/urls/resolvers.py", line 312, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/urls/resolvers.py", line 319, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The … -
If statement gives wrong output in query set
I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database. However, after I define selectedaccesslevel as: selectedaccesslevel = request.POST.get('accesslevelid') with a print statement it's displayed correctly as 3,4,5,6, or 7 depending on the option the user selects in the form. My issue seems to be with my nested if statement that always hits the else: when i use just selectedaccesslevel == '#'. I'm looking for my output for datareducecode to be 'S00009' and not . How can I accomplish this? Below is my view... def submitted(request): owner = User.objects.get (formattedusername=request.user.formattedusername) checkedlist = request.POST.getlist('report_id') print (f"checkedlist on submitted:{checkedlist}") access_request_date = timezone.now() coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername) datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid) # facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) # divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) # print(facilitycfo) # print(divisioncfo) selectedaccesslevel = request.POST.get('accesslevelid') print (f"accesslevel:{selectedaccesslevel}") selectedphi = request.POST.get('phi') print (f"phi:{selectedphi}") print (owner.coid.coid) if request.method == 'POST' and selectedaccesslevel == '3': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True) print (datareducecode) if selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', … -
How to use django-tagit-label outside admin panel?
I am currently working on a django project where one form is used outside the admin panel that requires tagging. I found django-tagit-labels Tagit Github but it only works for admin panel forms, any idea on how to use it outside the admin panel in custom pages ? -
How to read and open gal file from a selected path in my pc?
I used python code to analysis my data. But when I wanted to read the gal file I got error. w = pd.read_gal("C:\Users\Yousif\Downloads\PythonSpatial\statess7.gal") AttributeError Traceback (most recent call last) in () 1 ----> 2 w = pd.read("C:\Users\Yousif\Downloads\PythonSpatial\statess7.gal") 3 AttributeError: module 'pandas' has no attribute 'read' Also once I used this function w = pysal.open(pysal.examples.get_path("statess7.gal")).read() I got this error KeyError Traceback (most recent call last) in () 1 ----> 2 w = pysal.open(pysal.examples.get_path("statess7.gal")).read() ~\Anaconda3\lib\site-packages\pysal\examples__init__.py in get_path(example_name) 33 return os.path.join(base, 'examples', example_name) 34 else: ---> 35 raise KeyError(example_name + ' not found in PySAL built-in examples.') 36 37 KeyError: 'statess7.gal not found in PySAL built-in examples.' Ihope to help me how can I read and open gal file from path in my laptop. -
add limit for list in for loop django template
I want to print only 10 elements from list in Django template here is my code <ul> <h3>Positive Tweets :</h3> {% for tweet in positiveTweet %} <li>{{ tweet.0 }}</li> {% endfor %} </ul> How can I print first 10 elements if positiveTweet list having length of 100 something. -
Celery daemon doesnt start with sysmted on CentOS 7
Some time ago I encountered problem with starting celery on my CentOS 7 server. I am not systemd expert but tried to follow celery docs and did my best on it. I found one related problem on stackoverflow but it doesnt appeal to my case. I used Celery Daemonization docs to create my systemd unit, which is as follows (root user is there only to launch script, for production I am going to use diffrent one): [Unit] Description=Celery Service After=network.target [Service] Type=forking User=root Group=root EnvironmentFile=/etc/celery/celery.conf WorkingDirectory=/path/to/my/django/project ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target And EnviromentFile as follows: #C_FAKEFORK=1 # Name of nodes to start # here we have a single node CELERYD_NODES="w1" # or we could have three nodes: DJANGO_SETTINGS_MODULE=fk.settings # Absolute or relative path to the 'celery' command: CELERY_BIN="/var/bin/path/to/celery/in/venv" # App instance to use # comment out this line if you don't use an app CELERY_APP="myapp" # or fully qualified: #CELERY_APP="proj.tasks:app" # How to call manage.py CELERYD_MULTI="multi" CELERYD_PID_FILE="/var/log/celery_%n.pid" CELERYD_LOG_FILE="/var/log/%n%I.log" CELERYD_LOG_LEVEL="DEBUG" journalctl logs are as follows: Jan 03 14:24:06 … -
Inner classes - Inheritance and overriding their attributes
I'm trying to understand how Django uses python's metaclasses for it's database models (options) and came up with the following stripped down code snippet that should roughly mimic Django's logic. class DatabaseOptions(object): def __init__(self, opts): if opts: for key, val in opts.__dict__.items(): if not key.startswith('__') and not callable(val): setattr(self, key, val) class MetaModel(type): def __new__(cls, name, bases, classdict): result = super().__new__(cls, name, bases, dict(classdict)) opts = classdict.pop('DbMeta', None) if opts: setattr(result, '_db_meta', DatabaseOptions(opts)) return result class Model(object, metaclass=MetaModel): class DbMeta: database = 'default' migrate = True class User(Model): class DbMeta(Model.DbMeta): database = 'user' class GroupUser(User): class DbMeta(User.DbMeta): database = 'group_user' Using the above code, I would expect the following output: print(Model._db_meta.database) # default print(Model._db_meta.migrate) # True print(User._db_meta.database) # user print(User._db_meta.migrate) # True print(GroupUser._db_meta.database) # group_user print(GroupUser._db_meta.migrate) # True Instead I get the following exception >>> python3 test.py default True user Traceback (most recent call last): File "test.py", line 48, in <module> print(User._db_meta.migrate) # True AttributeError: 'DatabaseOptions' object has no attribute 'migrate' My question would be why User.DbMeta does not inherit the migrate attribute from Model.DbMeta? Is there any solution for this kind of problem? -
ImportError: No module django_nose
I following this pluralsight course and running into this error everytime I run the command: python manage.py test --settings=todobackend.settings.test I'm new to the Django framework; any idea why I'm getting that error, also see folder structure in pic below: python --version Python 2.7.13 Click on pic to see larger, clearer image. -
Use Django User permission layout for other manytomany field
When in a User object in the Django Admin, there is a really nice way to add permissions to the user. For a completely different model, I would like to use the same system. This model has a manytomany field to another model. Is there a way to copy the layout of the user admin, to this model's admin? -
Django website loads slow after using requests to check broken links
My website gives deatails about different servers. I have used requests to check which server ILO IP is not working through http and which is not. AFter using requests.. the page loads super slow! My server checks ILO Ips of many servers and if the server is broken it shows the IP as a text and if not it shows a link(THE IP) to the ILO. Do you know how to make the server load much faster? Thanks.. models.py - from django.db import models import requests class serverlist(models.Model): ServerName = models.CharField(max_length = 30,blank=True) Owner = models.CharField(max_length = 50,blank=True) Project = models.CharField(max_length = 30,blank=True) Description = models.CharField(max_length = 255,blank=True) IP = models.CharField(max_length = 30,blank=True) ILO = models.CharField(max_length = 30,blank=True) Rack = models.CharField(max_length = 30,blank=True) Status = models.CharField(max_length = 30,blank=True) def checkUrlAvailable(self): ip_check = 'https://' + self.ILO resp = requests.head(ip_check,allow_redirects=False) if resp.status_code == 303: return True else: return False index.html - {% if server.checkUrlAvailable is True %} <a href="//{{ server.ILO }}"> {{ server.ILO }} </a> {% else %} {{ server.ILO }} {% endif %} -
Javascript code for Bootstrap Sidebar menu not working
I have a Sidebar / Menu that I am working with. It has been created with Bootstrap, DJango, and Javascript. Basically, I am trying to write Javascript so that when on clicks on a menu-item, the background changes color (dark blue), the icon change color (light green / turquoise) and it gets a type of "wedge" Below is an example of a menu-item that has been chosen (Dashboard) along with menu-items that have not been chosen (Security and Messages). The "wedge" has a red arrow pointing to it. Here is the HTML code that is being used: [... snip ...] <div class="page-container"> <div class="page-sidebar-wrapper"> <div class="page-sidebar navbar-collapse collapse"> <ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <li class="nav-item start active open"> <a href="{% url 'mainadmin:dashboard' %}" class="nav-link nav-toggle"> <i class="fa fa-tachometer"></i> <span class="title">Dashboard</span> <span class="selected"></span> <span class="arrow open"></span> </a> </li> <li class="nav-item "> <a href="{% url 'mainadmin:security' %}" class="nav-link nav-toggle"> <i class="fa fa-users"></i> <span class="title">Security</span> <span class="arrow"></span> </a> </li> <li class="nav-item "> <a href="{% url 'mainadmin:in_progress' %}" class="nav-link nav-toggle"> <i class="fa fa-comment"></i> <span class="title">Messages</span> <span class="arrow"></span> </a> <ul class="sub-menu"> <li class="nav-item "> <a href="{% url 'mainadmin:in_progress' %}" class="nav-link "> <span class="title">List All Messages</span> </a> </li> <li class="nav-item "> <a href="{% …