Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render many to many in template
I have this models: class roles(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=False) company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name class freelancers(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) role = models.ManyToManyField(roles) I try to get the name that is related to the user at the roles table. In my view.py It looks like this: def company_details(request,id): obj = Company.objects.get(id=id) pro = Projects.objects.filter(company=id) free = freelancers.objects.filter(company=id) #free = freelancers.objects.all() return render(request, 'company/company_details.html', { 'obj':obj, 'pro':pro, 'free':free, } ) And in the HTML: {% for f in free %} {{ f.user }} // <br/> {% endfor %} {{ f.role.all }} {% endfor %} I have been trying different ways to get the name to show up. Like: {{ f.role.name }}. So any tips to make this work? -
can't compare datetime.datetime to datetime.date django
I'm trying to build reservation app. I tried to find the solution but I have no idea. import datetime def check_availability(room, check_in, check_out): avail_list = [] booking_list = Booking.objects.filter(room=room) for booking in booking_list: if booking.check_in > check_out or booking.check_out < check_in: avail_list.append(True) else: avail_list.append(False) return all(avail_list) from hotelbooking.booking_funkctions.availibility import check_availability class BookingView(FormView): form_class = AvalilabilityForm template_name = 'availability_form.html' def form_valid(self, form): data = form.cleaned_data room_list = Room.objects.filter(category=data['room_category']) available_rooms=[] for room in room_list: if check_availability(room, data['check_in'], data['check_out']): available_rooms.append(room) if len(available_rooms)>0: room = available_rooms[0] booking = Booking.objects.create( user = self.request.user, room = room, check_in = data['check_in'], check_out = data['check_out'] ) booking.save() return HttpResponse(booking) else: return HttpResponse('this category of rooms are booked') class AvalilabilityForm(forms.Form): ROOM_CATEGORIES = ( ('YAC', 'AC'), ('NAC', 'NON-AC'), ('DEL', 'DELUXE'), ('KIN', 'KING'), ('QUE', 'QUEEN'), ) room_category = forms.ChoiceField(choices=ROOM_CATEGORIES, required=True) check_in = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) check_out = forms.DateField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) -
docker containers can not connect to each other
I have a django-rest-framwork app which uses PosgreSql as db. So I am using docker containers for them one image for django-rest-framwork and one for PosgreSql, and then docker compose file to handle them. db service refrese to PostgreSQL backend refers to Django Rest app I have a docker-compose file version: '3.9' services: db: image: postgres:latest restart: always ports: - "5432:5432" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=85842475DB - POSTGRES_DB=sports_center_db - POSTGRES_PORT=5432 backend: build: ./api depends_on: - db ports: - "8000:8000" environment: - DB_NAME=sports_center_db - DB_USER_NAME=postgres - DB_PASSWORD=85842475DB - DB_HOST=db - DB_PORT=5432 It builds correctly but when I ran docker compose up I got following logs [+] Running 2/2 ⠿ Container sports_center-db-1 Created 0.1s ⠿ Container sports_center-backend-1 Created 0.1s Attaching to sports_center-backend-1, sports_center-db-1 sports_center-db-1 | The files belonging to this database system will be owned by user "postgres". sports_center-db-1 | This user must also own the server process. sports_center-db-1 | sports_center-db-1 | The database cluster will be initialized with locale "en_US.utf8". sports_center-db-1 | The default database encoding has accordingly been set to "UTF8". sports_center-db-1 | The default text search configuration will be set to "english". sports_center-db-1 | sports_center-db-1 | Data page checksums are disabled. sports_center-db-1 | sports_center-db-1 | fixing permissions on existing … -
Django inlineformset_factory. Request.FILES not returning filename to form when formset.is_valid() = False
I'm trying to allow the user to upload images tied to a project. I'm doing this via an inlineformset_factory. Im serving the form to the user trough a function based view. When the user fails to fill in one (or more) of the formsets correctly formset.is_valid() returns false and the bound formsets get returned to the user along with error messages. What i'm having trouble with is that the imagefield is not returned to the bound form. So if the user has filled in 2 out of 3 forms correctly then neither of the formsets have a bound imagefield after the failed validation. I can't manage to figure out if this is working as intended or if i'm doing something wrong. If i print out request.FILES i get the following: <MultiValueDict: {'image_set-0-filename': [<InMemoryUploadedFile: IMG_0017.jpg (image/jpeg)>], 'image_set-1-filename': [<InMemoryUploadedFile: sprite.svg (image/svg+xml)>]}> I would like the imagefield to be bound and show the user what value the field has. before incorrect form submission after incorrect form submission Hopefully you can see where my mistake is or tell me if i'm thinking about this the wrong way. Thank you in advance forms.py class EndUserImageForm(forms.ModelForm): class Meta: model = Image fields = ["filename", "description"] widgets … -
Django - Optimize grouping
I have a model: from django.db import models class Product(models.Model): sku = models.IntegerField() plu = models.CharField() pack_type = models.ForeignKey(PackTypes, on_delete=models.CASCADE) I need to group them into data structure: { < plu_1 >: { < sku_1 >: [ < pack_type_id_1 >, < pack_type_id_2 >, ... ], < sku_2 >: [], ... }, <plu_2>: { ... } } The code that does it: def dict_with_list(): return defaultdict(list) result = defaultdict(dict_with_list) products = Product.objects.values_list('sku', 'plu', 'pack_type_id') for (plu, sku, pack_type_id) in products: result[plu][sku].append(pack_type_id) The problem with it is because there are a lot of records in model Product the code is slow (> 5 seconds). How could I optimize the code to be faster? -
Unable to load multiple content blocks in Django 4.0 using TailwindCSS
Folder Structure: mysite -theme --templates ---main_base.html ---theme_footer.html ---theme_menu.html -home --templates ---home ----main.html main.html: {% extends "main_base.html" %} {% block content %} blah blah {% end content %} main_base.html: {% load static tailwind_tags %} <!DOCTYPE html> <html lang="en"> <head> {% tailwind_css %} </head> <body class="bg-blue-100"> <nav> {% block navbarn %} {% endblock %} </nav> {% block content %} {% endblock %} <footer> {% block footer %} {% endblock %} </footer> </body> </html> theme_menu.html: {% extends "main_base.html" %} {% block navbarn %} home {% endblock %} theme_footer.html {% extends "main_base.html" %} {% block footer %} <h1>this is a footer</h1> {% endblock %} So I was able to setup Django with Tailwind following the instructions on the plugin page. But I can't get the base theme to show multiple blocks. It doesn't show the menu nor the footer, just the base html template with content from main.html. Can't get it to work! -
Installing html5lib for Python on Ubunto
I am attempting to implement my selenium test suite for my Django app, but first want to install crispy forms. Apparently crispy forms has a dependency on html5lib, but for some reason when I attempt to pip install that I receive the below error. How do I adjust my system to grab and install html5lib? Traceback (most recent call last): File "/home/satch/.local/bin/pip", line 8, in <module> sys.exit(main()) File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/usr/lib/python3/dist-packages/pip/_internal/commands/__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "/usr/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 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 24, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py", line 16, in <module> from pip._internal.index.package_finder import PackageFinder File "/usr/lib/python3/dist-packages/pip/_internal/index/package_finder.py", line 21, in <module> from pip._internal.index.collector import parse_links File "/usr/lib/python3/dist-packages/pip/_internal/index/collector.py", line 14, in <module> from pip._vendor import html5lib, requests ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/__init__.py) -
Populate model instance with another model data during instance creation
I have creating an app as my learning project in Django. There are 3 model classes: # MOC class class Moc(models.Model): name = models.CharField(max_length=128, blank=True, null=True) my other fields... def __str__(self): return str(self.id) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: CheckList.objects.create(moc=self) # Pre Implement class class CheckList(models.Model): moc = models.OneToOneField(Moc, related_name='checklist', on_delete=models.CASCADE, default='1') name = models.CharField(max_length=128, blank=True, null=True) def __str__(self): return str(self.id) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: CheckListItem.objects.create(checklist=self) # Pre Implement Items class class CheckListItem(models.Model): checklist = models.ForeignKey(CheckList, related_name='checklistitems', on_delete=models.CASCADE, default='1') action_item = models.TextField(max_length=128, blank=True, null=True) actionee_name = models.ForeignKey(User, related_name='actionee_ready_pre_implements', on_delete=models.CASCADE, default='1') action_due = models.DateField(blank=True, null=True) def __str__(self): return str(self.id) I am creating Moc instance and on post save signal creating my CheckList class instance and consequently my CheckListItem class instances. However, imaging that my CheckList once created always should have 10 CheckListItem objects as a pre populated list (like an initial data). I could not figure-out if this is something doable (at least how I am trying to achieve it as per my model relationships). I do not want to hard code thus items in my HTML, I want to control add/delete of thus CheckListItems for related … -
MySql Client pip package isn't installing / is broken
When I run the command: pip3 install mysqlclient or pip install mysqlclient I get the following error: Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-jpxeffqw/mysqlclient_fed1a50532b74bc1aeaab814d12b88df/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The package is broken I guess but I need to run this now to make it work with my Django project. Any suggestions on any alternates or other command I could run … -
Updating data without redirecting to an update template
I'm learning django and trying to make a to-do app. I want to be able to change the status of a task from 'active' to 'finish' without redirecting the user to a different page just to update the status of a task. i've been reading the docs for the UpdateView class to see if there was a method that allow me to update the value of the status directly but couldn't find anything. -
Custom User Manager is not working in django
I have problem with custom user manager. It's not working properly, i mean it was working well but it stopped for some reason that i don't know (maybe i broke something). I can create user through my register page, but if i delete whole UserManager class nothing changes. It doesnt raise errors even if it should, normalize class for email is not working etc. What's more when i create superuser via "python manage.py createsuperuser" command everything is working fine. Models.py class CustomUserManager(BaseUserManager): def _create_user(self, email, user_name, password, first_name, last_name, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError("Password is not provided") user = self.model( email=self.normalize_email(email), user_name = user_name, first_name = first_name, last_name = last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, user_name, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, user_name, password, first_name, last_name, **extra_fields) def create_superuser(self, email, user_name, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, user_name, password, first_name, last_name, **extra_fields) class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) friends = models.ManyToManyField('self', blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = … -
I have a problem with MySQL and Django on Docker: "sql_mode=only_full_group_by"
"Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database_name.i.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by" Hi, sorry for me English. I have a problem with MySQL and Django when I dockerize my project. I'm new with this technologies. This is part of my docker-compose file: db_mysql: image: mysql:8 container_name: db_mysql restart: always environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: database_name MYSQL_USER: user MYSQL_PASSWORD: password ports: - '3306:3306' expose: - '3306' volumes: - dbdata:/var/lib/mysql The problem appears when I deploy my project and enter a section. The message I showed initially appears. I tried to apply what is mentioned in this post, but the problem persists. SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by I did the following: I entered the container of my db: docker exec -it db_mysql bash I logged in to MySQL with the root user: mysql -u root -p I placed the command to change the value of SQL_MODE: SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); I checked that the change has been made: SELECT @@sql_mode; I exited the container and restarted it with: docker restart db_mysql When … -
Expecting to get "non_field_errors: Unable to log in with provided credentials", but not getting it
Expectation: when wrong login credentials are provided, "non_field_errors: Unable to log in with provided credentials" is returned, such as below (screenshot from a tutorial which I'm following verbatim) Reality: instead I'm getting the error below. This gets printed to the console: POST http://127.0.0.1:8000/api/v1/token/login 400 (Bad Request) Interestingly I get this same error when I try to create users with passwords that are too short. I'm not having any issues with axios or the server when I provide the right credentials for log in, or use passwords of sufficient length when creating new users. When trying to catch errors such as these that I'm failing to get the expected result. My code for catching the error is the same as in the tutorial: methods: { submitForm() { axios.defaults.headers.common['Authorization'] = '' localStorage.removeItem('token') const formData = { username: this.username, password: this.password } axios .post('/api/v1/token/login', formData) .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common['Authorization'] = 'Token ' + token localStorage.setItem('token', token) this.$router.push('/dashboard/my-account') }) .catch(error => { if (error.response) { for (const property in error.response) { this.errors.push(`${property}: ${error.response.data[property]}`) } } else if (error.message) { this.errors.push('Something went wrong. Please try again!') } }) } } Is there something in the server settings that I … -
Is there a way to use django url template in json_script?
trying to find a way to save a url into a json script but its not rendering and reading it literally unlike other values: Tried this way {{ "{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}" | json_script:"url_test"}} And this way: {{ url_test | json_script:"{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}"}} But still comes out like this: <script id="url_test" type="application/json">"{% url 'tutorhomepage:tutorSelectedDay' tutor_id selected_date%}"</script> -
How to tell Django it has to read a some_folder/local.py file as settings.py
I am building an app in Django 4.1.2, and I am following a tutorial of an app made with Django 1.10.3. Right at the start, the teacher replaces settings.py with a directory settings containing the files local.py production.py base.py each of these having as content the exact copy of settings.py, with the exception that production.py has DEBUG=False instead of True. Then he changes, in each of these files, the BASE_DIR variable, from BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)) to BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) then, inside the new folder settings, he creates a __init__.py file, containing this from base import * from production import * try: from local import * except: pass then he runs python manage.py runserver and the server runs correctly. I did the same "file-to-folder" replacement, but I don't know how to update the content of BASE_DIR variable. Actually, because of the superior version of Django in my project, BASE_DIR was built by Django as BASE_DIR = Path(__file__).resolve().parent.parent How can I change it to have it correspond to the change made by the teacher? I tried with BASE_DIR = Path(__file__).resolve().parent.parent.parent then run python manage.py runserver, but it returns Traceback (most recent call last): File "/home/tommaso/tommaso03/programmazione/corsi_udemy/my-twitterlike-app/src/my_twitterlike_app/manage.py", line 22, in <module> main() File "/home/tommaso/tommaso03/programmazione/corsi_udemy/my-twitterlike-app/src/my_twitterlike_app/manage.py", … -
Memory leak in run Celery Django, Gevent strategy with Multi Worker
I used celery with rabbitmq in Django. my tasks are io-bound and I used the gevent strategy. I want to run celery tasks on a multi-process (because gevent runs on a single process). but memory grows up for no reason, without doing any tasks. what happened? this is my celery command: celery multi start 10 -P gevent -c 500 -A my-app -l info -E --without-gossip --without-mingle --without-heartbeat --pidfile='my-path' --logfile='my-path' my Django celery config: CELERY_IGNORE_RESULT = True CELERY_WORKER_PREFETCH_MULTIPLIER = 100 CELERY_WORKER_MAX_TASKS_PER_CHILD = 400 CELERYD_TASK_SOFT_TIME_LIMIT = 60 * 60 * 12 CELERYD_TASK_TIME_LIMIT = 60 * 60 * 13 celery==5.2.7 django==4.1.2 -
wanted to filter all the records created in last 24 hours with Django filter but timestamp stored epoch format in CharField
problem context - I've a django model like this. class UpdateRequests(models.Model): field_name = models.CharField(max_length=20) field_new_value = models.CharField(max_length=20) created_at = models.CharField(max_length=10) customer_id = models.CharField(max_length=50) request_status = models.CharField(max_length=20, choices=JOS_STATUS) request_close_date = models.CharField(max_length=20) problem statement - I want to fetch all records created with in last 24 hours. how I was trying - I was trying like this in my view function time_threshold = datetime.now() - timedelta(days=1) results = UpdateRequests.objects.filter(created_at__lte=time_threshold, request_status="Pending").values() but it is not working and I guess because django __lte , __gte works on DateTimeField() only. Please help me with this, I don't want to change the schema since it's already in the production. -
Django URL tag not working with JS file, weird bug
Hobbyist here. Can't seem to figure out how to use the {% url %} static template with dynamic javascript. For example, I am creating a list of days for a calendar where each day when clicked on should pull data from the database based on its date. The day is being created dynamically in a loop, where the href attribute is being set for the URL. My <a href> in the JS code looks like this currently for setting the URL: aLink.setAttribute('href', currentYear + '-' + (currentMonth + 1) + '-' +dayCounter) The problem with this method is this - Take a quick look at my URLS.py urlpatterns = [ path('<int:tutor_id>', views.tutorHomeOverviewPage, name='tutorHomeOverviewPage'), #homepage for when tutor/customer signs in path('<int:tutor_id>/<slug:selected_date>', views.tutorSelectedDay, name='tutorSelectedDay') ] If I start off on a page which matches path 1 like so: http://127.0.0.1:8000/tutorhomepage/7` The code for the list item looks like this and doesn't point to a matching path because it removes the /7 from the URL: <a href="2022-10-17" id="day17">17</a> Path: http://127.0.0.1:8000/tutorhomepage/2022-10-14 Giving me the obvious error when I click on it: Using the URLconf defined in sass_language_tutor_app.urls, Django tried these URL patterns, in this order: tutorhomepage/ <int:tutor_id> [name='tutorHomeOverviewPage'] tutorhomepage/ <int:tutor_id>/<slug:selected_date> [name='tutorSelectedDay'] admin/ The current path, … -
Porque a la hora de instalar la dependencia jazzmin me da un error
enter image description here Me dices que no encuentra el modulo ModuleNotFoundError: No module named 'jazzmin' -
How display the django q monitor output in a django view/template
I would like to show the status of Django Q in real time in a django app view/template, so accessible via browser, just like the result of the cli command python manage.py qmonitor. In particular, I would like to have displayed the currently running tasks (while the admin module of Django Q only displays the completed ones). -
ERROR: Could not find a version that satisfies the requirement rest-framework (unavailable) (from versions: none)
I'm a beginner and I'm getting this error, can someone with more experience help me? ERROR: Could not find a version that satisfies the requirement rest-framework (unavailable) (from versions: none) ERROR: No matching distribution found for rest-framework (unavailable) ERROR: Service 'web' failed to build : Build failed I've tried using the commands below but it didn't solve the problem. pip install djangorestframework-jsonapi pip3 install djangorestframework-jsonapi pip install -r requirements.txt --proxy address:port python -m pip install --upgrade pip python3 --version Python 3.10.6 print(django.get_version()) 3.2.12 cat /etc/os-release PRETTY_NAME="Ubuntu 22.04.1 LTS" -
Send id from one table to another automatically in form with ForeignKey in Django
#HELP in python (DJANGO 4) I send this message here because I have not been able to find an answer elsewhere. Currently I’m on a project where I have to create a booking form. The goal is that when the user submit the Reservation form, I send the data in BDD, and I retrieve the user's id by a relation (ForeignKey). And my difficulty is in this point precisely, when I send my form in BDD I recover the information, except the id of the user… I did a Foreignkey relationship between my 2 tables and I see the relationship in BDD but I don’t receive the id of the User table, but null in the place…. Does anyone of you know how to help me please? Thank you all. --My model.py -- class Reservation(models.Model): fullName = models.CharField('Nom Complet', max_length=250, null=True) adress = models.CharField('Adresse', max_length=100, null=True) zip_code = models.IntegerField('Code Postal', null=True) city = models.CharField('Vile', max_length=100, null=True) email = models.EmailField('Email', max_length=250, null=True) phone = models.CharField('Telephone', max_length=20, null=False) date = models.CharField('Date', max_length=20, null=True, blank=True) hour = models.CharField('Heure', max_length=20, null=True, blank=True) message = models.TextField('Message', null=True) accepted = models.BooleanField('Valide', null=True) created_at = models.DateTimeField('Date Creation', auto_now_add=True, null=True) modified_at = models.DateTimeField('Date Mise Jour', auto_now=True, null=True) user … -
Calculate a field django and save it in the database
I am just starting with Django and web development , so please be nice with me. i am trying to build an app that generates a new number to reports created by our inspectors (our company is an inspection company). each inspector chooses the type of reports, the inspection date and the client and the app saves the data and creates a report number . the report number is generated depending on the type of the report and the date. for example if i have 3 reports of type "visual inspection" done in 2022, the new "visual inspection" report will have the number 4/2022. here is the code I used to attempt this but unfortunately it is not working: Views.py from modulefinder import ReplacePackage from django.shortcuts import render from report.models import Report from django.http import HttpResponse from django.db.models.aggregates import Count from django.db import transaction from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ReportSerializer @api_view(['GET','POST']) def Report_add_view(request): if request.method =='GET': queryset = Report.objects.select_related('type').all() serializer = ReportSerializer(queryset,many=True) return Response(serializer.data,status=status.HTTP_200_OK) elif request.method =='POST': serializer = ReportSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) # Create your views here. models.py from django.db import models # Create your models here. class … -
How to show error messages during registration?
How to show error messages during registration? I tried to make an error message when filling out a field of registration. But it does not work. that is, when I enter the wrong data, the error message does not appear . what could be the problem? and how to fix it?? forms.py class UserRegistrationForm(forms.ModelForm): class Meta: model = User fields = ("username", "email", "password", ) def clean_username(self): username = self.cleaned_data.get('username') model = self.Meta.model user = model.objects.filter(username__iexact=username) if user.exists(): raise forms.ValidationError("A user with that name already exists") return self.cleaned_data.get('username') def clean_email(self): email = self.cleaned_data.get('email') model = self.Meta.model user = model.objects.filter(email__iexact=email) if user.exists(): raise forms.ValidationError("A user with that email already exists") return self.cleaned_data.get('email') def clean_password(self): password = self.cleaned_data.get('password') confim_password = self.data.get('confirm_password') if password != confim_password: raise forms.ValidationError("Passwords do not match") return self.cleaned_data.get('password') views.py def register_user(request): form = UserRegistrationForm() if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data.get('password')) user.save() messages.success(request, "Registration sucessful") return redirect('login') context = { "form": form } return render(request, 'registration.html') registration.html <fieldset> <input name="username" type="text" id="username_id" placeholder="Your username" > <p class="py-1 text-danger errors">{{form.username.errors}}</p> </fieldset> </div> <div class="col-md-12 col-sm-12"> <fieldset> <input name="email" type="email" id="email_id" placeholder="Your email" > <p class="py-1 text-danger errors">{{form.email.errors}}</p> </fieldset> </div> <div class="col-md-12 col-sm-12"> <fieldset> … -
Django static JS File not loading
When i am clicking button , js file is not loading internally..the static tag is not working inside home.html ... Its been a very long time since I had to use Django templates but I am having some trouble loading static js files. nav.html <!doctype html> <html lang="en"> <head> {% load static %} <link rel="stylesheet" href="{% static 'css/home.css' %}"> <script src='/crudapp/static/home.js'></script> <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap w/ Parcel</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.rtl.min.css" integrity="sha384-7mQhpDl5nRA5nY9lr8F1st2NbIly/8WqhjTp+0oFxEA/QUuvlbF6M1KXezGBh3Nb" crossorigin="anonymous"> <style> body{ background-color: rgb(54, 60, 58); } #dd{ color:blanchedalmond; } .table{ background-color: white; width:500px; margin-left: 500px; } .card{ margin-top: 100px; margin-left:500px; width:500px; } .card-body{ margin-left:100px; } .navbar-brand{ color:rgb(79, 200, 237); } </style> <link> <script src="/crudapp/static/home.js"></script> </head> <body> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="{%url 'index' %}">CRUD</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item"> <a class="navbar-brand" href="{%url 'data' %}">DATA</a> </li> </ul> </div> </div> </nav> </body> </html> home.html {% load static %} <!doctype html> <script type="text/javascript" src="{% static 'js/home.js' %}"></script> <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> <body> {%include 'nav.html'%} <div class="card"> <div class="card-body"> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" id="btnn" class="btn btn-primary">SUBMIT</button> </form> </div> </div> </body> </html> settings file STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') directory -static -css …