Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to connect mysql and django in vscode virtual environment
If l try to run pip install mysqlclient in virtual environment l get this pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\lib\mariadb', 'C:/mariadb-connector\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\include\mariadb', 'C:/mariadb-connector\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running egg_info writing src\mysqlclient.egg-info\PKG-INFO writing dependency_links to src\mysqlclient.egg-info\dependency_links.txt writing top-level names to src\mysqlclient.egg-info\top_level.txt reading manifest file 'src\mysqlclient.egg-info\SOURCES.txt' reading manifest … -
Please how I do fix [ModuleNotFoundError: No module named 'config.settings']?
I have already installed pip requests, installed config file but it keeps showing the same thing.I even created a new virtual world and a new project but anytime I run "python manage.py runserver" or "python manage.py migrate" it keeps tell me (ModuleNotFoundError: No module named 'config.settings'). pip install requests -
foreign key daterange filtering in django admin
for a hotel booking system using django admin, I'd like to filter the rooms available for a given date range, models are as follow class Room(models.Model): id = models.AutoField(primary_key=True) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) class Booking(models.Model): id = models.AutoField(primary_key=True) start_date = models.DateField(verbose_name=_("Start date")) end_date = models.DateField(verbose_name=_("End date")) room = models.ForeignKey(Room, on_delete=models.CASCADE) how can I filter the rooms in the admin so I can pick a date range and return only the rooms that have no bookings on the select range? thanks a lot -
Set Boolean value in hidden input
I have a form that lets users send new product to database, But I want to be able to review them before sending them, So I want to set a Boolean input the the form so when User sends new product they wait in admin panel for review and after reviewing them admin can change the Boolean field and the product is published. I made a hidden field in form and I want to give it the default value. now no matter what I did, I cannot make the form to submit with the hidden boolean field value forms.py : class AccountProductForm(ModelForm): class Meta: model = AccountProduct fields = ('name','price','description','image','is_agahi') labels = { 'name': '', 'price': '', 'description': '', 'image': '', } widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'price' : forms.NumberInput(attrs={'class': 'form-control'}), 'description' : forms.Textarea(attrs={'class': 'form-control'}), 'image' : forms.FileInput(attrs={'class': 'form-control'}), 'is_agahi' : forms.HiddenInput(), def __init__(self, *args, **kwargs): self._user = kwargs.pop('account_owner') super(AccountProductForm, self).__init__(*args, **kwargs) def save(self, commit=True): inst = super(AccountProductForm, self).save(commit=False) inst.account_owner = self._user if commit: inst.save() self.save_m2m() return inst views.py def sell_account(request): submitted = False if request.method == 'POST': form = AccountProductForm(request.POST, request.FILES, account_owner=request.user) if form.is_valid(): form.save() messages.success(request, 'Product Sent') else: form = AccountProductForm(account_owner=request.user) if 'submitted' in request.GET: submitted … -
TypeError: DatabaseWrapper.display_name() takes 0 positional arguments but 1 was given
I am getting the following error when running "python manage.py migrate" in cpanel terminal. I am using mysql for database. The library that I am using is mysql-connector-python. TypeError: DatabaseWrapper.display_name() takes 0 positional arguments but 1 was given The following are the settings of my settings file: DATABASES = { "default": { "ENGINE": "mysql.connector.django", "NAME": "my-database-name", "HOST": "localhost", "PORT": "3306", "USER": "my-database-username", "PASSWORD": "my-password", } } -
Django for loop with parentheses for zip command
In Python this code works mylist1 = ["peru", "germany", "japan"] mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]] mylist3 = [[1,2], [3,4], [5]] for country, (cities, numbers) in zip(mylist1, zip(mylist2, mylist3)): print(country) for city, number in zip(cities, numbers): print(city) print(number) I'm able to print what I want: peru lima 1 cusco 2 germany berlin 3 munich 4 japan tokyo 5 However in Django I have an issue with the parenthesis. In views.py I can set mylist=zip(mylist1, zip(mylist2, mylist3)), so I will have {% for country, (cities, numbers) in mylist %}: print(country) {% for city, number in zip(cities, numbers) %}: print(city) print(number) The first for loop is where I'm stuck. what should I do to use (cities,numbers). I think parenthesis is not accepted. python approach doesn't work -
Offcanvas dismiss button does not work when instance initialised via Javascript
I have offcanvas as part of the page layout. It does not show by default, but I want it to always show on large screens. On small screens it should have a button to dismiss it. Another button to show the offcanvas is placed on the menu panel underneath it. I'm using JavaScript on page load and on page resize to show the offcanvas when if screen is large. If the user then scales the screen down, the offcanvas should remain visible until dismissed. The issue is that the dismiss button works on the offcanvas only if it has not been initialised via JS. I.e. if opened on a small screen, the offcanvas is not visible and the two bottons can be used to toggle back and forth. But once the offcanvas has been triggerd via JS on a large screen, the dismiss button no longer works when the screen is downsized. I'm struggling to figure out if it has lost an EventListener and how to add it back, if so. Layout: <!-- Button to show offcanvas (positioned underneath it) --> <div> <button class="btn" type="button" id="off-canvas-body-toggle" data-bs-toggle="offcanvas" data-bs-target="#floating-menu"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#422543" class="bi bi-arrow-bar-right" viewBox="0 0 16 16"><path fill-rule="evenodd" … -
Why is this react-django app not rendering anything
my App.js is in appname/src/components : import React, { Component } from "react"; import { render } from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <h1>This is the App.js</h1> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); My index.js in appname/src: import { App } from "./components/App"; why is the server not rendering anything? see my templates app name index.html in appname/templates/appname seems to be doing just fine: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Testing DJREACT with Yarn</title> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div id="main"> <div id="app"></div> </div> <script src="{% static 'frontend/main.js' %}"></script> </body> </html> I think I did the installation correctly. The title of the web is indeed getting rendered but the body is not ???????????????????????? -
Cannot visualize ImageField in Django Rest Framework
I have a model with an ImageField: image_url = models.ImageField(upload_to=upload_to, blank=True, null=True) I did include it in my serializer in this way: image_url = serializers.ImageField(required=False, use_url=True) This is my viewset: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.order_by('-id') serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser) permission_classes = [ permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() The media root and url: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py: urlpatterns = [ path("users/", include("user.urls")), path("products/", include("products.urls")), path("utils/", include("utils.urls")), path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.jwt")), path("graphql/", csrf_exempt(GraphQLView.as_view(schema=schema, graphiql=True))), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It get listed properly: But the problem is that once I click on the url of the image (that is inside the media folder), it shows me a 404 error in this url: http://127.0.0.1:8000/media/images/base_bWxtftQ.png. But the image is in that folder. -
Creating A Responsive / Dynamic Form for Business Users, Efficiently
I am a data engineer and I've found myself in a position of needing to develop advanced frontend forms for nontechnical business users. These business users do not want or need to understand complexities of data modeling, and this is my strategy to try and remove the manner by which the complexities of data modeling impact the data entry process. As I said though, I am a data engineer- not a web developer. Before I reinvent the wheel here, what would be some feedback for this approach? Form Components and Their Expected Behaviors: Selection Fields: Behavior: Prepopulated with unique values from a column, allowing users to select or search for an option. Initialization: Start as empty fields. Input Fields: Behavior: Accept raw input from the user. Update Fields: Behavior: Corresponds to a table column that should receive updates. Also listens to a single Invisible Field for state changes. Visibility: Not editable until their corresponding Invisible Field is populated with a row-id value. Edit State: Require a double-click to enter an editable state. Value Update: Leaving the editable state with a changed value results in an UPDATE to the database record matching the ID value in the corresponding invisible field. Invisible … -
UserAccountManager superuser not loggin in
I am trying to add to my UserAccountManager, a way of creating a superuser so that I can easily manage my database, my problem is that when I create the super user from the terminal, everything seems ok, I don't get errors, but when I try to log in the default django admin page, it says that no staff account with those credentials is found. I have tried deleting my database, removing and redoing migrations. This is my models.py class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('User must have an email') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, first_name, last_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, first_name, last_name, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=128) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] -
Daphne refuses to connect websocket requests
I have a developed a complex Django server consisting of several applications, making use of channels in combination with the Daphne server an reverse proxy uplink from Nginx. This is the site configuration from /etc/nginx/sites-available: server { listen 80; server_name django.mydomain.eu; return 301 https://$server_name$request_uri; } server { client_max_body_size 100M; listen 443 ssl; server_name django.mydomain.eu; ssl_certificate /etc/letsencrypt/live/django.mydomain.eu/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/django.mydomain.eu/privkey.pem; access_log /var/log/nginx/django.mydomain.eu.access.log combined; error_log /var/log/nginx/django.mydomain.eu.error.log info; location /ws/ { proxy_pass http://127.0.0.1:8000/ws/; 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; } location / { proxy_pass http://127.0.0.1:8000/; } } Both HTTP and Websocket requests are forwarded to Daphne on port 8000. HTTP works fine. Websocket works fine if coming from the Python client, the connections are made somewhat like this: from websocket import WebSocket while self.do_run: try: self.ws = WebSocket() self.ws.connect(self.dbline.wsserver+'ws/predictions/') break except (BrokenPipeError, TimeoutError, WebSocketBadStatusException, ConnectionRefusedError, WebSocketConnectionClosedException, WebSocketAddressException, OSError, ): self.logger.warning('BrokenPipe or Timeout while resetting ' + 'prediction websocket server') sleep(djconf.getconfigfloat('long_brake', 1.0)) Websocket does not work when coming from the JavaScript section of a Django template, where the connections are made like this: function WSAsync(url) { return new Promise((resolve, reject) => { let result = {}; result.tracker = 0; … -
Python Django Authentication (Login/Register) Errors
I am making a weather application and wanted to incorporate authentication into it, so I decided to use django and postgres as my backend. I am new to all of this, so this may seem like a really dumb and easy fix for some of you... but for me I've spent a few hours with no success. The error I come through is: I have 3 html pages, dashboard.html, login.html and register.html. My folder structure is as follows: --- Folder Structure --- .DS_Store README.md db.sqlite3 manage.py [my_weather_project] ├── __init__.py ├── [__pycache__] ├── __init__.cpython-310.pyc ├── settings.cpython-310.pyc ├── urls.cpython-310.pyc └── wsgi.cpython-310.pyc ├── asgi.py ├── settings.py ├── [staticfiles] # a lot of files here that I did not include ├── urls.py └── wsgi.py my_weather_project.zip [myapp] ├── .DS_Store ├── __init__.py ├── [__pycache__] ├── __init__.cpython-310.pyc ├── admin.cpython-310.pyc ├── apps.cpython-310.pyc ├── forms.cpython-310.pyc ├── models.cpython-310.pyc ├── urls.cpython-310.pyc └── views.cpython-310.pyc ├── admin.py ├── apps.py ├── forms.py ├── [migrations] ├── 0001_initial.py ├── __init__.py └── [__pycache__] ├── 0001_initial.cpython-310.pyc └── __init__.cpython-310.pyc ├── models.py ├── [templates] ├── .DS_Store ├── [dashboard] └── dashboard.html └── [registration] ├── login.html └── register.html ├── tests.py ├── urls.py └── views.py requirements.txt [static] └── [js] └── cookies.js Here is my cookies.js: document.addEventListener('DOMContentLoaded', function () { const form = document.getElementById('registration-form'); … -
Adding plugins inside HTMLField in Django-CMS
I am struggling adding plugins inside HTMLField as djangocms-text-ckeditor in the latest version Django-Cms 4.1.0rc4 add fileimage plugin/button in the toolbar of it. In my models.py class PortfolioItem(CMSPlugin): # Attributes - Mandatory title = models.CharField(_('title'), max_length=200, blank=False) content = HTMLField() In the settings.py CMS_PLACEHOLDER_CONF = { 'content': { 'name' : _('Content'), 'plugins': ['TextPlugin', 'LinkPlugin', 'FilerImage'], 'default_plugins':[ { 'plugin_type':'TextPlugin', 'values':{ 'body':'<p>Great websites : %(_tag_child_1)s and %(_tag_child_2)s</p>' }, 'children':[ { 'plugin_type':'LinkPlugin', 'values':{ 'name':'django', 'url':'https://www.djangoproject.com/' }, }, { 'plugin_type':'FilerImage', 'values':{ 'name':'django-cms', 'url':'https://www.django-cms.org' }, }, ] }, ] } } CKEDITOR_SETTINGS = { 'language': '{{ language }}', 'toolbar': 'CMS', 'toolbar_HTMLField': [ ['Undo', 'Redo'], ['cmsplugins', '-', 'ShowBlocks'], ['Format', 'Styles'], ], 'skin': 'moono-lisa', } I can not get the list of plugins and fileimage button does not show up. How do I get the plugins inside nested editor? ps: in the console i am getting bundle-9f0bbac8ec.cms.ckeditor.min.js:25 [CKEDITOR] Error code: editor-plugin-deprecated. {plugin: 'flash'} -
Getting n*n forms when I use formset
I am using multiple formsets in one page according to the categories I require,this has lead me to getting two errors right now; 1.I am getting n*n number of forms for one formset when asked for n 2.The cleaned data gives a none value at the end views.py def form_faculty(request): submitted=False Tutorial_number=request.session["Tuts"] Lab_number=request.session["Lab"] Lecture_Number=request.session["Lec"] Lab_Faculty=[] Tut_Faculty=[] Lec_Faculty=[] #number of forms get squared here Lectureformset=formset_factory(facultyform1,extra=Lecture_Number) Tutformset=formset_factory(facultyform2,extra=Tutorial_number) Labformset=formset_factory(facultyform3,extra=Lab_number) if request.method=="POST": form_lec=Lectureformset(request.POST or None) form_tut=Tutformset(request.POST or None) form_lab=Labformset(request.POST or None) if all([form_lec.is_valid(),form_tut.is_valid(),form_lab.is_valid()]): for form1 in form_lec.forms: Lec_Faculty.append(form1.cleaned_data.get('Faculty_Lec')) #gives none as the value for form2 in form_tut.forms: Tut_Faculty.append(form2.cleaned_data.get('Faculty_Tut')) #gives none as the value for form3 in form_lab.forms: Lab_Faculty.append(form3.cleaned_data.get('Faculty_Lab')) #gives none as the value create_file(FIC_name=FIC,cdc=cdc_name,Lecture=Lecture_Number,Tutorial=Tutorial_number,Lab=Lab_number,Faculty_Lab=Lab_Faculty,Faculty_Lec=Lec_Faculty,Faculty_Tut=Tut_Faculty) return HttpResponseRedirect('choose_new_table?submitted=True') return render(request, 'homepage/facultyForm.html', {'Lectureformset': Lectureformset,'Tutformset':Tutformset,'Labformset':Labformset,"submitted":submitted}) forms.py class facultyform1(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Lec") class facultyform2(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Tut") class facultyform3(forms.Form): Department_name = department_description.objects.get() Faculty = forms.ModelChoiceField(queryset=Faculty_List.objects.filter(Department=Department_name),label="Faculty_Lab") .html <form action="" method=POST> {% csrf_token %} <center> <center> <b>Tutorial</b> </center> <br><br> <center> {% for form in Tutformset %} {{Tutformset.as_table}} {%endfor%} </center> <br><br> <center> <b>Lab</b> </center> <br><br> <center> {% for form in Labformset %} {{Labformset.as_table}} {%endfor%} </center> <br><br> <center> <b> Lecture </b> </center> <br> <br> <center> {% for form in Lectureformset %} {{Lectureformset.as_table}} {%endfor%} </center> <br /> <br … -
failing to build django cookiecutter
I guess its stupid question, but still when im trying to build like in docs docker-compose -f production.yml build its give me error like CELERY_BROKER_URL=\"\" DJANGO_SETTINGS_MODULE=\"config.settings.test\" python manage.py compilemessages" did not complete successfully: exit code: 1 in default Dockerfile its contains empty field`s. What's im doing not rigth ? im tryed fill this fields by my credetials, and still getting this error. -
Django: sending email through smtp.gmail.com
I am using Django==4.2.1 I want to send an email to user using django.core.mail.EmailMessage, but facing this exception: socket.gaierror: [Errno -3] Temporary failure in name resolution My Django settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my-email" EMAIL_HOST_PASSWORD = "xxxxxxxxxxxxxxxx" # 16-char Google App password EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = "foo my-email" Code: from django.core.mail import EmailMessage from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import CreateModelMixin from rest_framework.response import Response from settings import EMAIL_HOST_USER from .models import Instance class InstanceViewSet(GenericViewSet, CreateModelMixin): serializer_class = InstanceCreateSerializer queryset = Instance.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() email = EmailMessage( subject="subject", body="sup", from_email=EMAIL_HOST_USER, to=[instance.user.email] ) email.content_subtype = 'html' email.send() return Response(serializer.data, status=201) I tried to ping smtp.gmail.com from my docker container and it works fine. Tried to recreate EMAIL_HOST_PASSWORD. Also tried to use other EMAIL_HOST_USER. Any thoughts? -
Django Error: "Select a valid choice. That choice is not one of the available choices." Form works for one ID, but not the other
Models.py class PointCategoryRecord(models.Model): point_category_assignment_id = models.AutoField(primary_key=True) league_id = models.ForeignKey(League) description = models.TextField(default="") user_getting_points = models.ForeignKey(TeamMember) date_created = models.DateTimeField(auto_now=True) Forms.py class UserForm(ModelForm): class Meta: model = PointCategoryRecord fields = '__all__' Views.py def point_form(request, league_id): form = UserForm() if request.method == "POST": if form.is_valid(): form.save() return redirect(request.path_info) form.fields['league_id'].queryset = League.objects.filter(league_id = league_id) form.fields['point_category'].queryset = PointCategory.objects.filter(league_id = league_id) form.fields['user_getting_points'].queryset = TeamMember.objects.filter(league_id = league_id) urls.py I have the path() correct and it's passing the league_id through int:league_id I'm trying to create a form that filters by the 'league_id' parameter being passed in the views.py function. I have two objects, one with the league_id of 1 that works perfectly. The other with the league_id of 2 that throws the "Select a valid choice. That choice is not one of the available choices." error. Any idea why it works for the first ID but not the second? -
Function not triggering correctly when called
I am using request.session to pass value from one page to another in django but apparantly when you trigger the latter function,it does not update the variable. views.py first function` def form_CDC(request): global FIC if request.method == 'GET': cdc_name = request.GET.get('data') if request.method == 'POST': form = classForm(request.POST) if form.is_valid(): FIC=form.cleaned_data["FIC"] request.session['Tuts']=form.cleaned_data["Tutorials"] request.session['Lec']=form.cleaned_data["Lectures"] request.session['Lab']=form.cleaned_data["Labs"] return HttpResponseRedirect("form_Faculty") else: form = classForm() return HttpResponseRedirect('form_CDC') else: form = classForm() return render(request, "homepage/form_CDC.html", context={'form': form,"cdc_name":cdc_name}) second function def form_faculty(request): submitted=False #these lines of code are not triggered when page is loaded Tutorial_number=request.session["Tuts"] Lab_number=request.session["Lab"] Lecture_Number=request.session["Lec"] Lab_Faculty=[] Tut_Faculty=[] Lec_Faculty=[] Lectureformset=formset_factory(facultyform1,extra=Lecture_Number) Tutformset=formset_factory(facultyform2,extra=Tutorial_number) Labformset=formset_factory(facultyform3,extra=Lab_number) if request.method=="POST": form_lec=Lectureformset(request.POST or None) form_tut=Tutformset(request.POST or None) form_lab=Labformset(request.POST or None) if all([form_lec.is_valid(),form_tut.is_valid(),form_lab.is_valid()]): for form1 in form_lec.forms: Lec_Faculty.append(form1.cleaned_data['Faculty']) for form2 in form_tut.forms: Tut_Faculty.append(form2.cleaned_data['Faculty']) for form3 in form_lab.forms: Lab_Faculty.append(form3.cleaned_data['Faculty']) create_file(FIC_name=FIC,cdc=cdc_name,Lecture=Lecture_Number,Tutorial=Tutorial_number,Lab=Lab_number,Faculty_Lab=Lab_Faculty,Faculty_Lec=Lec_Faculty,Faculty_Tut=Tut_Faculty) return HttpResponseRedirect('choose_new_table?submitted=True') return render(request, 'homepage/facultyForm.html', {'Lectureformset': Lectureformset,'Tutformset':Tutformset,'Labformset':Labformset,"submitted":submitted}) urls.py urlpatterns = [ path('form_CDC',views.form_CDC,name='form_CDC'), path('form_Faculty',views.form_faculty,name='form_Faculty'), ] ` I feel its a dumb intendetion mistake since it was working fine before but now trying every possible outcome,nothing I can think of is remaining.Hope someone can help me out. -
django manage.py can not find command
When I run python manage.py loadcsv --csv reviews/management/commands/WebDevWithDjangoData.csv manage.py cannot find command loadcsv. Any help -
Many to Many Django Model
Hello i am trying to figure out the best way to design this model, this is what i have so far but i am running into issues of having a start and end date per service per customer class Customer(models.Model): name = models.CharField(max_length=255, null=False, unique=True) services = models.ManyToManyField(Service) class Service(models.Model): name = models.CharField(max_length=255, null=False) What would be the best way to design this in order to get the data to look like this: Customer || Services || Start || End Customer A Service A 1/1/2001 1/1/2010 Service B 2/2/2002 2/2/2011 Service C 3/3/2003 3/3/2012 Customer B Service A 4/4/2004 4/4/2014 Service C 5/5/2005 5/5/2015 Have been breaking my head for last few days trying to figure out what is the best way to design this model. Any help would be very much appreciated. -
Django + IIS + HttpPlatform handler
I'm trying to configure the web.config file but I can't, I would like help on how to configure it <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/> </handlers> <httpPlatform processPath="C:\Program Files\Python312\venv\Ambiente_datafit\Scripts\python.exe" arguments="C:\Application\Datafit.Pro\Projeto_datafit\manage.py runserver %HTTP_PLATFORM_PORT%" stdoutLogEnabled="true" startupTimeLimit="60" processesPerApplication="16"> <environmentVariables> <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" /> </environmentVariables> </httpPlatform> </system.webServer> </configuration> I put the path to python in my virtual environment in processPath and in arguments I put the path to manage.py, but something is still missing I have this error The requested page cannot be accessed because the configuration data related to the page is invalid. Help configuring the web.config file -
Django Container Fails to Find Settings Module Specified in Environment Variable
I'm encountering a persistent issue when deploying my Django application using Docker. Despite specifying the settings module in my environment variable, Django throws an OSError indicating it cannot find the file. Here's the error I'm getting: OSError: No such file: /code/app/settings/environments/.py This suggests that Django is looking for a .py file without a preceding filename in the /code/app/settings/environments/ directory. Moreover, when I remove the development.py file, Django raises a different error: ModuleNotFoundError: No module named 'app.settings.environments.development' Here's how I have my DJANGO_SETTINGS_MODULE set in docker-compose.yml: `services: web: build: context: ./ dockerfile: docker/Dockerfile.backend volumes: - ./backend/:/code/ ports: - 8000:8000 environment: - DJANGO_SETTINGS_MODULE=app.settings.environments.development env_file: - backend/.env depends_on: - database database: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - backend/.env ports: - "5434:5432" volumes: postgres_data:` `FROM python:3.11-slim ARG DJANGO_ENV ENV DJANGO_ENV=${DJANGO_ENV} \ PYTHONFAULTHANDLER=1 \ PYTHONUNBUFFERED=1 \ PYTHONHASHSEED=random \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=on \ PIP_DEFAULT_TIMEOUT=100 RUN apt-get update && apt-get install -y \ gcc \ python3-dev \ libpq-dev \ netcat-openbsd \ && rm -rf /var/lib/apt/lists/* WORKDIR /code COPY backend/requirements /code/requirements COPY backend/app/settings /code/app/settings RUN pip install -r requirements/development.txt COPY backend /code EXPOSE 8000 CMD ["sh", "run.sh"]` In backend/.env file I have only DB settings. In run.sh file script check if database has been started and then … -
How to make Django Dynamic Inline Forms as like admin (using Class Based Views)?
I have 2 Models class Section(models.Model): SECTION_CHOICES_CLASS_6_7_8 = [ ("A", "Section A"), ("B", "Section B"), ("C", "Section C"), ] SECTION_CHOICES_CLASS_9_10 = [ ("Sc", "Science"), ("Co", "Commerce"), ("Ar", "Arts"), ] name = models.CharField( max_length=2, verbose_name="Section", choices=SECTION_CHOICES_CLASS_6_7_8 + SECTION_CHOICES_CLASS_9_10, ) description = models.TextField( null=True, blank=True, help_text="Section Description, e.g. 'Section A of Class 6, total 30 students'", ) class_name = models.ForeignKey( Class, on_delete=models.CASCADE, help_text="Class", verbose_name="Class", ) teacher = models.OneToOneField( "Teacher", on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Section Teacher", ) seat = models.PositiveIntegerField(default=0) subjects = models.ManyToManyField(Subject, through="SectionSubject") class SectionSubject(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) teachers = models.ForeignKey(Teacher, on_delete=models.CASCADE) period = models.IntegerField( default=0, validators=[MaxValueValidator(10), MinValueValidator(0)] ) time = models.TimeField( null=True, blank=True, ) After configuring the admin, Using Tabular Inline How can I achieve the same kinda UI functionality in the template. Or suggest me a better way to make it comfortable for user. I've tried the inlineformset_factory forms.py class SectionSubjectForm(forms.ModelForm): class Meta: model = SectionSubject fields = "__all__" widgets = { "subject": forms.Select(attrs={"class": "form-select"}), "teachers": forms.Select(attrs={"class": "form-select"}), "period": forms.TextInput(attrs={"class": "form-control "}), "time": forms.TextInput(attrs={"class": "form-control "}), } SectionSubjectInlineFormset = inlineformset_factory( Section, SectionSubject, form=SectionSubjectForm, extra=1, can_delete=True, can_delete_extra=True, ) views.py class SectionCreateView(SuccessMessageMixin, CreateView): form_class = SectionForm template_name = "dashboard/section/section_add_or_update.html" success_message = "Section created successfully" def get_context_data(self, **kwargs): context … -
Open the link in new tab instead of the default action of a bootstrap template
I am using a bootstrap MyResume And there is this section This is the piece of code for it <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-1.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 1</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-1.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 1"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-2.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 3</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-3.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 2</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-3.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-4.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 2</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-4.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 2</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-5.jpg" …