Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am creating a simple website with 3 pages but i keep getting an erro. ModuleNotFoundError: No module named 'HomePage'
I cannot figure out why I keep getting the ModuleNotFoundError: No module named 'HomePage' error I'm fairly new to Django but have spent a majority of the day trying to figure out how to make a homepage where I could link a Homepage.html and have a different page on my original page. Any help would be appreciated this is my second question ever on here please be gentle. Below is the full error am getting. PS C:\Users\admin\Desktop\InstitutionFinderWebsite> python manage.py runserver; Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\python\python3.10.0\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\python\python3.10.0\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site- packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File"C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site- packages\django\core\management_init_.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\python\python3.10.0\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, … -
How can I check if the current request is from htmx
I'm using Django, Is there a way to check if the current request is from HTMX -
python coverage - specify the working directory
I have a django application called edison with multiple django-apps in it. I run tests on them using coverage: coverage run --source='.' edison/manage.py test application_one coverage run --source='.' edison/manage.py test application_two ... My repo structure is: -- edison [the repo name] -- edison [a django application] -- schuedled_jobs -- internal_packages In my tests files I import stuff from internal_packages directory and when I run the coverage commands i get the error ModuleNotFoundError: No module named 'internal_packages'. My question is: how do I change the working directory of coverage to be the root directory - so it will recognise all modules? -
Django static files to AWS S3 return 403 forbidden
I'm working on a Django(3) project which is deployed at Heroku. I'm trying to connect AWS S3 using Django Storages to upload Static and Media files to S3 Bucket. Note: I have googled a lot and tried every solution I found, but nothing solved my issue, so don't mark this as duplicate, please! I have created an S3 bucket with the Public access enabled and added the following CORS configuration: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Also, created an IAM user with programmatic access and gives the permission as S3FullAccess And here's what I have in **settings.py** AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = False AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-1' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' If I open files from the bucket directly I can see the file in the browser, but when I load my site (pythonist.org) these files return with 403 forbidden Here's the response from browser's Network tab for a file: Summary URL: https://s3.amazonaws.com/pythonist.org/css/normalize.css Status: 403 Forbidden Source: Network Initiator: pythonist.org:18 Don't know what's wrong here, Thanks in advance! -
coverage.misc.NoSource: No source for code: '/usr/src/server/rep-1>'
I am using the coverage package for quite a while now and it functioned well until yesterday it just fails at the level of generating a report I believe. There were no changes on how the functionality which is way more bizarre. I have the below coveragerc file: [run] source = . branch = True concurrency = multiprocessing omit = manage.py config/asgi.py config/wsgi.py config/settings.py */migrations/* *test* [report] show_missing = True skip_covered = True and Django manage.py file is as the following: import os import sys COVERAGE_ACCCEPTANCE = 85 def main(): argv = sys.argv try: command = argv[1] except IndexError: command = "help" default_settings = "config.settings" running_tests = (command == "test") if running_tests: default_settings = "config.settings_test" from coverage import Coverage cov = Coverage() cov.erase() cov.start() os.environ.setdefault("DJANGO_SETTINGS_MODULE", default_settings) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?", ) from exc execute_from_command_line(argv) if running_tests: cov.stop() cov.save() cov.combine() if round(cov.report()) < COVERAGE_ACCCEPTANCE: sys.exit(1) cov.erase() if __name__ == "__main__": main() After the tests are run successfully, the coverage raises the below error: Ran 317 tests in 96.790s OK … -
DjangoCKEditor Configuration Fully Enabled
I am using djangocms-text-ckeditor on a couple of my sites. On one of them, I have the following in base.py CKEDITOR_SETTINGS = { 'language': '{{ language }}', 'toolbar': 'full', 'toolbar_HTMLField': [ ['Undo', 'Redo'], ['ShowBlocks'], ['Format', 'Styles'], ], 'skin': 'moono-lisa', 'removePlugins': ['image'], 'extraPlugins' : [ # these are non-standard plugins 'codesnippet', 'html5audio', 'image2', 'autogrow', ], } This provides the following editor toolbar On another site, I have not added anything into base.py and get this My question is how I can get the CMSPlugins section in the first site. Also, what should a config look like if I want all plugins enabled explicitly? -
Editing many_to_many fields in admin_panel __init__() takes 13 positional arguments but 14 were given
I was looking for a way to edit, display and delete when using M2M fields in the admin panel. based How To Edit ManyToManyField In Django Admin list Display Page? . When adapting to my project, I encounter the error init() takes 13 positional arguments but 14 were given app.admin class app.admin class ReceptChangeList(ChangeList): def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin): super(ReceptChangeList, self).__init__(request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin) # these need to be defined here, and not in MovieAdmin self.list_display = ['action_checkbox', 'name', 'ingredient'] self.list_display_links = ['name'] self.list_editable = ['ingredient'] @admin.register(Recept) class ReceptAdmin(admin.ModelAdmin): #list_display = ('author','name','description',) def get_changelist(self, request, **kwargs): return ReceptChangeList def get_changelist_form(self, request, **kwargs): return ReceptChangeListForm app.forms from django import forms from api.models import Ingredient class ReceptChangeListForm(forms.ModelForm): ingredient = forms.ModelMultipleChoiceField( queryset=Ingredient.objects.all(), required=False) -
django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments
I cannot register a new user due to below error: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uid64': 'Mjk', 'token': 'aydhbh-1b0354ce0dd3df37193a6f22e95b0c4e'}' not found. 1 pattern(s) tried: ['account/activate/(?P<uidb64>[-a-zA-Z0-9_]+)/(?P<token>[-a-zA-Z0-9_]+)/$'] urls.py: urlpatterns = [ path('register/', views.account_register, name='register'), path('activate/<slug:uidb64>/<slug:token>/', views.account_activate, name='activate'), # User dashboard path('dashboard/', views.dashboard, name='dashboard'), ] views.py: def account_register(request): if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False user.save() # Setup email current_site = get_current_site(request) subject = 'Active your account' message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('Registered successfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_encode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') account_activation_email.html: {% autoescape off %} Hi {{ user.user_name }}, Your account has been successfully created. Please click below link to activate your account. http://{{ domain }}{% url 'account:activate' uid64=uid token=token %} {% endautoescape %} A new user is registered to a DB but as you can see there an error error image Do you … -
django tag { % block content % } isn't working
so i just started learning django, i understand the basic tag blocks but it didn't works well on my page. i have page called index.html and question.html i write like this in index.html <body> <div> <div> sum content </div> <div> { % block content % } { % endblock % } </div> </div> </body> and like this in question.html : { % extends 'index.html' % } { % block content % } <<my content>> { % endblock % } but the content in question.html didn't show up in index.html. i've checked my setting and didn't have django-stub like in other case. and if you want to know the structure, it goes like : djangoProject1 >djangoProject1 >myweb >static >templates -index.html -question.html Thank you in advance! -
Add attribute to admin model Django
I'm trying to add an attribute to my user admin model, but it doesn't work, here is what I succeded to do (I want to add inactivity field): from django.contrib import admin from .models import User class usersAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'inactivity') admin.site.register(User, usersAdmin) Here is my model code: class User(models.Model): username = models.TextField(max_length=140, default='uid', primary_key=True) first_name = models.TextField(max_length=140, default='cn') last_name = models.TextField(max_length=140, default='givenName') inactivity = models.IntegerField(default=500) def _str_(self): return self The error occurs when I'm trying to access to my added field from my views: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) data['username'] = self.user.username data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name data['inactivity'] = self.user.inactivity print(self.user) return data the error says: Traceback (most recent call last): File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post serializer.is_valid(raise_exception=True) … -
Updating FileField Or ImageField In Django, Django-Ninja?
enter image description here How can I assign The New Image In The ImageField ????? -
How to get current user in models.py?
I have a model like this class Orders(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) The logic is the companies to send offers to get the specific travel. When you send an offer you will not have access to that travel anymore untill the base company accept or reject your offer. So when the specific company logged in I want to show them if they sent an offer or not. The company name is saved in the user that is logged in. What I tried to do is this class Order(models.Model): @property def has_sent_offer(self): Offer.objects.filter(order=self.pk, company=request.user.company) But in the models.py I don't have access to request.user -
Django - How do you email a completed create view form
I'm working on a property management app where users can fill out an online application for a property. I want to set it up so when someone fills out an application the form gets emailed to the admin formatted with the form labels. Is there a way to email an entire formatted form with labels or am I going to have to make an email template and tag it according to how I want it to look? My example code: class ApplicationView(CreateView): redirect_field_name = '' form_class = ApplicantForm model = Applicant template_name = 'base/application.html' def form_valid(self, form): form.instance.created_by = self.request.user subject = 'New Application - {} {}'.format( form.cleaned_data.get('first_name'), form.cleaned_data.get('last_name'), ) message = '{} {}'.format( form.cleaned_data.get('first_name'), form.cleaned_data.get('last_name'), ) Application_Alert(subject, message) return super().form_valid(form) -
django CSRF_TRUSTED_ORIGINS not working as expected
Im having trouble in understanding why a post from a third party site is being rejected even though the site is added to CSRF_TRUSTED_ORIGINS list in settings.py. Im receiving a 403 error after the post stating the the csrf check has failed. I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site exempt from csrf checks. Is there something else I should have done in order to receive post requests from external origins? Im running django 3.2 CSRF_TRUSTED_ORIGINS = ['site.lv'] request headers: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,lv;q=0.8,ru;q=0.7 Cache-Control: no-cache Connection: keep-alive Content-Length: 899 Content-Type: application/x-www-form-urlencoded Host: cvcentrs-staging.herokuapp.com Origin: https://www.site.lv Pragma: no-cache Referer: https://www.site.lv/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: cross-site Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62 -
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket
I was following this tutorial : link This is the google cloud version i used : (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud --version Google Cloud SDK 367.0.0 bq 2.0.72 core 2021.12.10 gsutil 5.5 During the deploy process I was getting the following error: (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud app deploy Initializing App Engine resources...failed. ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket. I've searched from various sources and they suggest running this: gcloud config set app/use_deprecated_preparation True But when I run the error appears: (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud config set app/use_deprecated_preparation True ERROR: (gcloud.config.set) Section [app] has no property [use_deprecated_preparation]. I running it in the project directory folder. Can anyone help me? -
Why this search doesn't work for another entry but CSS?
So I'm currently working for Harvard CS50 Project1:Wiki and I have a difficulty for this project. In my search box, it doesn't want to direct to that particular entry instead it takes me to search.html file. But when I typed CSS in the search box, it takes me to CSS entry page. Can you guys help to mend this? Thank you, here's the code I use. If it doesn't tell you enough, feel free to ask the rest of the code! Oh and by the way I use Django for this one. def search(request): if request.method == 'GET': input = request.GET.get('q') html = convert_to_HTML(input) entries = util.list_entries() search_pages = [] for entry in entries: if input.upper() in entry.upper(): search_pages.append(entry) for entry in entries: if input.upper() == entry.upper(): return render(request, "encyclopedia/entry.html", { "entry" : html, "entryTitle" : input }) elif search_pages != []: return render(request, "encyclopedia/search.html", { "entries" : search_pages }) else: return render(request, "encyclopedia/nonexistingpage.html", { "entryTitle" : input }) -
Django DRF - Sending email with html template - html template appears as plain text
I'm trying to send emails from django using a html template. It does send the email but the html is sent as plain text. How can I make the email appear as html to the receiver? I'm using Django 4.0 views.py # import file with html content html_version = 'activate_email.html' html_message = render_to_string(html_version, {'context': context }) email = EmailMessage( 'Website email verification', html_message, 'info@example.co', [user.email], ) email.send() activate_email.html {% autoescape off %} <h1>Test</h1> {% endautoescape %} -
Extract error message from django html and display in console
In debug mode, and when exceptions are not being handled, django sends a typical error in html format, is it possible in any way to capture the error message from the html to be able to print it on the console? For example, the error is: in JS, do something like: console.log(error.message) and print out: CUDA out of memory. Tried to allocate 3.14 GiB (GPU 0; 9.78 GiB total capacity; 4.28 GiB already allocated; 2.89 GiB free; 5.57 GiB reserved in total by PyTorch) -
How To Create An Article Parser Loop With Apscheduler in Django
I have a script in Django that helps me parse RSS feeds for my own daily consumption. It gets the jobs done so far. Its made 3 models: class Categories(models.Model): category_name = models.CharField(max_length=50, verbose_name='Categories') ''' Categories = ['Business', Sports, Politics, Tech] ''' class FeedSource(models.Model): feed_url = models.URLField(verbose_name='RSS Feed Link') ''' FeedSource = ['http://rss.cnn.com/rss/edition.rss', ''https://www.espn.com/espn/rss/news, 'http://rss.politico.com/politics.xml'] ''' class Posts(models.Model): ... source = models.ForeignKey(FeedSource, on_delete=models.CASCADE, verbose_name='Source') category = models.ForeignKey(Categories, on_delete=models.CASCADE, verbose_name='Category') The Apscheduler command is as follows. As you can see, there is a bit of repetition in the fetch_articles functions that parse different links because each link belongs to a different Feedsource & Category. The same applies to Handle function. Each fetch_articles function has its own scheduler. import logging from django.conf import settings from django.core.management.base import BaseCommand from apscheduler.schedulers.blocking import BlockingScheduler from django_apscheduler.jobstores import DjangoJobStore from Posts.models import Posts, FeedSource, Categories import time logger = logging.getLogger(__name__) def save_new_articles(feed, source_id, category_id): """Function that parses & saves new articles to DB""" ... if not Posts.objects.filter(guid=item.guid).exists(): post = Posts( ... guid = item.guid, source_id = selected_source_id category_id = selected_category_id ... ) post.save() def fetch_siteA_articles(): """Fetches news artices from siteA""" feed = feedparser.parse("siteA") source = FeedSource.objects.get(pk=1) source_id = int(source.pk) category = Categories.objects.get(pk=3) category_id = int(source.pk) … -
Django using a Query in a Query does not work
so I have this model : class Student(models.Model): id = models.AutoField(primary_key=True) first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) title=models.CharField(max_length=30,default="",blank=True) tel=models.CharField(max_length=50,default="",blank=True) e_mail=models.CharField(max_length=50,default="",blank=True) social_media=models.CharField(max_length=50,default="",blank=True) social_media2=models.CharField(max_length=50,default="",blank=True) social_media3=models.CharField(max_length=50,default="",blank=True) street=models.CharField(max_length=50) postal=models.CharField(max_length=50) city=models.CharField(max_length=50) country=models.CharField(max_length=50) graduation_uni=models.DateField(null=True,default=None,blank=True) graduation_ikomt=models.DateField(null=True,default=None,blank=True) certificate_no=models.CharField(max_length=50,default="",blank=True) def __str__(self): return str(self.id) + " - " +self.first_name + " " + self.last_name class Course(models.Model): id = models.AutoField(primary_key=True) course=models.CharField(max_length=50) description=models.CharField(max_length=50,null=True,default=None,blank=True) start_date=models.DateField(null=True,default=None,blank=True) end_date=models.DateField(null=True,default=None,blank=True) def __str__(self): return str(self.id) + " - " +self.course + " | " + self.start_date.strftime("%d.%m.%y") + " - " + self.end_date.strftime("%d.%m.%y") class StudentInCourse(models.Model): StudentId = models.ForeignKey(Student, on_delete=models.CASCADE) CourseId = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return str(Student.objects.get(id=self.StudentId.id)) + " in " + str(Course.objects.get(id=self.CourseId.id)) And I'd like to Display only the Students in a specific course using Queries like this (in my views.py): students_in_course=StudentInCourse.objects.filter(CourseId=id) latest_student_list = Student.objects.filter(id__in=students_in_course) Sadly, I only get an empty result. Any Ideas what I'm doing wrong? I thought with the Primary/Foreign Key relation the Filter should just work this way? Any advice will be appreciated. Greetings -
How to use variable to get attributes of another another variable in Django templates
I am trying to populate a CSS grid in a Django template with specified columns and rows. To my best understanding, I need to do something like “nested variables” in the Django template to achieve what I’m looking for. I tried this, but it does not work: {% for parent_row in parent_rows %} {{ parent_row }} <div>p1</div> <div>p2</div> {% for child_row in children_rows %} <div> {{ child_row}} </div> {% for guy in guys %} <input type=”text” value=”{{guy}}.{{child_row}}”></input> {% endfor %} {% endfor %} {% endfor %} The {{guy}}.{{child_row}} neither some of the similar variants I tried do not work. I manage to get the result I'm looking for by just writing the whole HTML open, and then by looping through each guy on separate rows, as I can use for example guy.name to get the desired value to each row, but this means lots of repetition. parent_rows could look something like this for example: “names”, “contact_information”, “hobbies” children_rows could look something like this for example: “forename”, “family_name”, “phone_number”, “mail”, “favourite_hobby” and two records in the guys would be like this (both identical, to ease illustration): “forename”: “Mike” “family_name”: “McMediocre” “phone_number”: “123” “mail”: “mike@mediocre.com” “favourite_hobby”: “tennis” I am trying to populate … -
Django custom model manager for derived class - filtering on base class attribute
I am using Django 3.2 I have the following models: class AuthoriseableApprovedManager(models.Manager): def get_queryset(self): return super(AuthoriseablePendingManager, self).get_queryset().filter(computed_status=AUTHORISATION_STATUS_APPROVED) class Authorisable(models.Model): # various fields ... approved_objects = AuthoriseableApprovedManager() class ApprovedPublishedArticlesManager(models.Manager): def get_queryset(self): return self.approved_objects.filter(is_published=True) class Article(Authorisable, # Other base classes ): # various fields # .... objects = models.Manager() # The default manager. approved_published_articles = ApprovedPublishedArticlesManager() class Meta: ordering = ('-created_at', ) I have the following code in my views.py class ArticleListView(ListView): model = Article def get_queryset(self): return self.model.approved_published_articles.all() # <- Barfs here ... I get the error message: 'ApprovedPublishedArticlesManager' object has no attribute 'approved_objects' Which makes sense, since ApprovedPublishedArticlesManager does not derive from Authorisable. How do I create a custom manager that allows me to filter based on base class properties - does my custom manager have to derive from models.Manager and the relevant base class (Authorisable in this case)? -
Django app is crashing Chrome browser on Android
I have hosted a Django app on pythonanywhere.com . It works fine on desktop but crashes Chrome on Android. It works fine on another Android browsers and Safari too. It just a simple Django application with a single html page. One thing I found out was, it crashes only when I turn on 'Forced HTTPS' on pythonanywhere. If I turn it off it works fine. It's the bug with only this app. My other hosted apps works fine. Hosted app: https://shantanu2k17.pythonanywhere.com/ CAUTION : don't open it on Android chrome, your browser will crash. Open it in incognito mode instead. Code : https://github.com/Shantanu2k19/testing2.git Please help me find the bug. -
Django DRF - Send email with html template - django.template.exceptions.TemplateDoesNotExist
I've added sending emails in my Django project and now I want to use html templates for the content of these emails. I've created a templates folder and put my template in there. Then I added the template path to TEMPLATES in settings.py. (See code below) But now I'm getting the following error. django.template.exceptions.TemplateDoesNotExist: activate_email.html Even though the template exists: views.py # import file with html content html_version = 'activate_email.html' # 'templates/activate_email.html' also doesn't work html_message = render_to_string(html_version, {'context': context, }) email = EmailMessage( 'MySubject', html_message, 'info@example.co', [user.email], ) email.send() settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'django_backend/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Can anyone point me in the right direction what I'm doing wrong? I'm using Django 4.0 and DRF 3.13.1 -
Bootstrap 5 get rid of big number input fields
I have a table that can be used as a form, which all quite works well, but I do not manage to reduce the space a number input takes: here is a view from when it is not a form: What argument can I put in th class or td so the green areas get minimized? Fixed width in pixels would be an option (is this possible?). I already tried <th class="w-25"> or <td class="w-25"> (and both). I achieved adding a class="w-50" argument to the number input fields, so this seems to work. <table class="table table-striped table-hover"> <thead class="thead-dark"> <tr> {% for col in header %} {% if col == "number" %} <th>{{ col }}</th> {% else %} <th>{{ col }}</th> {% endif %} {% endfor %} <th class="text-end">action</th> </tr> </thead> <tbody id="table"> <tr> {% for key, value in product.data.items %} <td>{{ value }}</td> {% endfor %} </tr> </tbody> </table>