Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_filter, integrate form in classview
I have a Listview class that show a table (working), I also have a django_filter for filtering the table (working). I want a button in template Listview , that open the django_filter_form ( not working, only show submit buttom), how do that ? views.py from django.shortcuts import render from django.views.generic import ListView from django.views.generic.edit import FormView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Cmsexport from .filters import CmsFilter from django.contrib.auth.decorators import login_required class Cms(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport template_name = 'table.html' context_object_name = 'cms' paginate_by = 10 def get_queryset(self): queryset = super().get_queryset() self.filterset = CmsFilter(self.request.GET, queryset=queryset) return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.filterset.form return context filters.py: from django_filters import FilterSet from .models import Cmsexport class CmsFilter(FilterSet): class Meta: model = Cmsexport fields = { 'name': ['icontains'], 'state_text': ['icontains'], 'is_virtual': ['icontains'], } urls.py: from django.urls import path from django.views.generic import TemplateView from . import views from .views import Cms urlpatterns = [ path('', views.dashboard, name='dashboard'), path('table/', views.table_view, name='table_view'), path('cms/', Cms.as_view(), name='cms'), path('filters_form/', TemplateView.as_view(template_name='filters_form.html'), name='filters_form'), path('search/', views.search, name='search'), ] template/table.html: {% extends 'base.html' %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} {% include 'filters_form.html' %} <a href="{% url 'filters_form' … -
django-corsheaders, No 'Access-Control-Allow-Origin
Let me appreciate your help in advance. I deployed FE and BE in different servers on different domains. django-corsheaders is in use in django to deal with CORS, but the response does not include Access-Control-Allow-Origin. I searched and tested out a lot but nothing worked. Also, I read this article "https://developer.mozilla.org/ja/docs/Web/HTTP/CORS" I understood the logic, so I couldn't get why my case was not working. The weirdest point is that some requests to specific endpoints return a response with Access-Control-Allow-Origin which makes me confused. Thank you for your advice. DJANGO settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddtriede', //tried to set corsheaders.middleware above here 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = getenv( 'CORS_ALLOWED_ORIGINS', 'http://localhost:3000,http://127.0.0.1:3000' ).split(',') CORS_ALLOW_CREDENTIALS = True Here is okay case response and request Response Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: "here is FE origin" Allow: POST, OPTIONS Cache-Control: public, max-age=0, must-revalidate Content-Length: 37 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Fri, 08 Sep 2023 04:39:17 GMT Referrer-Policy: same-origin Server: Vercel Strict-Transport-Security: max-age=63072000; includeSubDomains; preload Vary: Accept, origin X-Content-Type-Options: nosniff X-Frame-Options: DENY X-Vercel-Cache: MISS X-Vercel-Id: syd1::iad1::ssnw2-1694147954133-6c4eee9047a5 Request :authority: "here is FE origin" :method: POST :path: /api/jwt/verify/ :scheme: https Accept: */* Accept-Encoding: gzip, deflate, … -
django-crontab not working for background tasks on Django app
I am developing a django application in which I want to perform some automatic tasks from time to time. I was looking for different ways to perform my task and I found some solutions like using celery, django-background-tasks or django-crontab. I discarded the celery option because it would complicate a lot the infrastructure of the project and the idea is to keep it as simple as possible. For that reason, I wanted to try django-crontab. I based on this video and made a test task to test this library, but I do not get the desired results. This is the test task: import datetime def test_task(): file = open("test_output.txt", "a") file.write(str(datetime.datetime.now())+"\n") file.close() The previous code is on a cron.py file. As the video and the documentation says, add the necessary in the setting.py file: INSTALLED_APPS = [ 'validator', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'validator.cron.test_task') ] The desired result is a test_output.txt file, with datetimes with ranges of 1 minute apart. I don't know what I'm doing wrong or what I need to do to make it work properly. If someone knows another simple way to automate tasks in django, … -
Django Model Validation to ensure a Object can't be Child of itself and parent of its children/ grand Children
I have a case where I have a WBS, which has a parent_wbs field as Foreign key. I am trying to ensure that User don't keep adding child of a WBS so a Limit of Max 4 dept. Secondly I also want to ensure, that on edit I am not saving an object as parent of itself or an object shouldn't be set as parent who is also child/ grand child of current Object. class WBS(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.CASCADE) num = models.IntegerField(default=0) parent_wbs = models.ForeignKey('WBS', on_delete=models.CASCADE, null=True, blank=True, related_name='children') created_on = models.DateTimeField(auto_now_add=True) created_by = models.IntegerField(blank=True, default=0) modified_on = models.DateTimeField(auto_now=True) # This field will be automatically updated on each save modified_by = models.IntegerField(blank=True, default=0) # You can specify your own logic for updating this field def is_valid_descendant(self, parent_wbs, max_depth=4): """ Check if this WBS is a valid descendant (child or grandchild) of the provided WBS, and also ensure that the depth of the relationship is not greater than max_depth. """ current_wbs = self depth = 0 while current_wbs and depth <= max_depth: if current_wbs == parent_wbs: return False current_wbs = current_wbs.parent_wbs depth += 1 return True def __str__(self): return self.name Here is my form validation class WBSForm(forms.ModelForm): … -
SerializedMethodField vs overriding save() method : What is the best choice to deal with calculated fields in django?
I develop a django app with a lot of calculated properties for business logic. For example, let us take model Task, that is just an ordinary task for students. It is necessary to obtain the number of users that likes this task, that solved it, attempted to solve it, etc Now I am using to approaches to this challenge. The first is to use SerializedMethodField solved_users_number = serializers.SerializerMethodField(method_name='get_solved_users_number') def get_solved_users_number(self, object): #business logic return 42 The second is to provide a field in the model I use and update it every time the model changes. Overriden save() method suits for such purposes. def save(self, *args, **kwargs): if not self.id: self.solved_users_number = 0 else: self.solved_users_number += 1 return super(Task, self).save(*args, **kwargs) What is the best choice to deal with calculated fields in django? I tried both and still not sure -
Ajax not displaying data on a web page in my Django app--and instead shows this >>> <cart.cart.Cart object at 0x0000014D574B3AD0>
I'm following VeryAcademy's Django E commerce tutorial on YouTube and I encountered and issue. I followed the tutorial precisely and reach the Ajax part where we pass the add_to_cart data to the cart page to be displayed--and instead of seeing the data--I see this <cart.cart.Cart object at 0x0000014D574B3AD0> what is this? I'm supposed to see the product details of the current items in cart--not this. Here is my Ajax code. I'm running Django: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); $(document).on('click', '#add_button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'inventory:single_product_add_to_cart' %}", data: { productid: $('#add_button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: csrftoken, action: 'post' datatype: 'json', }, success: function (json) { document.getElementById("basket-qty").innerHTML = json.qty }, error: function (xhr, errmsg, err) {} }); }) settings.py """ Django settings for ds_mp project. Generated by 'django-admin startproject' using Django 4.2.3. … -
Django AttributeError: 'ForeignObjectRel' object has no attribute 'through'
I have two django apps, app1 and app2. app1 has a ScenesConfig table, and then app2 has a Task. Their definitions are as follows: class ScenesConfig(models.Model): id = models.AutoField(auto_created=True, primary_key=True) name = models.CharField(max_length=128, null=True) class Meta: db_table = 'scenes_config' from django.db import models from app_1.models import ScenesConfig class Task(models.Model): task_name = models.CharField(max_length=100, db_index=True) source_type = models.CharField(max_length=100, default="") scenes = models.ForeignObject(ScenesConfig, from_fields=['source_type'], to_fields=['id'], null=True, related_name='task_scenes_config', on_delete=models.DO_NOTHING) def __str__(self): return self.task_name At this point, I conducted my first migration and there were no errors. When I added a blank=True attribute to the scenes field of the task table the next time, an error occurred during the migration: Applying app_2.0003_auto_20230908_0256...Traceback (most recent call last): File "/Users/donghao/test/test_migations/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 202, in handle post_migrate_state = executor.migrate( File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/migration.py", line 129, in apply … -
Model's ImageField returning different results in viewset vs function-based view
I have a model for representing user ratings in a sample app I'm building using Django Rest Framework, and I'm weirdly getting different results for the ImageField depending on the kind of view I use to request the data. Here is my model: class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) rating = models.IntegerField() review = models.CharField(max_length=500) recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE, related_name='ratings') published_date = models.DateField(default=date.today) updated_date = models.DateField(default=date.today) photo = models.ImageField(upload_to='images/ratings/', blank=True) I have the following Viewset set up for this model: class RatingViewSet(viewsets.ModelViewSet): serializer_class = RatingSerializer lookup_fields = ('id', 'recipe') filter_backends = [DjangoFilterBackend] filterset_class = RatingFilter queryset = Rating.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(updated_date=date.today()) and a separate simple function-based view to grab just the latest rating for the logged in user: @api_view(['GET']) def UserRating(request): recipe_id = request.query_params.get('recipe_id') try: rating = Rating.objects.filter(recipe=recipe_id, user=request.user).latest('updated_date') serializer = RatingSerializer(rating) return Response(serializer.data, status=status.HTTP_200_OK) except Rating.DoesNotExist: return Response({}) When I use the viewset to request the Ratings objects, the photo field is represented in each object like this: "photo": "http://127.0.0.1:8000/media/images/ratings/SuperKofBros64.jpg" but when I use the function-based view the field doesn't show the server address, like this: "photo": "/media/images/ratings/SuperKofBros64.jpg" Why would this field show up differently depending on the kind of view I'm using? Is there a … -
Google Cloud: Access to image has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I deployed a website on Google Cloud via Cloud Run. The site uses Django and Webpack. The resources are automatically loaded to a Google Cloud Storage bucket. However, when I try to load the website some resources are not loaded correctly: Access to image at 'https://storage.googleapis.com/<bucket-name>/bcf8ff28514bad926b0c.png' from origin '<URL of my website>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If I try to access the request just by copy-pasting the URL into the browser it works fine (I can see the image). By looking at the Request Header for the resources that do not load correctly, their Origin is set to the URL of my website, e.g. https://example.com. The resources that do load correctly don't have Origin in the Request Header. Moreover, this issue only appears on Chrome and Safari but not on Firefox. When I inspect the Request Header on Firefox, the origin is actually set to https://storage.googleapis.com/ (instead of https://example.com), which I assume it's the reason why the resources load correctly. I guess there are two ways to solve the problem, though I don't know what solution should be preferred and how to implement it: Find a way to set … -
Login method in DJango throwing table or view does not exist
I am trying to customize the login by writing backend authentication, but login is throwing error "table or view does not exist". when I am running code below error was throwing return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-00942: table or view does not exist settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', # This is the default that allows us to log in via username 'App_CPL.authentication.AuthBackend' ] authentication.py from django.contrib.auth.models import User from App_CPL.models import GainsUsers class AuthBackend: """ Custom authentication backend. Allows users to log in using their email address. """ def authenticate( request, username, password): """ Overrides the authenticate method to allow users to log in using their email address. """ try: print("hit authenticate model"+ username + password) user = GainsUsers.objects.get(user_id=username) print(user) print("password "+password) print(user.real_name) if str(user.real_name)==password: print("hit authenticate model"+ str(user)) return user return None except User.DoesNotExist: return None def get_user(self, user_id): """ Overrides the get_user method to allow users to log in using their email address. """ try: return GainsUsers.objects.get(pk=user_id) except User.DoesNotExist: return None views.py def Login_user(request,Username1,Password1): print(Username1) print(Password1) Gains_Users=AuthBackend.authenticate(request,Username1,Password1) print("back to main funtion"+str(Gains_Users)) if Gains_Users is not None: print("main if condition") login(request,Gains_Users) return JsonResponse(str('1'),safe=False) else: return JsonResponse(str('0'),safe=False) -
Error when running install pyhon3-dev in docker container
I am trying to set up a Python docker container, when I run the command "docker-compose up" to build the Dockerfile it throws me this error message below Trying to build the image produces the following error: 0 16.66 debconf: delaying package configuration, since apt-utils is not installed #0 16.69 Fetched 35.2 MB in 9s (3993 kB/s) #0 16.71 Selecting previously unselected package libpython3.11-minimal:amd64. (Reading database ... 6705 files and directories currently installed.) #0 16.71 Preparing to unpack .../libpython3.11-minimal_3.11.2-6_amd64.deb ... #0 16.71 Unpacking libpython3.11-minimal:amd64 (3.11.2-6) ... #0 16.78 Selecting previously unselected package python3.11-minimal. #0 16.78 Preparing to unpack .../python3.11-minimal_3.11.2-6_amd64.deb ... #0 16.78 Unpacking python3.11-minimal (3.11.2-6) ... #0 16.92 Setting up libpython3.11-minimal:amd64 (3.11.2-6) ... #0 16.93 Setting up python3.11-minimal (3.11.2-6) ... #0 17.01 [Errno 13] Permission denied: '/usr/lib/python3.11/__pycache__/__future__.cpython-311.pyc.140584693250096'dpkg: error processing package python3.11-minimal (--configure): #0 17.02 installed python3.11-minimal package post-installation script subprocess returned error exit status 1 #0 17.02 Errors were encountered while processing: #0 17.02 python3.11-minimal #0 17.04 E: Sub-process /usr/bin/dpkg returned an error code (1) ------ failed to solve: executor failed running [/bin/sh -c apt-get update && apt-get install -y python3-dev]: exit code: 100 My requirements.txt file looks like: amqp==5.1.1 asgiref==3.7.2 asttokens==2.4.0 async-timeout==4.0.3 attrs==23.1.0 backcall==0.2.0 beautifulsoup4==4.12.2 billiard==4.1.0 bs4==0.0.1 celery==5.3.1 certifi==2023.7.22 … -
i cant send query_set as context argument to the render method
im trying fetch data from db and display it into the page, i get the data properly form db but cant display it. view.py from books.models import Book from django.shortcuts import render def query(request): query_set = Book.objects.all() return render(request, 'books.html', {'books', query_set}) books.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Mostafa Saleh</h1> <p>first Django web application!</p> <ul> {% for book in books %} <li> {{ book.name }}</li> {% endfor %} </ul> </body> </html>``` error message(debug_toolbar): TypeError at / context must be a dict rather than set. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.5 Exception Type: TypeError Exception Value: context must be a dict rather than set. i used list method to convert the query_set to dict but it wont work and get me another error: (debug_toolbar) unhashable type: 'list' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.5 Exception Type: TypeError Exception Value: unhashable type: 'list' -
How can I store multiple values in one field of a Django model? Like an array, list, etc
I currently have a "Financing" django model which currently has multiple attributes like amount, date and so on, on top of that I have a "Quota" model that has similar values and a foreign key (many-to-one) relationship with the Financing model (as in multiple quotas per financing). My question is, is there a way to store said quotas in an array-like field so I can easily access them from the parent financing for referencing later? I would love to visualize them in their respective "Financing" tab in the admin panel or to fetch with a for loop like you can do with regular python arrays. Here is the simplified code in case it helps: class UserFinancing(BaseModel): amount = models.DecimalField( _("Amount"), max_digits=18, decimal_places=2, null=True, blank=True, ) periods = models.IntegerField( _("Weeks"), default=6, null=True, blank=True ) num_of_quotas = models.IntegerField( _("Number of quotas"), default=6, null=True, blank=True ) is_completed = models.BooleanField( _("Is completed?"), default=False ) class Meta: verbose_name = _("User Financing") verbose_name_plural = _("User Financings") class UserQuota(BaseModel): user_financing = models.ForeignKey( UserFinancing, verbose_name=_("User financing"), related_name='user_quotas', on_delete=models.CASCADE ) amount = models.DecimalField( _("Amount"), max_digits=18, decimal_places=2, null=True, blank=True, help_text=_("Amount of the financing option") ) date_payment = models.DateField( _("Date payment"), help_text=_("Max date to be payed") ) date_start = models.DateField( _("Date … -
Deploy Django app to Python Anywhere through GitHub
I am currently trying to set up a deployment pipeline for my django app to pyhton anywhere. But the github Webhook recieves a 301 and I don't understand why... "Last delivery was not successful. Invalid HTTP Response: 301" I followed the instructions from this tutorial: https://digitalshyna.com/blog/how-to-deploy-django-apps-to-python-anywhere-through-github/ I added the update url: path('update_server/', views.update, name='update'), this is my update view: @csrf_exempt def update(request): if request.method == "POST": try: # Log the incoming request logger = logging.getLogger('webhook_logger') logger.info("Webhook POST request received") # Perform the code update repo = git.Repo('mayapp.pythonanywhere.com') origin = repo.remotes.origin origin.pull() # Log a success message message = "Updated code on PythonAnywhere" logger.info(message) return HttpResponse(message) except GitCommandError as e: # Log a Git error and return an error response error_message = f"Git Error: {str(e)}" logger.error(error_message) return HttpResponseServerError(error_message, status=500) else: return HttpResponse("Couldn't update the code on PythonAnywhere") GitPython is installed in my Pythonanywhere virtualenv. I created the deploy key and added it to my repository on github. I created a second ssh-key and added it to my github account, I added both keys to the ssh-agend on pythonanywhere. https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent When I access the route directly with Postman I see "Couldn't update the code on PythonAnywhere" Status Code 200 OK My log … -
Running Raw sql query in django signal giving is throwing error
I am trying to run a CTE in my django application I have a model class WorkflowStepDependency(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) step = models.ForeignKey('WorkflowStep', on_delete=models.CASCADE, related_name='step') step_dependency = models.ForeignKey('WorkflowStep', on_delete=models.CASCADE, related_name='step_dependency') step_dependency_status = models.ForeignKey('WorkflowStepStatus', on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.step}'s dependency on {self.step_dependency}'s {self.step_dependency_status}" class Meta: ordering = ['created_on'] I am trying to run a cte in one of my signals @receiver(post_save, sender=WorkflowStepInstance) def workflowStepInstanceUpdated(sender, instance, created, **kwargs): table_names = connection.introspection.table_names() print(table_names) if not created: with connection.cursor() as cursor: cursor.execute(""" WITH hierarchy AS ( SELECT step ,step_dependency ,1 AS lvl FROM Projects_workflowstepdependency WHERE step = %s ) ,lvls AS ( SELECT lvl ,step FROM hierarchy GROUP BY lvl ,step ) """, [instance.workflow_step] ) This is giving me error saying -
How to query models with a related model in a onetoone relationship in Django?
Models from the one-to-one Django docs: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return f"{self.name} the place" class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) How would I query "Place objects with name 'foo' or Place objects that have a Restaurant"? It needs to be one queryset, so I can return it to django-ninja for an API. -
Not able to add new instance of model, not even using Django Admin panel
For several months I am programing a web app using Django for learning purposes. I created class me function based view to create new entries of many model but for this one something is off. First I was unable to add using CBV, then I switch to function base view. I tried using forms.py or directly with template but every time I get clean console, good redirect but no new entry. Then I tried to create it just using Admin panel but i would get something like "The performance review “PerformanceReview object (1e549e2c-4b3d-4030-9007-b889265ed908)” was added successfully.", but the list of objects was still empty. As this message is basically a link when i try to follow it i get this message: "Performance review with ID “1e549e2c-4b3d-4030-9007-b889265ed908” doesn’t exist. Perhaps it was deleted?" -I did 'makemigrations' and 'migrate' -While this was happening rest of the app still worked as expected -Admin.py has model registred -All fields are correctly presented within Admin form -Validators work correctly from django.contrib import admin from . models import PerformanceReview # Register your models here. admin.site.register(PerformanceReview) I don't think that the rest of code is relevant as the Admin panel not working is the thing that puzzles … -
Django - Necessary to create own account adapter?
I am using django-allauth. I want to make use of the send_mail function that is found inside allauth.account.adapter import DefaultAccountAdapter. Is it necessary for me to create my own adapter that simply inherits the allauth DefaultAccountAdapter and what is the purpose if I am not modifying anything inside it? adapters.py from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): pass myAdapter = MyAccountAdapter() settings.py ACCOUNT_ADAPTER = 'api.adapters.MyAccountAdapter' views.py from .adapters import * myAdapter.send_mail(...) -
How to Create and Save Database Objects for Django Tests in the Same Test Case?
I'm working on Django tests, and I have a base class for my tests where I define some common variables and methods. I want to use fixtures or a similar approach to create database objects and use their attributes in the test data. However, I encountered an issue where the objects created in the base class are not available in the test class. Here's my simplified test structure: test_base.py: class BaseTestCases: class BaseEndpointTest(APITestCase): @classmethod def setUpClass(cls): super().setUpClass() # Create users and set up API clients @classmethod def tearDownClass(cls): # Delete users super().tearDownClass() # Other methods... def create(self, data, main_user=True): # Create API request # ... # Other code in test_base.py test_cities.py: class TestCities(BaseTestCases.BaseEndpointTest): endpoint = "cities" # Create a city object using create_city() p_key = create_city().pk print(Country.objects.all()) # Test data data = {"name": random_string(), "country": p_key} The problem is that when I print Country.objects.all() in test_cities.py, it contains the result of create_city(), but when I print the same in test_base.py using the create method, it doesn't contain the newly created record. I believe this is because the objects created in the base class are not being saved to the test database. How can I create and save objects in the … -
Use other table & column names for authenticate function in django
I have pre existing table with table name='XYZUsers' which columns names as user_id, XYZ_password. I want use authenticate function in django by passing user_id, XYZ_password instead of using normal username , password. How I can acheive this? Models.py class XYZUsers(models.Model): user_id = models.CharField(primary_key=True, max_length=30) XYZ_password = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'xyz_users' views.py def Login_user(request,Username,Password): print(Username) print(Password) try: PYX_Users=XYZUsers.objects.get(user_id=Username) except Exception as e: print('user not avaialble') PYX_Users=authenticate(request,PYX_Users.user_id=Username,PYX_Users.XYZ_password=Password) print(PYX_Users) if Gains_Users is not None: auth_login(request,PYX_Users) return JsonResponse(str('1'),safe=False) else: return JsonResponse(str('0'),safe=False) -
Python's time.sleep() function freezes Postgres DB time in Django tests
I need to make a pause in my Django project's test (I use pytest-django) and time.sleep() kind of works but with a strange side effect. It pauses the execution of the code as expected but it also stops Postgresql's "in-DB clock" that is not desired. Here is an example: from pytest import mark, fixture, raises from django.db import connection from django.utils import timezone import sys, datetime as dt @mark.django_db def test_db_time (): print('Code time before:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() before:', t_before := cursor.fetchone()[0], file = sys.stderr) sleep(1.56) print('Code time after:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() after:', t_after := cursor.fetchone()[0], file = sys.stderr) assert t_before != t_after, 'I need a nap!' When run this test with pytest, I get the next output: ========================================= test session starts ========================================= platform linux -- Python 3.10.1, pytest-7.4.0, pluggy-1.0.0 django: settings: pms.settings (from ini) rootdir: /home/nikita/files/projects/pms/dev configfile: pyproject.toml plugins: django-4.5.2 collected 1 item sis/tests/db/triggers/test_answer.py F [100%] ============================================== FAILURES =============================================== ____________________________________________ test_db_time _____________________________________________ def test_db_time (): print('Code time before:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() before:', t_before := cursor.fetchone()[0], file = sys.stderr) sleep(1.56) print('Code time after:', … -
How can i distinguished request actions in a serializer DRF Django
class EmailSerializerU(serializers.ModelSerializer): customlink = serializers.SerializerMethodField() class Meta: model = Email fields = ['id','owner','address','type','primary','customlink'] def get_customlink(self, instance): #Here Logic IF Action=List then A) IF Action=GET THEN b) full_url = ''.join(['http://', get_current_site(req).domain])+'/emails' return full_url In the def_get_customlink function i am trying to set the full_url depending on the action of the URL/API. How can i access this value? Is the context/the request somehow available? List Actions have a link to singel object url: emails/3 Get/View Actions have a link to the list of objects url: emails/ tried self.action, didnt work. self.action leads to 'EmailSerializer' object has no attribute 'action' tried self.context, but it shows an url not an action like in views, where self.action is set. req=self.context['request'] print(req) GET /emails/ HTTP/1.1" 200 21865 GET /emails/4/ HTTP/1.1" 404 15897 -
How to display child elements in a comment system
I'm implemeneting a comment system where a users can reply to each others comments. To do this I'm using MPTT and following along with this very good tutorial (https://www.youtube.com/watch?v=j7vj4k13xDY&list=WL&index=5). The problem I've come across is that I want to load the replies to comments dynamically, when someone presses a button, rather than load all the replies to every comment when the page first loads. The way the tutorial shows how to load comment replies is like so: {% if comments %} {% load mptt_tags %} {% recursetree comments %} #Use comment objects here, e.g {{ comment.description }} {% if not node.is_leaf_node %} #Displays the child elements <div class="pl-2">{{ children }}</div> {% endif %} {% endrecursetree %} This works fine when I was loading all the comments and replies at once, however as I'm now moving to loading the replies when a user clicks a button on the parent comment I'm having problems. I'm trying to use HTMX to load in the replies once this button is clicked but am having trouble accessing all the children. It's hard to figure out what to do as it just magically "works" with using the {{ children }} variable above. When I try and … -
Django Treebeard on how to use 'Position' and 'Relative to' in a customized form
I'm using treebeard and the materialized path trees to give tech support the ability to create troubleshooting guides. Each parent node will be the title of the guide and descendants of that parent node will be the steps to take. I've made a model to inherit from MP_Node with a few additional fields that I will be using to help create these guides such as name, description, step_type, etc. The form I've made for this is inheriting from the MoveNodeForm class which allows you to define the Position and Relative to fields that come with the class. It seems to me that the only way to access those fields is to call the entire form in the template like so {{ form|crispy }}. I would like to be able to use my form in a way where im calling each field one at a time so that I can make custimizations such as a RadioSelect for my step_type field, otherwise it will display as a dropdown in the form. Is there a way to access these fields Position and Relative to without calling the entire form? Can I not access those fields in my customized form class so that I … -
Arrows for carousel
I have the carousel with images from django <section id="container-id" class="container"> <div class="carousel"> <div class="slider"> {% for ph in photos %} <img id="{{ph.pk}}" src="{{ph.photo.url}}" class="slide"> {% endfor %} </div> <div class="slider-nav"> {% for ph in photos %} <a href="#{{ph.pk}}"></a> {% endfor %} </div> </div> </section> how can i add arrows for left and right slides? i tried bootstrap but it didnt work, so im here... :)