Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prevent Django to save an specific form from a formset
I'm working with a Django formset and I'm trying to prevent certain forms that could be partially filled to be saved. Form: class WeeksForm(forms.ModelForm): monday = forms.DecimalField(required=False) tuesday = forms.DecimalField(required=False) wednesday = forms.DecimalField(required=False) thursday = forms.DecimalField(required=False) friday = forms.DecimalField(required=False) saturday = forms.DecimalField(required=False) sunday = forms.DecimalField(required=False) class Meta: model = Weeks fields = ('activity', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') Formset: WeeksFormset = modelformset_factory(Weeks, form=WeeksForm, extra=10, can_delete=True) I'm dynamically generating the forms using JS and it automatically fills the field 'activity' but the problem is that sometimes the user might decide to not complete the other fields (those named with weekdays, "monday", "tuesday", etc...). If that is the case I end up with an "empty" form (not really empty because the field "activity" was filled) that I'm not interested in saving. I'm trying to somehow prevent in my view that these forms are saved: views.py if request.method == 'POST': formset = WeeksFormset(request.POST) if formset.is_valid(): for form in formset.forms: # From here is pseudocode, I want that if a form has all the weekdays empty that form is not saved if form.instance.monday and form.instance.tuesday and ... form.instance.sunday == None: form.delete() # End of pseudocode, this approach didn't work form.instance.user = request.user … -
django application code in @staticmethod or class?
I have long functions in my Django application like process staff pay, I dont want these functions directly in the view, so I moved them out to their own python files but the only way I could call the functions from the view was to make them @staticmethod, this seems wrong. How do I create a module and then call the functions without making the functions static? -
Django - constraint that uses related field value
As of now, it isn't possible to create constraints that use joins so I'm trying to figure out how I can do this. I want to make sure (on a DB level) that ResponseDetail.object is NOT null if response__action=='added' and IS null if response__action=='removed'. I can't modify Response model. class Response(..): action = CharField # added/removed class ResponseDetail(..): response = OneToOneField.. object = OneToOneField... class Meta: constraints = [ # CheckConstraint( # check=Q( # Q(response__action="added", object__isnull=False) # | Q(response__action="removed", object__isnull=True) # ), # name="object_only_if_action_added", # ) ] The CheckConstraint would work if Postgres and Django supported joins in constraints. Another solution is to add ResponseDetail.response_action field but I'm curious if there is a solution that doesn't expect me to add such field. -
Django rest framework - using SerializerMethodField with ModelSerializer
I have the following models. models.py class Language(models.Model): name = models.CharField(max_length=255, unique=True) class Subject(models.Model): name = models.CharField(max_length=255, unique=True) class Term(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) name = models.CharField(max_length=255) definition = models.TextField() image = models.ImageField(default='', blank=True) I want to write a Serializer that will return a list of subjects. Each subject has a term field, which contains None or a single object, depending on the condition. serializers.py class TermSerializer(serializers.ModelSerializer): language = serializers.CharField(source='language.name') def to_representation(self, data): data = data.get(language=self.context['language']) return super(TermSerializer, self).to_representation(data) class Meta: model = Term fields = ('id', 'language', 'name', 'definition', 'image') class FilteredSubjectSerializer(serializers.ListSerializer): def to_representation(self, data): if self.context['condition']: terms = Term.objects.filter(language=self.context['language']) data = data.filter(term__in=terms) return super(FilteredSubjectSerializer, self).to_representation(data) class SubjectSerializer(serializers.ModelSerializer): term = serializers.SerializerMethodField() def get_term(self, term): if self.context['condition']: return TermSerializer(many=False, source='term_set').data return None class Meta: model = Term list_serializer_class = FilteredSubjectSerializer fields = ('id', 'name', 'definition', 'image', 'term') The problem is that when condition == True, the ViewSet returns incorrect data. All fields inside term have a default value. It works fine if I write SubjectSerializer like this: class SubjectSerializer(serializers.ModelSerializer): term = serializers.TermSerializer(many=False, source='term_set') class Meta: model = Term list_serializer_class = FilteredSubjectSerializer fields = ('id', 'name', 'definition', 'image', 'term') But the case when condition == False doesn't … -
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"