Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Django Object Values List to jquery datatables
I'm trying to display the data from postgresql using django python to jquery datatables but I'm having some problems. this is my view.py from administrator.models import User def showuser(request): showall = list(User.objects.values_list()) return render(request, '/path.html', {"data": showall}) I want to display it to html template using javascript <script type="text/javascript"> var myDjangoList = "{{ data | safe}}" console.log(myDjangoList) $(document).ready(function () { $("#example").DataTable({ data: [myDjangoList], columns: [ { title: "ID" }, { title: "First Name" }, { title: "Last Name" }, { title: "Email" }, { title: "Roles" }, { title: "Company" }, ], }); }); </script> But unfortunately, I'm having this problem. My table looks like this [table 1] and my data looks like this [(1, 'Test', 'Test', 'Test.@gmail.com', 'Test', 'Test')] -
No data in my postgres DB even though it exists
I have a PostgreSQL DB on a remote ubuntu server. My Python script is able to write to the DB, with the use of these configuration. def get_query(group_name , heb_sale_rent ,heb_street, heb_city , heb_rooms , heb_size , heb_floor , heb_porch , heb_storage , heb_mamad , heb_parking , heb_elevator , heb_phone , heb_price): conn = psycopg2.connect(database='my_db', host='192.168.72.130', port='5432', user='sql_user', password='sql_user') cur = conn.cursor() cur.execute("SELECT * FROM to_excel") query = cur.fetchall() print(query) #Result of print - [('1', 'Karin', 'מכירה, השכרה', 'רחוב, ברובע', 'שכונת, בסמטאות', 'חדרים', 'מ״ר, מ"ר', 'קומה', 'מרפסת', 'מחסן', 'ממד, ממ״ד', 'חניה, חנייה, חניית, חנית', 'מעלית', '054, 052, 053', 'מחיר, מבקשים', '2020-01-01')] I can see that there is data because it prints out the query, but when I connect to the DB on the ubuntu there are no table rows... so weird. Does anybody know what the problem might be? -
Testing CRUD function in Django Restaurant App
I am wondering if someone could help me. I am trying to test some views in a Django restaurant bookings system app I have created. I am doing well with jut testing the views but now I want to test the CRUD functionality of certain pages. In particular the create a booking on the bookings page and then redirect it back to the home page once the booking was successful (as is what happens on the site) I just can't seem to figure out how to do it. Here is my current code. If someone could point me in the right direction that would be great. Thanks setUp: class TestViews(TestCase): """ Testing of the views taken from the views.py file. All HTTP testing includes the base.html template as well as the view being tested to make sure everything is being tested as it would appear for a user """ def setUp(self): testing_user = User.objects.create_user( username='JohnSmith', first_name='John', last_name='Smith', email='johnsmith@email.com', password='RandomWord1' ) Booking.objects.create( user=testing_user, name='John Smith', email_address='johnsmith@email.com', phone='123654789', number_of_people='2', date='2022-10-20', time='19:00', table='Window', occasion='none' ) test: def test_add_booking(self): self.log_in() response = self.client.post('/bookings', {Booking: Booking}) self.assertRedirects(response, '/') -
Django View value not updating in template unless gunicorn.socket is restarted (setup: Django + Gunicorn + Nginx)
I have a little Django website running on Ubuntu 22.04 on Linode. It uses Nginx and Gunicorn to serve the Django page. Now I struggle to understand how to get the latest value for today's date & time from views.py upon a page refresh; it seems to get cached somewhere instead. My view contains the following: import datetime class MonitorView(LoginRequiredMixin, ListView): [...] def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['todayvalue'] = datetime.datetime.today() return context_data And my template contains: {% extends 'base.html' %} {% block title %} DummyTitle {% endblock title %} {% block content %} {{todayvalue}} {% endblock content %} When loading the template, this {{todayvalue}} prints "Aug. 11, 2022, 8:32 a.m.". And when refreshing the template again 10 minutes later, this {{todayvalue}} still prints "Aug. 11, 2022, 8:32 a.m.". When I restart gunicorn.socket (sudo systemctl restart gunicorn.socket), the values get updated. So it seems gunicorn doing some kind of caching. The thing that confuses me even more, is that other values in the views are updated fine in the template without requiring a gunicorn.socket restart. For example this value in the view: total_monthly_sent_volume = DailyStats.objects.filter(sg_date__gt=last_month).aggregate(Sum('sg_processed')) context_data['total_monthly_sent_volume'] = total_monthly_sent_volume is presented in the template in pretty much the same way, with … -
Django - Annotate with Case/When/Value and related objects
I have the two following models: class Post(models.Model): content = models.TextField() class Vote(models.Model): UP_VOTE = 0 DOWN_VOTE = 1 VOTE_TYPES = ( (UP_VOTE, "Up vote"), (DOWN_VOTE, "Down vote"), ) post = models.ForeignKey(Post, related_name="votes") vote_type = models.PositiveSmallIntegerField(choices=VOTE_TYPES) I would like to have a score property on Post that returns the sum of the values of the votes to that post, counting votes with UP_VOTE type as 1 and those with DOWN_VOTE as -1. This is what I’ve tried: # inside Post @property def score(self): return ( self.votes.all() .annotate( value=Case( When(vote_type=Vote.DOWN_VOTE, then=Value(-1)), When(vote_type=Vote.UP_VOTE, then=Value(1)), default=Value("0"), output_field=models.SmallIntegerField(), ) ) .aggregate(Sum("value"))["value__sum"] ) However, this yields None. More specifically, without dereferencing ["value__sum"], this returns {'value__sum': None}. Is using Case-When-Value the correct approach to my use case? If so, what’s wrong with the code I posted? Thanks in advance. -
Error while changing database engine to PostgreSQL
I got this error after changing the engine, the database is connected however it figured out my id field is a bigint, yet I specifically set it as a UUID field. class Cart(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) created_at = models.DateTimeField(auto_now_add=True) in terminal I get this error: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...LE "store_cart" ALTER COLUMN "id" TYPE uuid USING "id"::uuid enter image description here -
django restframework object-level-validation
These are my models : Test, Skillarea, question MODELS.PY : class Test(BaseModel): types = models.ManyToManyField( TestType, related_name='tests', ) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title class SkillArea(BaseModel): title = models.CharField(max_length=255) test = models.ForeignKey('Test', on_delete=models.PROTECT, related_name='skill_areas') questions = models.ManyToManyField( 'assessment.Question', related_name='skill_areas', ) def __str__(self): return self.title class Question(BaseModel): question_text = models.TextField() def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) class TestType(BaseModel): title = models.CharField(max_length=255) def __str__(self): return self.title I want to have an updateserializer for updating, but the field "type" in the Test model, only can be updated if there is no question in Skillarea model which related to Test model( has the same id as updating test, in its test field) I wrote these serializer and view but it doesnt know data['id'] which i used in validator and sends KeyError: 'id' serializer.py : class TestUpdateAPIViewSerializer(serializers.ModelSerializer): def validate(self, data): questions = SkillArea.objects.filter(test=data['id'], questions=None) if questions.exists(): raise serializers.ValidationError("You may not edit type") return data class Meta: model = Test fields = ( 'id', 'types', 'title', 'summary', ) Views.py : class TestUpdateAPIView(APIView): def patch(self, request, pk): test = Test.active_objects.get(pk=pk) serializer = TestUpdateAPIViewSerializer(instance=test, partial=True, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) -
Django Model custom User creates auth_user table in my app database when using multiple databases
I've created a new project from scratch. By default it uses the auth package for user and permission management. I am wanting to override the default User - using AbstractBaseUser. Having created migrations and executed them on my databases, the auth_user table resides in my application database - not the auth database. Is this expected behaviour? I was expecting - and I want the auth_user table to reside in the auth database. Is there a way to make the auth_user reside in the auth database? Create Project py -m venv venv venv\scripts\activate pip install django django-admin startproject core . py manage.py startapp acmeapp acmeapp/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class Foo(models.Model): foo_id = models.BigAutoField(primary_key=True) name = models.TextField() class Meta: db_table = 'foos' class AccountManager(BaseUserManager): """ The management class to handle user creation. """ def create_user(self, username, password=None): if not username: raise ValueError(_('The Username must be set')) user = self.model(username=username) user.set_password(password) user.save() return user def create_superuser(self, username, password=None): return self.create_user(username, password) class Account(AbstractBaseUser): """ The custom user model. """ username = models.CharField(max_length=40, unique=True) email = None USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['access_platforms', 'access_missions', 'access_rule_sets', 'access_mdsr'] objects = AccountManager() def __str__(self): return ''.join(c for c in self.username if … -
Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details
remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed This is the error i am getting when i am deploying my application on Heroku. I used a postgres database to store my data and when i am trying to deploy its giving me an error code DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','mca-blog-n.herokuapp.com'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CrabbyCoder.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] -
ModuleNotFoundError: No module named 'django_rest_passwordreset'
I have tried to Create a Django Superuser Account for my Project by using: 'python manage.py createsuperuser' on the command Prompt error occurred - ModuleNotFoundError: No module named 'django_rest_passwordreset' -
Nepali language written in html template of python not supporting
i was trying to display sales invoice in nepali language but it displays as enter image description here -
Raised Error when I run python manage.py in Django in linux vps
I've recently cloned my django project into a linux vps. I used python3.10 in my system but in vps I have python3.8 . Actually I installed all necessary packages for it and also created database. I have this error whenever I run commands start with python manage.py. Can any body help me to solve it? Maybe this error is for different python version? It also raised the error ModuleNotFoundError: No module named 'mysite' but I have no idea where I defined 'mysite' module. Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How to display the data that available in database using exist() query
I have this Code. But I need to display the values that exists in the database, Not like "It's Exists in the Database", I need to display the values of that given email_id. def post(request): if request.method == 'GET': value = example.objects.all() email_id = request.GET.get('email_id', None) if example.objects.filter(email_id = email_id).exists(): tutorials_serializer = exampleSerializer(value, many=True) return JsonResponse(tutorials_serializer.data, safe=False) Pls help me through it. -
Pytest fails on distinct with sqlite
I've a django system with drf where my views work fine, however, I'm unable to write a test for a view which has the following query: Object.objects.filter(...).order_by(...).distinct('comdate') . The problem is the distinct and it fails with the following error: #python -m pytest -k celler --pdb self = <django.db.backends.sqlite3.operations.DatabaseOperations object at 0x7f9dd7418a90>, fields = ['"tis_tislog"."comdate"'], params = [[]] def distinct_sql(self, fields, params): """ Return an SQL DISTINCT clause which removes duplicate rows from the result set. If any fields are given, only check the given fields for duplicates. """ if fields: > raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') E django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend env/lib/python3.9/site-packages/django/db/backends/base/operations.py:176: NotSupportedError entering PDB PDB post_mortem (IO-capturing turned off) > /home/user/prj5/env/lib/python3.9/site-packages/django/db/backends/base/operations.py(176)distinct_sql() -> raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') (Pdb) c PDB continue (IO-capturing resumed) [100%] short test summary info FAILED prj5/tests/test_tis_view.py::TestBillingUpdatedTransactionsView:: test_responds_ok_for_authorized_clients - django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend . The test itself is pretty simple: class SomeTestingView: @pytest.mark.django_db def testTisView(self, client: Client): client.get(URL) Is there any way how I could make this test running? -
How to link hierarhical data into another model in Django?
Consider the following hierarchical data. It can be 3 to 4 levels deep. I understand I can use existing packages like django-mptt or django-treebeard to create a tree data structure. Mercedes Consumer ModelA ModelB SUV ModelC Luxury ModelD Nissan Consumer ModelA ModelB SUV ModelC Now let's say I have another model called Battery. A battery can be compatible with multiple models for different market segments by different car vendors. So what I want to do is assign this battery to one or more compatible models above. I'm not sure how to accomplish this linkage in Django. Would it just be a ManytoMany field to the hierarchical model? Some pseudo-code would help. class Battery(models.Model) name = Charfield(max_length=50) compatible_models = ???? I would also like to know how a query would be written. For example, I want to query all the battery that are compatible with ModelA by Mercedes, etc. -
Getting Fatal Python error running Django on Apache
I am trying to deploy my Django app through a Digital Ocean droplet server using Ubuntu 22.04 and MySQL. When I try to run the app through Apache, I get a "Forbidden Access" message. I checked the error log and see this error (I have removed my username from the directories): Permission denied: mod_wsgi (pid=983): Unable to stat Python home /home///mm_venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home///mm_venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home//mm_venv' sys.base_exec_prefix = '/home//mm_venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '//mm_venv' sys.exec_prefix = '//mm_venv' sys.path = [ '/home//mm_venv/lib/python310.zip', '/home//mm_venv/lib/python3.10', '/home//mm_venv/lib/python3.10/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I have checked the etc/apache2/sites-available files, and this is what I have as the python path: WSGIDaemonProcess mommind_new python-home=/home//mommind_new/mm_venv python-path=/home//mommind_new These look correct to me, so I am really at a loss. Can someone please help me … -
In django how to remove a string value storing parent id from child table when the parent is deleted in M2M relationship?
I am storing some values from the parent in the child table as csv in a character field. Problem is when the parent is deleted, though the m2m relation is deleted, the value that was selected in the child table string remains as it is. How do I take care of it? Will I have to run a post_save method on the parent to access all the children's string and remove the value from there. There will be a lot of performance issues. eg: class Child1(models.Model): name = models.CharField(max_length=30, unique=True) class Teacher1(models.Model): name = models.CharField(max_length=30, unique=True) children = models.ManyToManyField( Child1, blank=True,null=True, related_name='children') child_list = models.CharField(max_length=500, unique=True) Above, the child_list is populated with the child names as CSV, when the children are selected in Teacher1Admin in admin.py. But when any child is deleted, though the corresponding relationships are deleted, the name of the child remains in the Teacher table in the child_list. How can this be removed, whenever the Child1 table is edited/ child deleted, without much performance overhead? -
Add UID or Unique ID in Wagtail/Django
So my question was how I can generate a random UID or slug for my CMS. If I use the default id which is coming from API v2 people can easily guess my next post URL easily. Is there any way to add a unique slug/ID/UUID for my wagtail CMS? -
Django Rest Framework with gunicorn gevent
I'm using Django Rest Framework(class views), with configs gunicorn --workers=5 --worker-class=gevent --worker-connections=100 When interacting with ORM, it gives You cannot call this from an async context - use a thread or sync_to_async Can someone help me with this. -
what way can i fix django DB migration error without deleting migration files
what is the best way to fix this kind of DataBase Errors without having to delete my db and migration files and starting to enter data from scratch? django.db.utils.IntegrityError: The row in table 'store_product_category' with primary key '1' has an invalid foreign key: store_product_category.category_id contains a value '1' that does not have a corresponding value in store_category.id. while inspection the sqlit DB i observe that there is a mismatch in the IDs of the store_product_category and store_category.id. is there anyway i can modify the id directly on the DB, i dont want to start deleting database files and migrations -
Cleaning a specific field in Django forms.Form?
I have a Django form like this. class TransactionForm(forms.Form): start = forms.DateField() end = forms.DateField() I wanted to change the value before running validation: def clean_start(self): start = sef.cleaned_data.get('start') return bs_to_ad(start) //This function returns date in 'YYYY-MM-DD' format The problem is that this method runs in forms.ModelForm object but doesn't in forms.Form object. Help appriciated. Thank You. -
How to maintain the log name for an unhandled exception in Django
I am a bit lost about the logging topic. I declare all my loggers with logger = logging.getLogger(__name__) so when logging I have this info available. However, if an unhandled exception happens, I know that Django logs the exception with log name as django.request and so on because of this https://docs.djangoproject.com/en/4.0/ref/logging/#loggers, but what if I would like to use the log name I have declared? I know I am not actually calling the logger when the exception happens, but I would like to know the originary module for the exception. Any ideas? Thanks! -
Django Simple Jwt Authenticate multiple models
I'm working on a project that includes users communicating with devices( rpi's) via websockets. They only way I can think to make it more secure so other's can't access a websocket 'room' they aren't allowed to be in, is to have a separate way for the rpi's to login like users do. Then somehow check if they are authenticated when connecting to a socket room. Any tips for how to do this? -
Django - DateTime Model field saving time as midnight
I'm experiencing an unusual and frustrating challenge: I have formatted the date/time input inside of the form so it knows what format I'm sending it in, the form validates, and there are no challenges with the data, however when it's saving it saves the time as midnight no matter what way I plug it in. The failing value is sample_date, in the below model. Database Pic: https://imgur.com/yUObctR Model class WaterTest(models.Model): name = models.CharField(max_length=200) sample_date = models.DateTimeField() sample_address = models.TextField() mailing_address = models.TextField(blank=True, null=True) sample_point = models.CharField(max_length=200) job_site = models.ForeignKey(JobSite, on_delete=models.CASCADE, blank=True, null=True) template = models.ForeignKey(Template, on_delete=models.CASCADE, blank=True, null=True) collected_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) def __str__(self): return f"{self.name}: {self.sample_address}" class Meta: verbose_name = 'Water Test' verbose_name_plural = 'Water Tests' Form class CreateWaterTestForm(forms.ModelForm): sample_date = forms.DateField(input_formats=['%m/%d/%Y %H:%M']) class Meta: model = WaterTest fields = ['name', 'sample_date', 'sample_address', 'mailing_address', 'sample_point', 'job_site', 'template', 'collected_by'] create_report.html <div class="col-md-6"> <div class="mb-3"> {{ form.sample_date.errors }} <label class="form-label" for="{{ form.sample_date.id_for_label }}">Sample Date/Time <span class="text-danger">*</span></label> {{ form.sample_date|add_class:"form-control" }} </div> </div><!-- Col --> <script> $("#{{ form.sample_date.id_for_label }}").datetimepicker({ {% if THEME == 'demo2' %}theme: 'dark',{% endif %} format: 'm/d/Y H:i' }); </script> DateTime picker: https://xdsoft.net/jqplugins/datetimepicker/ GitHub: https://github.com/varlenthegray/wcadmin/tree/dev -
Fetch relations from ManyToMany Field using Annotation
I have my database here. Where I have 2 users connected to one instance of ChatRoomParticipants with a ManyToManyField. I'm trying to get list of related users from a ManyToMany Relation Field from ChatRoomParticipants where I don't want to show the currently authenticated user in the list with other fields i.e room present in the model. Considering user f4253fbd90d1471fb54180813b51d610 is currently logged in and is related to all ChatRooms via ChatRoomParticipants model. Things I've tried but couldn't get the desired output chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values_list('user__chatroom_users__user__username', 'room').distinct()) ##### chatrooms = ChatRoomParticipants.objects.filter(user=user).annotate(user!=User(user)) #### chatrooms = Chatrooms.objects.filter(user=user) rooms = chatrooms.values('user__chatroom_users__user__username').distinct().exclude(user__chatroom_users__user__username=user) I want an output like [ { 'user': '872952bb6c344e50b6fd7053dfa583de' 'room': 1 }, { 'user': '99ea24b12b8c400689702b4f25ea0f40' 'room': 2 }, { 'user': 'eecd66e748744b96bde07dd37d0b83b3' 'room': 3 }, ] models.py class ChatRoom(models.Model): name = models.CharField(max_length=256) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey( User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT)