Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the foreign key value into href attribute of a hyperlink element as a url parameter in Django template
I have data table showing list of vehicles from the Vehicle model with Driver column. When user clicking on the Driver column value, I want to redirect the user to driver detail page url driver-detail/license_number. I tried to pass the license_number to href attribute of hyperlink element like href="{% url 'driver-detail' vehicle.driver.license_number %}". This does not help me, it's always empty. If I omit the license_number in the href value it will pass the __str__(self) return value of the Driver model, which is combination of license_number and fullname. If I change the return value of __str__(self) in the Driver model it will work. But I don't want to change the return value of __str__(self). Any help is much appreciated! Model.py class Driver(models.Model): license_number = models.CharField(primary_key=True, max_length=50) fullname = models.CharField(max_length=25) license_issue_date = models.DateField("Issued Date") def __str__(self): return self.license_number + " " + self.fullname class **Vehicle**(models.Model): license_plate = models.CharField(max_length=25, primary_key=True) model = models.CharField(max_length=100, verbose_name="Vehicle model") driver = models.ForeignKey(Driver,on_delete=models.SET_NULL,null=True, blank=True) template.html <a href="{% url 'driver-detail' vehicle.driver.license_number %}" > {{vehicle.driver.license_number}}{{vehicle.driver.fullname}} </a> urls.py urlpatterns = [ path('driver-detail/<str:pk>/', views.driverDetail, name='driver-detail'), ] -
Celery and Celery beat wit django after running in docker container running some job
I am trying to run django celery and celery beat after i start celery and celery beat this process is running every second is this normal celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.478374+05:30) celery-1 | [2024-03-10 16:08:11,479: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Running job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" (scheduled at 2024-03-10 16:08:11.766830+05:30) celery-beat-1 | [2024-03-10 16:08:11,767: INFO/MainProcess] Job "EventPublisher.send_events (trigger: interval[0:00:01], next run at: 2024-03-10 16:08:12 IST)" executed successfully I tried clearing redis db also tried uninstalling and installing redis,celery -
Django PasswordResetView not working properly with app_name causing DisallowedRedirect
I'm encountering an issue with Django's built-in password reset functionality within my project. Specifically, I have an app named 'user' and I've defined the app_name variable in my urls.py as app_name = 'user'. However, this seems to be causing problems with Django's password reset views. Initially, I encountered the "Reverse for 'url name' not found" error when using auth_views.PasswordResetView. To address this, I tried setting the success_url parameter to 'user:password_reset_done' and providing a custom email_template_name. However, now I'm facing a new issue where the debugger is raising a DisallowedRedirect exception with the message "Unsafe redirect to URL with protocol 'user'" when attempting to access the password reset functionality. This occurs during the execution of django.contrib.auth.views.PasswordResetView. the error is: Unsafe redirect to URL with protocol 'user' Request Method: POST Request URL: http://127.0.0.1:8000/accounts/reset_password/ Django Version: 5.0.2 Exception Type: DisallowedRedirect Exception Value: Unsafe redirect to URL with protocol 'user' Raised during: django.contrib.auth.views.PasswordResetView Here's a summary of my setup: urls.py (within the 'user' app): from django.urls import path from django.contrib.auth import views as auth_views app_name = 'user' urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name='registration/reset_password.html', success_url='user:password_reset_done', email_template_name='registration/password_reset_email.html'), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] registration/reset_password.html: {% block content %} <h1>Password reset</h1> <p>Forgotten your … -
creating migrations in Django [closed]
I was following a YouTube video guide on django, and I ran into a problem when after filling out the file models.py I went to cmd and wrote python manage.py makemigrations, but instead of the created file in the migrations directory, I was met with a long error. This is my first experience with django and no migrations have been created before. The code models.py - ` from django.db import models class Articles (models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('Announcement', max_length=250) full_text = models.TextField('Article') date = models.DateTimeField('Publication date') def __str__(self): return self.title` ` error - `C:\Users\глеб\Desktop\pip\books> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\глеб\Desktop\pip\books\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 16, in cached_import return getattr(module, class_name) AttributeError: module 'django.db.models' has no attribute 'Bi gAutoField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\db\models\options.py", line 275, in _get_default_pk_class pk_class = import_string(pk_class_path) File "C:\Users\глеб\AppData\Local\Programs\Python\Python38-32\lib\site-package s\django\utils\module_loading.py", line 32, in import_string raise ImportError( ImportError: Module "django.db.models" does not define a "Bi gAutoField" attribu te/class The above exception … -
Creating a model through the admin panel inside the test
I'm new to Python. I'm trying to create a test that will create an item inside the admin panel, but when I run the test I get: AssertionError: False is not true. Help me please class ItemAdminTest(TestCase): serialized_rollback = True def setUp(self): self.client = Client() self.user = User.objects.create_superuser(email='admin@example.com', password='admin') def test_create_item_admin(self): self.client.login(email='admin@example.com', password='admin') response = self.client.post('/admin/product/item/add/', { 'title': 'Test Item', 'description': 'Test Description', 'price': 10.00, 'code': 123456, 'color': 'Red', 'weight': 1.5, 'height': 10.0, 'width': 5.5, 'types': ["КБТ", "МБТ"], 'amount': 5, }) self.assertTrue(Item.objects.filter(title='Test Item').exists()) At the same time, I am absolutely sure that a superuser is created and authorization is successful, but for some reason the item itself is not created. -
Invalid credentials even putting right credentails django
I have created a sign in form for my user and when I’m trying to log in it says invalid student_ID or password even though I put my credentials properly I’m using postgresql via Railway I’m a beginner (https://i.stack.imgur.com/iRQcJ.png) This is my forms.py from django import forms from django.forms import ModelForm from .models import StudentInfo class StudentInfoForm(forms.ModelForm): class Meta: model = StudentInfo fields = ['student_id', 'firstname', 'lastname', 'middlename', 'course','year', 'section', 'password', 'confirm_password',] widgets = { 'password': forms.PasswordInput(), 'confirm_password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'].required = True self.fields['firstname'].required = True self.fields['lastname'].required = True self.fields['course'].required = True self.fields['section'].required = True self.fields['password'].required = True self.fields['confirm_password'].required = True class SignInForm(forms.Form): student_id = forms.CharField(label='Student ID', max_length=10) password = forms.CharField(label='Password', widget=forms.PasswordInput) This is my models.py from django.db import models from django.contrib.auth.hashers import make_password # Create your models here. class StudentInfo(models.Model): student_id = models.CharField(max_length=10, unique=True, primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) middlename = models.CharField(max_length=100, blank=True, null=True) course = models.CharField(max_length=100) year = models.CharField(max_length=1) section = models.CharField(max_length=1) password = models.CharField(max_length=128, null=True) confirm_password = models.CharField(max_length=128, null=True) def __str__(self): return f"{self.firstname} {self.lastname}" def save(self, *args, **kwargs): self.password = make_password(self.password) super(StudentInfo, self).save(*args, **kwargs) This is my urls.py from django.urls import path from . import views urlpatterns = [ … -
how to make a django model with no id column and primary key?
i am working with big data and i can have an extra column like id. i cant put the primary key to any other single column, because of duplicate. and even more i cant have primary key on two column or more because my data is not unique. so the only way to get rid of the id column with a primary key left for me is to stop django making it! and i don't know how... i tried to edit the operation part of the migration file before doing the migrate command but it didn't work. even if i delete the id column in the migration file it still make it /:(. -
Query using reverse relationship or objects manager?
from .models import Comment user = request.user comments_1 = user.comment_set.all().count() comments_2 = Comment.objects.filter(user=user).count() Between comments_1 and comments_2, which one is faster? Can someone explain to me? Any help will be greatly appreciated. Thank you very much. I looked in Django Documentation Making queries, but does not really say about the difference in performance. -
Django - Redirection to Strava API Auth Page is not working
So I'm Trying to redirect my django web app after the user submitted the form AND if the user chose 'Strava Link' Option from the form. What I'm currently doing is to open Strava's API Authorization Page for code/token exchange so my app will fetch the data from user's Strava account. My current problem is that it does not redirect to my Strava API's Authorization page (No Error, nothing) and I tried printing the Authorization URL so I can debug it. I Tried Manually opening the Authorization URL and It is working. I've watched some Strava API tutorials using python and all of them manually enters the link to copy the code after the user clicked 'Authorized'. Is My method correct? Form Submission -> Redirect the user to Strava's API Authorization Page (stuck on this step) -> Callback to return the code/token -> Fetch the data Here's my current code innside views.py: async def index(request): if request.method == 'POST': #Start of process after Form Submitted try: data_dict = link_validation(request, data_dict) #Rest of the code Here (Irrelevant and not related to Strava API) except Exception as e: return render(request, 'index.html', {'error_message': str(e)}) else: return render(request, 'index.html') def link_validation(request, data_dict): redirect_to_strava_auth(request) #Rest … -
NextJs not setting the cookie from django csrf_token
My nextjs application integrated with django has an authentication system based on csrftoken and sessionid. Once the nextjs application runs, it makes a request to the backend for the csrf route, which automatically sets a cookie to the destination of the request. This works normally running locally. But when running nextjs in docker in the production environment you can see that the cookie is set in the response headers, but it does not actually create a cookie. I had seted CSRF_COOKIE_SAMESITE = None and SESSION_COOKIE_SAMESITE = None But still not setting the cookie, even in the headers showing the set cookie XHRGET https://api.viajahturismo.com.br/api/v1/csrf/ [HTTP/2 204 23ms] csrftoken expires "2025-03-09T00:38:39.000Z" path "/" samesite "None" value "8UayLGpyXUF0cc2AlM5zqBd4kdOHSfXf" csrftoken "8UayLGpyXUF0cc2AlM5zqBd4kdOHSfXf" My django setting: """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY … -
Error deploying Django project on Railway
I'm trying to deploy a Django project on Railway and I'm getting a runtime error saying "The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages." As far as I'm aware I've installed Apache but have probably missed something -
AWS ElasticBeanstalk container_commands: Commands trigger errors even if they were correct
I have a django project that I want to deploy with ElasticBeanstalk, I defined a [xxxx.config] file in .ebextensions, the content of the file is: xxxx.config container_commands: acvenv: command: "source /var/app/venv/*/bin/activate" migrate: command: "python /var/app/current/manage.py migrate" But the project doesn't deploy unless I remove xxxx.config. I follow the documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html What am I doing wrong? -
Django UpdateView not Updating
I have created a Django app that allows users to enter their stock trades, as a journaling tool. When a user clicks on an individual journal entry from the index page, they will be taken to a detail page showing all the information on that individual entry (single_entry.html). This page is handled by an UpdateView. From this page, a user can edit/update any info, as well as DELETE that specific entry. There are two buttons on the form, one for 'Delete' and another for 'Update'. The deleting works fine. The updating used to work, but now is not for some reason! Nothing updates in the Entry. Also I can't figure out why the 'messages' middleware is not being output to the screen. Same with all my print() statements, nothing is coming out on the console. Thanks for your help! Here's my views.py: from django.forms.models import BaseModelForm from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.views import View from django.contrib import messages from django.urls import reverse_lazy from .forms import EntryForm from .models import Entry from django.views.generic.edit import UpdateView, DeletionMixin from django.views.generic import DeleteView # Create your views here. class EntryView(View): def get(self, request): entries = Entry.objects.all().order_by("entered_date") form = … -
Data is not being returned to Django Template, Data Does Exist
I am having an issue not getting data to return to a template, but this is not happening with other models in the same template. I can properly submit data on another page to this data model (TechnicianLabor) via a form, but the data will not publish from my calls in the html, what am I missing?: models.py class TicketList(models.Model): identifier = models.AutoField(primary_key=True) name = models.CharField(max_length=150, null=True, blank=True) description = RichTextField(default="Add description for Ticket: ", null=True, blank=True) client = models.ForeignKey('ClientCompany', blank=True, null=True, on_delete=models.CASCADE) assignment = models.ManyToManyField(TechnicianUser, null=True, blank=True) create_date = models.DateField(auto_now_add=True) end_date = models.DateField(null=True, blank=True) due_date = models.DateField(null=True) class TechnicianLabor(models.Model): ticket = models.ForeignKey(TicketList, on_delete=models.CASCADE) minutes = models.BigIntegerField(default=0) is_tracked = models.BooleanField(default=False) created_by = models.ForeignKey(TechnicianUser, on_delete=models.DO_NOTHING) created_at = models.DateTimeField() views.py def apps_tickets_details_view(request, pk): tickets = TicketList.objects.get(pk=pk) projects = ProjectList.objects.filter(pk=tickets.project_id) labors = TechnicianLabor.objects.all() comments = TicketComment.objects.filter(ticket_id=tickets) comment_count = comments.count() technicians = TechnicianUser.objects.all() replies = TicketCommentReplies.objects.filter(ticket_id=tickets) context = {"tickets":tickets,"comments":comments,"projects":projects, "replies":replies, "technicians":technicians, "labors":labors, "comment_count":comment_count} if request.method == "POST": form = TicketListAddForm(request.POST or None,request.FILES or None, instance=tickets) if form.is_valid(): print(comments) form.save() messages.success(request,"Ticket Updates Successfully!") #return redirect("apps:tickets.list") return redirect(reverse("apps:tickets.details", kwargs={'pk':tickets.pk})) else: print(form.errors) messages.error(request,"Something went wrong!") return redirect("apps:tickets.list") #return redirect(reverse("apps:tickets.list", kwargs={'pk':tickets.pk})) return render(request,'apps/support-tickets/apps-tickets-details.html',context) html <h6 class="card-title mb-4 pb-2">Time Entries</h6> <div class="table-responsive table-card"> <table class="table align-middle mb-0"> <thead class="table-light … -
Deploying Django in PAAS (Clever-Cloud) / can't find my app
I am trying to deploy my django (5.0.3) in Clever cloud It can't locate my app on the server, although it works fine locally Here is my tree structure Here is my settings.py Here are my env variables in cleveer-cloud Here is the error : 2024-03-09T14:55:49+01:00 ModuleNotFoundError: No module named 'photos' What could be the root cause ? -
Django: The static tag not loading on extended html when linking an image but works for CSS style sheet?
I have a layout.html file as follows: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'app/styles.css' %}" rel="stylesheet"> </head> <body> {% block body %} {% endblock %} </body> </html> and a extended.html as follows: {% extends "layout.html" %} {% block body %} <div class="maincontainer"> <h1>Extended</h1> <img src="{% static 'app/images/image.svg' %}" alt="image"> </div> {% endblock %} When I load the exnteded.html I get the follwoing error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'static', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have tested a few scenarios out: If I remove the <img src="{% static 'app/images/image.svg' %}" alt="image"> from the extended.html the CSS style sheet loads perfectly. If I add {% load static %} to the extended.html the image and CSS style sheet both load. I have had a look at the Django docs and have ensured that the settings.py file does have django.contrib.staticfiles in INSTALLED_APPS and STATIC_URL = "static/". Am I missing something here? -
django-celery-beat loading task but celery worker not receiving it
I've been having these issues on my celery beat and worker where my celery beat creates task, but celery worker does not receive it . I am using elasticmq as the broker My celery beat logs docker exec -it app-1 celery -A app beat --loglevel info celery beat v5.3.6 (emerald-rush) is starting. __ - ... __ - _ LocalTime -> 2024-03-09 16:25:41 Configuration -> . broker -> sqs://user:**@sqs:9324// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2024-03-09 16:25:41,744: INFO/MainProcess] beat: Starting... [2024-03-09 16:25:41,821: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) [2024-03-09 16:25:51,782: INFO/MainProcess] Scheduler: Sending due task beat_task (app.tasks.beat_task) My celery worker log docker exec -it kole-app-api-app-1 celery -A app worker --loglevel info/usr/local/lib/python3.11/site-packages/celery/platforms.py:829: SecurityWarning: You're running the worker with superuser privileges: this isabsolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(SecurityWarning(ROOT_DISCOURAGED.format( -------------- celery@b4d9d70aafdc v5.3.6 (emerald-rush)--- ***** ------- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with 2024-03-09 16:26:10 *** --- * --- ** ---------- [config] ** ---------- .> app: app:0x7fd2fe122f90 ** ---------- .> transport: sqs://user:**@sqs:9324// ** ---------- .> results: disabled:// *** --- * --- .> concurrency: 6 (prefork)-- ******* ---- .> task … -
send data from javascript to django without sending request, post, get
I have a project is about web game, if the player end the game #e.g. bool state == false then it will send the score back to the django backend, but i don't want the player have to press the submit button, is there any ways to do that? i have no any complete idea, i just found some solution is about ajax, fetch api..., but i don't really know if those work or not. my post can't pass the quality standard, is that means my post's word too less? -
how to use django validation with bootstrap tab list
I am trying to use bootstraps tab list with django, Basically i have grouped my fields under several fieldsets in the modelform. in the html template i generate bs nav-pills and tab-control to show the fields. it renders fine. below is the code. However whenever the user leaves a required field empty in a tab which is not active and clicks submit, django cannot put the focus on the required field. the same form works fine without bs tabs. So is there a way for me to be able to use django validation or do I need to write my own js to loop through all required fields and set focus? ========= the model form ================ class PostSellTutorForm(forms.ModelForm): class Meta: model = SellTutor exclude = default_exclude + ['post'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fieldsets = [ ['Basics', {'comment': 'about the tutor', 'fields': ['english', 'languages', 'years_of_experience', 'primary_occupation', 'message']}], ['Cost', {'comment': 'tutor cost', 'fields': ['hourly_rate', 'free_trial', 'free_trial_hours']}], ] def get_fieldsets(self): return self.fieldsets ============ the render function =============== def render_post_form(request, template, form, title, post_id, post_type, partial_save): context = {} # context['fieldsets'] = form.Fieldsets.value context['form'] = PostSellTutorForm context['page_title'] = title return render(request, template, context) =========== the template ======================= {% load static %} <!-- … -
Django ModuleNotFoundError on Heroku Release
Similar to many previously stated issues yet unresolved in my case, I get a ModuleNotFoundError when deploying my Django project for release on Heroku, which works fine locally. I use Django 4.0 and Python 3.10.13. Heroku release log: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 454, in execute self.check() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/compatibility/django_4_0.py", line 9, in check_csrf_trusted_origins for origin in settings.CSRF_TRUSTED_ORIGINS: File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'opportunities.settings.heroku_staging' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 426, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/connection.py", line … -
Django i18n failing to catch strings in JS render functions
I'm using i18n to translate a Django project into various languages. Everything is nicely translated depending on locale, except for certain strings in JavaScript render functions. For example, if I run django-admin makemessages --all and django-admin makemessages -d djangojs --all, "Launch this app" and "App under review" from an HTML template don't show up in any of the django.po or djangojs.po files, despite being tagged with gettext(): <script> const renderStatus = () => { let launchApp = gettext("Launch this app"); document.getElementById("component-appLauncher").innerHTML = ` <span class="u-flex-grow-1" style="vertical-align: middle;">` + launchApp + `</span> <a href="#launch_this_app-modal"> <button style="btn--sm"> <i class="u-center fa-wrapper fa fa-solid fa-arrow-right-long"></i> </button> </a> `; let appReview = gettext("App under review"); document.getElementById("component-appStatus").style.color = "red"; document.getElementById("component-appStatus").innerHTML = appReview; } </script> Sometimes (though not consistently, and I can't reproduce this at will), one or the other .po file will have these lines (example from the Spanish translation), with no reference to the HTML template source file or line numbers: #~ msgid "Launch this app" #~ msgstr "Lanzar esta app" #~ msgid "App under review" #~ msgstr "App en estudio" This seems to be related to the cache because, after a lot of tab refreshes, the translation will suddenly appear (even though the mapping … -
How to add css_class to django ModelForm using crispy_forms
I have a ModelForm in django and I want to add desired classes to its fields using crispy_forms. this is my form: class ProductInventoryForm(ModelForm): class Meta: model = Product fields = ["sku", "regular_price", "sale_price", "stock_quantity"] def __init__(self, *args, **kwargs): super(ProductInventoryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field("sku", css_class="your-class"), Field("regular_price", css_class="another-class"), Field("sale_price", css_class="another-class"), Field("stock_quantity", css_class="another-class"), ) As you see I used init method and crispy helper and Layout, but it doesn't affect and no classes added to my form. -
Django FileField: File not uploading in media folder or sql database
I'm doing a e-learning portal using Django. The user 'teacher' should be able to upload files under any course. However, the files are not being upload in media/course_materials folder. When i check the sql database, there is no instance of the id being created when a file is upload (i tried both an image file and a word document file, both of very less storage). This is the debugging comment i get from views : " <MultiValueDict: {'course_materials': [<InMemoryUploadedFile: filematerial.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>]}>" models: class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField(default ="Description of Course") course_materials = models.ManyToManyField('CourseMaterial', blank=True) def __str__(self): return self.name class CourseMaterial(models.Model): name = models.CharField(max_length=255) file = models.FileField(upload_to='course_materials/') def __str__(self): return self.name views: def edit_course(request, course_id): course = get_object_or_404(Course, id=course_id) if request.method == 'POST': form = CourseForm(request.POST, request.FILES.get, instance=course) if form.is_valid(): print(request.FILES) course = form.save(commit=False) course.save() form.save_m2m() # Save many-to-many relationships return redirect('teacher') # Redirect to teacher dashboard after editing the course else: form = CourseForm(instance=course) context = { 'form': form, 'course': course, } return render(request, 'elearn/edit_course.html', context) forms.py: class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['name', 'description', 'course_materials'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['course_materials'].queryset = CourseMaterial.objects.none() html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> … -
Vue3 is fetching data from Django graphql but does not display the component on webpage?
While using Vue3 to fetch data from Django graphql backend, chrome console shows the fetched data as array: (3) [{…}, {…}, {…}] 0 : {__typename: 'PostType', title: 'That Bum.', subtitle: '', publishDate: '2023-12-14T19:23:09+00:00', published: false, …} 1 : {__typename: 'PostType', title: '"Fight Like a Girl!"', subtitle: '', publishDate: '2023-12-07T19:27:26+00:00', published: false, …} 2 : {__typename: 'PostType', title: 'Sunday Sermon', subtitle: '', publishDate: null, published: false, …} length : 3 but the component (AllPosts.vue) is not displayed on the webpage. Can you suggest a solution with description of the error and the solution? -
Nonexistent custom ModuleNotFound error for Django deployment on Apache24
The Problem I have a Django deployment with Apache24 that was working as expected previously, with the django project name being "API_Materials". However, when I tried to make new migrations with python manage.py makemigrations, a command that never had any problem before, I got the following stacktrace: (venv) C:\API\BD_API_Materials>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 453, in execute self.check() File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\core\checks\urls.py", line 36, in check_url_namespaces_unique if not getattr(settings, "ROOT_URLCONF", None): File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\Users\afonso.campos\Desktop\BD_API_Materials\API\venv\lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MaterialsAPI' The module that the project tried to use is …