Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
(django) Foreign key does not get recorded and receives Integrity Error
I'm trying create a python with django project to record the username (active session), quizid, questionid, studentanswer to mysql database but receives the integrity error > "Column 'username_id' cannot be null" models.py class Quiz(models.Model): questionid = models.IntegerField(null=False) quizid = models.AutoField(primary_key=True) subjectname = models.CharField(max_length=50) question = models.CharField(max_length=50) correctanswer = models.CharField(max_length=50) eqpoints = models.IntegerField() student = models.ManyToManyField("self", through="StudentAnswer") teacher = models.ManyToManyField(Teacher) class StudentAnswer(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) questionid = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='quiz_question') quizid = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='quiz_id') studentanswer = models.CharField(max_length=50) forms.py class StudentAnswerForm(ModelForm): questionid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('questionid')) studentanswer = forms.CharField(widget=forms.TextInput()) quizid = forms.ModelChoiceField(widget=forms.Select(), queryset=Quiz.objects.only('quizid')) class Meta: model = StudentAnswer fields = ['quizid','questionid','studentanswer'] views.py class AnswerQuiz(View): template = 'ansQuiz.html' def get(self, request): form = StudentAnswerForm() request.session['visits'] = int(request.session.get('visits', 0)) + 1 quiz = Quiz.objects.all() #get data from all objects on Quiz model return render(request, self.template,{'quiz':quiz, 'form':form}) def post(self,request): if request.method == 'POST': form = StudentAnswerForm(request.POST) if form.is_valid(): form.instance.user = request.user form.save() return render(request, self.template, {'form':form}) -
Aggregate Sum shows total for all members
When i add aggregate function on my get_context_data it shows the total for all members and not according to there ID. Thank You ItemListView class ItemListView(ListView): model = HBTYItem template_name = "accounts/modals/nomodal/todo_list.html" paginate_by = 2 ordering = ['id'] def get_queryset(self): return HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) def get_context_data(self): context = super().get_context_data() context['t_sum'] = HBTYItem.objects.aggregate(Sum('price')) context["hbty_list"] = HBTYList.objects.get(id=self.kwargs["list_id"]) return context -
Django query based on through table
I have a 5 models which are Contents, Filters,ContentFilter , Users. a user can view contents. a content can be restricted using Filters so users can't see it. here are the models. class Content(models.Model): title = models.CharField(max_length=120) text = models.TextField() filters = models.ManyToManyField(to="Filter", verbose_name=_('filter'), blank=True, related_name="filtered_content",through='ContentFilter') class Filter(models.Model): name = models.CharField(max_length=255, verbose_name=_('name'), unique=True) added_user = models.ManyToManyField(to=User, related_name="added_user", blank=True) ignored_user = models.ManyToManyField(to=User, related_name="ignored_user", blank=True) charge_status = models.BooleanField(blank=True, verbose_name=_('charge status')) class ContentFilter(models.Model): content = models.ForeignKey(Content, on_delete=models.CASCADE) filter = models.ForeignKey(Filter, on_delete=models.CASCADE) manual_order = models.IntegerField(verbose_name=_('manual order'), default=0,rst')) access = models.BooleanField(_('has access')) What it means is that 5 contents exist(1,2,3,4,5). 2 users exist. x,y A filter can be created with ignored user of (x). Contents of 1,2,3 have a relation with filter x. so now X sees 4,5 and Y sees 1,2,3,4,5 what I'm doing now is that based on which user has requested find which filters are related to them. then query the through table(ContentFilter) to find what contents a user can't see and then exclude them from all of the contents.(this helps with large joins) filters = Filter.objects.filter(Q(added_user=user)|(Q(ignored_user=user)) excluded_contents = list(ContentFilter.objects.filter(filter__in=filters).values_list('id',flat=True)) contents = Contents.objects.exclude(id__in=excluded_contents) Problem I want a way so that Filters can have an order and filter a queryset based on top … -
How to create models depending on different users in Django?
I'm going to create a model called student. But the model might be a little different due to different users: trial and expert users. Expert users might have an additional field to store comments. class Student(models.Model): id = models.CharField( max_length=7,primary_key=True) name = models.CharField(_('name'),max_length=8, default=""); address = models.CharField(_('address'),max_length=30,blank=True,default="") # comments field is not available for trial users # and for expert users the max_length should also a variable # rather than a constant # the switch if(settings.version !="trial"): comments = models.CharField(_("comments"),max_length=30); My idea is to store an attribute to store the user's versions. And when it comes to initialize the model, the switch will determine if the field will be applied or not. But Where should I store the attibute? Is it appropriate to be inside settings.py? Or it should be an attribute of a customer? If it's not appropriate. Should I create different models for different versions? Do the tables should be created for different models with only one or two fields different? -
How to retrieve value in Dropdown list on edit button in Django
I have a form (edit_city.html) where I want to edit my record, there is also one dropdown field in which data is retrieving from another model name Country. How can I get the exact value in dropdown field, when I click on edit. class Country(models.Model): CountryID = models.AutoField(primary_key=True) CountryName = models.CharField(max_length=125, verbose_name="Country Name") def __str__(self): return self.CountryName class City(models.Model): CityID = models.AutoField(primary_key=True) CityName = models.CharField(max_length=125, verbose_name='City Name') Country = models.ForeignKey(Country, verbose_name='Country Name', on_delete=models.CASCADE) def __str__(self): return self.CityName views.py def Edit_City(request, id): city = City.objects.get(CityID=id) country = Country.objects.all() context = { 'city':city, 'country':country, } return render(request, 'City/edit_city.html', context) edit_city.html <form method="post" action="{% url 'update_city' %}"> {% csrf_token %} <div class="row"> <div class="col-12"> <h5 class="form-title"><span>Edit City</span></h5> </div> {% include 'includes/messages.html' %} <div class="col-12 col-sm-6"> <div class="form-group"> <label for="">Country</label> <select class="form-control" name="country_id" required> <option>Select Country</option> {% for con in country %} <option value="{{con.CountryID}}">{{con.CountryName}}</option> {% endfor %} </select> </div> </div> <div class="col-12 col-sm-6"> <div class="form-group"> <label>City Name</label> <input type="text" class="form-control" name="city_name" value="{{city.CityName}}" required> <input type="text" class="form-control" name="city_id" value="{{city.CityID}}" required hidden> </div> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Update City</button> </div> </div> </form> -
Fetch API key from Django to React app in a secure way
I am building an app at the moment and security is a priority so I want to ensure I'm implementing API fetches correctly. I currently have stored an API key in a .env file in Django. I want to use this key to perform requests through the frontend. django-app/.env API_KEY = key settings.py import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) SECRET_KEY = os.environ['API_KEY'] I'm only just getting into backend development so I'm unsure of how to produce a view that would allow the frontend to use this key safely. Any tips or pointers will be much appreciated, thank you