Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Anisble django postgres how to get user account or see if user exists
I need to determine if any users exist in a Django site using postgresql. I'm using ansible to update the sites including building new sites. If the site is not new, I check to make sure the database does not exist. If not, I create the database and the superuser. The next time the system runs, it knows not to create the database, but when it goes to create the superuser again, I get a fatal error. Hence, I need to check on if there are users in the database. -
Django "'str' object has no attribute 'decode'" Error
I'm not using any decode in my codes but I receive this error on Google Cloud Engine. However app is working fine on my local. this is my view for the home page. ( Pagination is commented because it gives same error on pagination too) def HomePage(request): id = 0 post = Post.objects.filter(is_active=True).select_related('created_user').prefetch_related('category') # paginator = Paginator(post, 10) # page_obj = paginator.page(request.GET.get('page', '1')) context = { 'posts': post # page_obj } return render(request, 'index.html', context) This is the content of the one view for the including setting.html. The logic is same in others. import traceback from django import template from django.db.models.functions import Coalesce from .models import AppSettings from django.db.models import Count from django.http import HttpResponse register = template.Library() @register.inclusion_tag('setting.html') def get_base(base): try: appsetting = AppSettings.objects.filter(is_active=True) except Exception as e: trace_back = traceback.format_exc() # message = str(e) + " " + str(trace_back) # return {'appsettings': appsetting} return HttpResponse({'appsettings': appsetting}) I have changed below part in the django\db\backends\mysql\operations.py, but I see original line in the traceback. Also it doesn't allow me deploy with the original first line. # query = query.decode(errors='replace') query = errors='replace' Traceback: Environment: Request Method: GET Request URL: http://flowing-my_server.appspot.com/index/ Django Version: 2.2.7 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', … -
Django app on Azure not gettin static files
Got my Django project on a Azure webapp, but when I call on SSH terminal: Python manage.py collectstatic It always says files copied and of course, my static files are not visible on my templates...Here's my folder structure: Myproject |---settings.py |---urls.py ├── myapp │ ├── migrations │ ├── __pycache__ │ ├── static | |------myimage.png | |------myimage.png │ └── templates And this is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = (os.path.join(BASE_DIR, 'Myproject/static_files/')) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ('myapp', os.path.join(BASE_DIR, 'myapp', 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) Any idea why or what am I doing wrong ?, does Azure collect different ? -
Save generated pdf in folder Django
The code below generate the pdf of an instance and the generated pdf files can be downloaded one by one from the browser. I want the generated pdfs to automatically save in a folder in my static directory or perhaps a given file path. Can someone kindly help me with that. def gen_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('order/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf_generate.css')]) return response -
Django Shows Page Source Instead Of My Webpage
I have found that when passing context and a title into my views it causes the page to only show its html source code instead of the actual frontend graphics. If i remove the title being passed in then it works again but i do want to have the title passed in so is there any way to have this work? Views def myPosts(request): context = { 'products': Post.objects.all() } return render(request, 'create/my_posts.html', context, {'title_page': 'My Posts'}) class PostListView(ListView): model = Post template_name = 'my_posts.html' context_object_name = 'products' -
Why doesn't my social media icon display correctly
So I'm trying to add social media icons to the footer of my web application. I was able to do it in a separate HTML file but when I tried it in my Django app I'm not able to make the icons look the way I want it. Seems like my css for the icon isn't working and showing. I deleted the css for the icon and it was the same. Not sure what I'm doing wrong body { background: #fafafa; color: #333333; margin-top: 5rem; } h1, h2, h3, h4, h5, h6 { color: #444444; } ul { margin: 0; } .bg-steel { background-color: #5f788a; } .site-header .navbar-nav .nav-link { color: #cbd5db; } .site-header .navbar-nav .nav-link:hover { color: #ffffff; } .site-header .navbar-nav .nav-link.active { font-weight: 500; } .content-section { background: #ffffff; padding: 10px 20px; border: 1px solid #dddddd; border-radius: 3px; margin-bottom: 20px; } .article-title { color: #444444; } a.article-title:hover { color: #428bca; text-decoration: none; } .article-content { white-space: pre-line; } .article-img { height: 65px; width: 65px; margin-right: 16px; } .article-metadata { padding-bottom: 1px; margin-bottom: 4px; border-bottom: 1px solid #e3e3e3 } .article-metadata a:hover { color: #333; text-decoration: none; } .article-svg { width: 25px; height: 25px; vertical-align: middle; } .account-img { height: … -
Display image in Template
I've been trying to display in my template an image that is stored in my model. but I can't. Could someone please tell me what I'm doing wrong? Thank you in advance. model.py: class DeviceType(models.Model): type_name = models.CharField(primary_key=True, max_length=64, unique=True) type_description = models.TextField(max_length=512, blank=True) def __str__(self): return self.type_name def get_absolute_url(self): return reverse("devices:type-detail", kwargs={"pk": self.pk}) class DeviceTypeImage(models.Model): image_status = IntegerField(unique=True) image = models.ImageField(upload_to='images/types/') image_device_type = models.ForeignKey(DeviceType, on_delete=models.CASCADE, related_name='image') def __str__(self): return str(self.image_status) def get_absolute_url(self): return reverse("devices:type-detail", kwargs={"pk": self.pk}) view.py: class DeviceTypeDetailView(DetailView): template_name = 'devices/type-detail.html' model = DeviceType def get_object(self): return get_object_or_404(DeviceType, pk=self.kwargs.get("pk")) template: <h1>Type detail</h1> {{ object.type_name }}<br> {{ object.type_description }}<br> {{ object.image_status }}<br> {{ object.image_device_type }} <img src="{{ object.image.url }}" alt="..."> urls.py: urlpatterns = [ .... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how can I print objects in a model as options
my html <select multiple class="form-control" name="tags"> <option value="">{% for tag in Tag %} {{ tag }} {% endfor %} </option> </select> my views.py def CreateView(request, pk=None): queryset = Tag.objects.all() args = {'Tag':queryset} return render(request, 'home/create.html', args) i wrote my code like this but it is printing them as one option oh and i am still a beginner Thank you in advance -
Django redis caching per url
So I am trying to implement moreover learn how to cache Django views per URL. I am able to do so and here is what is happening... I visit a URL for 1st time and Django sets the caches. I get my result from cache and not from querying the database during the second visit if the browser is same. Now the doubt is - if I change my browser from the first visit and second visit, for example, do the first visit from Chrome (it sets the cache) and during the second visit from Mozilla, it again sets the cache. I was expecting it to return the result from the cache. During my research on StackOverflow and checking what it sets as cache, I found there are two important things first being a header and the second being the content. And I think every time a browser is changed the header is new so it sets the cache instead of returning the result from cache. Do let me know if I am wrong. I have a public URL and I was thinking to show data from the cache if a subsequent request is made, irrespective of browser or mobile/laptop/desktop, … -
Trying to view a network pdf file with Django
Please help. I have a project that shows the path of a list of pdf files on the network but it has been impossible to view them after the click. I have tried almost everything without good results. Thanks. -
How can I add a field to a many-to-many relationship in Django?
This is a question about how to add a field to a many-to-many relationship in Django. I have a model LandingPage and a model Product. (Code below). In my project, LandingPages can have many Products listed on them and those same Products can appear on multiple different LandingPages. Product is connected to LandingPage via a ManyToManyField. My Goal: I am trying to figure out how to add a field so that I can set the order (1 through 10) for Products on their associated LandingPages. Reminder, Product instances can appear on multiple LandingPages, so each instance will need to have a different order attribute. Ideally, I'd like to expose this functionality via the built-in Django admin. Right now it shows the relationships table, but not the order field as it does not yet exist. (Screenshots/mockups below). My Code: models.py class LandingPage(models.Model): """Stores a single LandingPage and metadata. """ name = models.CharField(max_length=200, help_text="The name is only used internally. It is not visible to the public.") slug = models.SlugField(default="", editable=False, max_length=150, null=False, verbose_name="Slug", help_text="This is not editable.") # Additional fields that I do not believe are relevant class Product(models.Model): """Stores a single Product and metadata. """ name = models.CharField(max_length=200, help_text="Used internally. Not … -
django.forms.fields.DateTimeField got error: 'list' object has no attribute 'strip', when calling BaseForm._clean_fields()
Handling of a POST request led to calling _clean_fields(self). The form contains a field in type of django.forms.fields.DateTimeField, and it triggered an exception of "AttributeError" saying 'list' object has no attribute 'strip'. It looks like, on step value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) the field got a return as ['', ''], which is a list of empty strings. Later on, step value = field.clean(value) triggered the exception. I'm still new to Django, and this is a project to upgrade from Python2.7+Django1.8 to Python3.7+Django3.1. The older version doesn't have this issue. Any pointers will be highly appreciated. Partial source code of django/forms/forms.py: def _clean_fields(self): for name, field in self.fields.items(): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. if field.disabled: value = self.get_initial_for_field(field, name) else: value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) try: if isinstance(field, FileField): initial = self.get_initial_for_field(field, name) value = field.clean(value, initial) else: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) -
psql migrate giving error: psycopg2.errors.UndefinedTable: relation "accounts_profile" does not exist
When i run the command python manage.py makemigrations followed by python manage.py migrate I keep getting this error: C:\Users\Rohan\teamproject\epic>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying admin.0001_initial...Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "accounts_profile" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Program Files\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 245, in handle fake_initial=fake_initial, File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 229, in apply_migration migration_recorded = True File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 115, in __exit__ self.execute(sql) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute cursor.execute(sql, params) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 98, in … -
Mysql database problem with django and vscode
im working on creating website with tools like vs code, django , mysql(using macos). I was trying connect my database to phpmyadmin with mamp but couldn't. Then i tried connect to mysql workbench and that was working.Think that i broke something because i couldn't run program(had out put like :django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?`). Finally when tried to install mysqlclient and mysql to my venv i got error like below. Do you have some sugestion to solve this problem? Thanks for help! ERROR: Command errored out with exit status 1: command: /Users/arincatlamaz/Documents/praca-inzynierska/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/setup.py'"'"'; __file__='"'"'/private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-record-uph0htiy/install-record.txt --single-version-externally-managed --compile --install-headers /Users/arincatlamaz/Documents/praca-inzynierska/env/include/site/python3.8/mysqlclient cwd: /private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/ Complete output (118 lines): running install running build running build_py creating build creating build/lib.macosx-10.14.6-x86_64-3.8 creating build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb creating build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.14.6-x86_64-3.8 creating build/temp.macosx-10.14.6-x86_64-3.8/MySQLdb xcrun … -
POST and GET requests to a client API URL using Django REST
I am kind of new to API. I am working on a project where I can send POST and GET requests to different APIs. I just want to know how sort of the class in the view file should look like. For example, I have a class that inherits generics.GenericAPIView. How do I send a get request to a specific URL or how do I save the data using the serializer to the database with post request? class ArticelViewSet(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin): serializer_class = ArticleSerializer_Modelserializers queryset = Article.objects.all() lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) #return the created object -
How to serialize three models with many to many relationships in Django Rest Framework
I have three base models: class User(models.Model): displayName= models.CharField(max_length=128) class Cell(models.Model): title = models.CharField(max_length=128) class List(models.Model): title = models.CharField(max_length=128) And three many-to-many relationships between them: class UserCell(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) cell = models.ForeignKey( Cell, on_delete=models.CASCADE ) value = models.SmallIntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'cell'], name='unique_UserCell' ) ] class UserList(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) target_list = models.ForeignKey( List, on_delete=models.CASCADE ) last_updated = models.DateTimeField(default=timezone.now) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'target_list'], name='unique_UserList' ) ] class CellAssignment(models.Model): target_list = models.ForeignKey( List, on_delete=models.CASCADE ) cell = models.ForeignKey( Cell, on_delete=models.CASCADE ) idx = models.SmallIntegerField() class Meta: ordering = ['idx'] constraints = [ models.UniqueConstraint( fields=['target_list', 'idx'], name='unique_cellAssignment' ) ] My view is given a List.id and a User.id and I want to return data in the following format, or something similar: {"List.id": 2, "List.title": "The Big List of Cells", "List.created_date": "2020-10-02T18:14:02Z", "cells": [{"target_list.id": 2, "Cell.id": 6, "CellAssignment.idx": 0, "Cell.title": "The first cell", "UserCell.value": 4}, {"target_list.id": 2, "Cell.id": 12, "CellAssignment.idx": 1, "Cell.title": "This is the second cell and so on", "UserCell.value": 9}, ...]} Is it possible to do this by nesting serializers, or should I query the relationships separately and join the data in the view? Any info … -
Django: Where can i find user login, logout activity for past 1 year
In django, is there any where the login, and logout activity for past 1 year is there any tables which stores these details I am using a web, session based application -
Static files django do not load with nginx and daphne
recently I needed to implement a solution with django-channels in an application that was in production with NGINX and uWSGI. It worked well. So, I had to stop the systemd service that managed uwsgi in order to run and manage Daphne as follows: [Unit] Description=daphne daemon for ubuntu After=network.target [Service] User=ubuntu Group=ubuntu WorkingDirectory=/path/to/my/app/ ExecStart=/path/to/my/app/env/bin/daphne -b 0.0.0.0 -p 8000 myproject.asgi:application [Install] WantedBy=multi-user.target However, when performing modifications to the nginx file, even though the application is running, static files are not being loaded. My nginx file looks like this: upstream channels-backend { server localhost:8000; } server { listen 80; # 8000 server_name my_server_ip; # substitute your machine's IP address or FQDN charset utf-8; client_max_body_size 75M; # adjust to taste location /media { alias /path/to/my/app/media; # your Django project's media files - amend as required } location /static { alias /path/to/my/app/static; # your Django project's static files - amend as required } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Note: before that, when I was using uwsgi, I ran the command ./manage.py collectstatic If … -
No module named 'mysite.settings'
I know this question has been asked quite a lot but all the solutions given do not seem to fit for me. I run this in a venv with python 3.6.8 and django 2.2.10 When I run django from cli it works and all functionality is working great so I know it is not django itself that is failing me. Path to wsgi script is "/opt/sites/aws/okta/wsgi.py" Actual wsgi.py: import os, sys sys.path.append('/opt/sites/aws') #path = os.path.dirname(os.path.dirname(os.path.abspath(file))) #sys.path.append(path) print(sys.path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "okta.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() When running python to see what errors it gives I get ModuleNotFoundError: No module named 'okta.settings' I get the same error when running apache with debug logging. I have quadruple checked the path and the environment variables and they are set right in the wsgi.py script. Please help! Thank You, -Chris -
anonymus user data storing related issue related help in Django
i need help for catching the guest user data. in my Django project for example ... i have a site which have an booking form .and also anyone must be signup for using it . but i like to that any interested user can submit the form before signup and after signup . but who submit the form before signup then he got an signup page after submit the form . and the user complete the signup process and then this user submitted data, can show the user dashboard. more example guest user submit data > Next > login/signup > show the submitted data on dashboard it is an session related issue . but i can not successfully. need help for that . thanks an advance -
Trouble implementing Voting to a Django File Upload project
I'm new to programming and have been following along Vitor Freitas' Django File Upload Project. I was able to complete the project, but now I want to add a vote function to the project that takes one of three choices ['Aye', 'Nay', 'Abstain'] on the uploaded file. I'm just not sure if what I want is possible. After uploading the file using forms.py from django import forms from .models import Leg class LegForm(forms.ModelForm): class Meta: model = Leg fields = ('title', 'ministry', 'pdf', 'cast','votes') widgets = { 'cast': forms.HiddenInput(), 'votes': forms.HiddenInput() }# Hide cast and vote totals options when uploading file for review In views I can call the form and list it Views.py class LegListView(ListView): model = Leg template_name = 'class_leg_list.html' context_object_name = 'legs' class UploadLegView(CreateView): model = Leg fields = ('id','title', 'ministry', 'pdf',) #leave out (cast and votes )fields to hide in upload form success_url = reverse_lazy('class_leg_list') template_name = 'upload_leg.html' Html file: {% extends 'base.html' %} {% block content %} {% block content_header %} <h2>Legislation</h2> {% endblock %} <table class="table mb-0"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Ministry</th> <th>View</th> <th>Cast Vote</th> <!-- <th>Votes</th>--> </tr> </thead> <tbody> {% for leg in legs %} <tr> <td>{{ leg.id }}</td> <td>{{ leg.title }}</td> <td>{{ … -
Is there a way to set an expiration time for a Django cache lock?
I have a Django 3.1.3 server that uses Redis for its cache via django-redis 4.12.1. I know that cache locks can generally be set via the following: with cache.lock('my_cache_lock_key'): # Execute some logic here, such as: cache.set('some_key', 'Hello world', 3000) Generally, the cache lock releases when the with block completes execution. However, I have some custom logic in my code that sometimes does not release the cache lock (which is fine for my own reasons). My question: is there a way to set a timeout value for Django cache locks, much in the same way as you can set timeouts for setting cache values (cache.set('some_key', 'Hello world', 3000))? -
Django field with multiple model option
I have a scenario where I have a model "Thread". There are two fields in it. "Sender" and "receiver". Also there are other models like "Teacher", "Student", "Principal" etc. Now in the "Thread" model, the sender can be a "Student", and receiver can be a "Teacher" OR Vice Versa. What is the solution for that: class Thread(models.Model): sender = models.(???) # can't be a student relation because a sender can be a teacher too receiver = models.(???) # same here. Is there any way that I can dynamically first select the model and then pick an object of that list. I have seen this functionality in Odoo. But is there anything in Django? -
Why list index in Django Template it's not in the output?
I use this in the template {% for num in '0123456789'|make_list %} <li>{{ respuesta.num }}: {{ puntaje.num }} </li> But then, the page only shows something like this : : (and the rest goes on like that) Why it doesn't show the elements from the lists? If I only use {{num}} it prints the actual nums from the for iteration and if I use {{respuesta}} it shows the hole list. This happens without triggering any error message or anything else (and yes, there are elements in the list "respuesta" and "puntaje"). -
(Django App) Django-Microsoft-Auth - Please enter the correct username and password
I have been trying to set up this app, but I am a stuck on step 10 in the usage documentation: Start site and go to /admin and logout if you are logged in. Login as Microsoft/Office 365/Xbox Live user. It will fail. This will automatically create your new user. Login as a Password user with access to change user accounts. Go to Admin -> Users and edit your Microsoft user to have any permissions you want as you normally. Am I supposed to create this user using py .\manage.py createsuperuser? I created a user with that program (Only username and password, no email), but the /admin page says the following when I attempt to log in with these credentials: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive" Before I sent the login form, I had the HTTP logs open in Chrome. When I sent the login form, the server responded with 200. I triple checked that my caps-lock key was not the problem, and I changed the HTML so I can see the password I was putting in. Am I missing something? Am I supposed to be using a …