Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send message using Django Channels outside consumer class getting RuntimeError('Event loop is closed')
I am trying to send a message to the frontend outside of a consumer class in Django Channels. What I am trying to do is, the client will send a file via http, thus hitting a view class, and the view class will call the consumer class and send update to the client via websocket. This is my view class GroupListView(BaseListView): name = "Group list view" model = Group serializer = GroupSerializer def get(self, request: Request): if "bulk" in request.query_params and request.query_params["bulk"]: async_to_sync(get_channel_layer().group_send)("test_lobby", {"type": "chat.message"}) return self.send_response(False, "pending", {}) This is my consumer class TestConsumer(WebsocketConsumer): def connect(self): self.room_name = "lobby" self.room_group_name = "test_lobby" async_to_sync(self.channel_layer.group_add( self.room_group_name, self.channel_name )) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def chat_message(self, event): # Send message to WebSocket self.channel_layer.send(text_data=json.dumps({"message": 'hello world'})) I am following from the Django Channels documentation: https://channels.readthedocs.io/en/stable/topics/channel_layers.html#using-outside-of-consumers However, I am getting this error HTTP GET /api/v2/groups/?bulk=true 200 [0.05, 127.0.0.1:56152] Task exception was never retrieved future: <Task finished name='Task-28' coro=<Connection.disconnect() done, defined at /python3.9/site-packages/redis/asyncio/connection.py:819> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "/python3.9/site-packages/redis/asyncio/connection.py", line 828, in disconnect self._writer.close() # type: ignore[union-attr] File "/python3.9/asyncio/streams.py", line 353, in close return self._transport.close() File "/python3.9/asyncio/selector_events.py", line 700, in close self._loop.call_soon(self._call_connection_lost, None) File "/python3.9/asyncio/base_events.py", line 746, … -
Django admin. How to redirect the link on the model class to open the first object?
I have model in django it is 'Slogan' model. I restricted it to only 1 object from admin: def has_add_permission(self, request): if len(Slogan.objects.all()) == 1: return False return True My view in home page will create the first object on page load if there is no object slogan in the database. What I want to do is when I open admin and click on the left side where Slogan is to open the first object of that class directly instead of seeing a list with objects on the right and select it from there. I tried get_url() method from admin but this seems to be for the specific objects. -
My list gets suddenly empty and I can't restore it
I'm newbie in django and I was trying to construct a site in which the user can take a quiz. In a simpler version of that, I wanted just the questions to be displayed in random order, one after another(when the user presses a button) and when all the questions have been displayed to return to the main page, where there is a link "take the test". I know that it certainly isn't the most efficient way to do it, but I want to know what is wrong with my code. urls.py: path('start',views.startquiz,name='start'), path('test/<int:pk>/<int:index>',views.TakeQuizView.as_view(),name='test'), views.py: def startquiz(request): questions=list(Question.objects.all()) question=random.choice(questions) pk=question.id return redirect(reverse('quiz:test',args=(pk,1))) class TakeQuizView(LoginRequiredMixin,View): questions=list(Question.objects.all()) n=len(questions) def get(self,request,pk,index): question=Question.objects.get(id=pk) self.questions.remove(question) ctx={'question':question,'index':index,'n':self.n} return render(request,'quiz/test.html',ctx,) def post(self,request,pk,index): if index<self.n: question=random.choice(self.questions) pk=question.id return redirect(reverse('quiz:test',args=(pk,index+1))) else: self.questions=list(Question.objects.all()) return redirect(reverse_lazy('quiz:main')) ` Whenever I take the quiz for the first time, all works fine, and after all questions have been displayed, it returns to the main page. However, if I want to take the test again, the questions list fails to be filled up again and I get an error: list.remove(x): x not in list from remove() I also tried to put in the get method the following code: ` if index==1: self.questions=list(Question.objects.all()) ` However it … -
pip command not working. I tried upgrading pip <pip install --upgrade pip> and < python -m pip install -U pip> but it's giving out a similar error
I tried installing django but it gave out the following error ERROR: Exception: Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve It's a long one... Then I tried using pip for different packages and it turns out I'm getting a similar error in almost all of the so I tried to upgrade them python -m pip install -U p and pip install --upgrade pip but it's giving out a similar error Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Program Files\Python310\lib\site-packages\pip\_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Program Files\Python310\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 472, in resolve -
How can i return json web token after creating user in djoser with dango rest framework
This is my serializer file for updating the default UserCreateSerializer of djoser. I saw this question but did'nt understand anything please help me to implement this. -
Celery KeyError: 'myproject.tasks.async_task'
When i'm trying to run celery background task then it giving me error: KeyError: 'myproject.tasks.async_task' I'm using python version: 3.8.10, django verion: 4.1.2 , celery version: 5.2.7 and rabbitmq version: 3.8.2 here below screenshot is my project structure: here below is my code for background task: settings.py: CELERY_BROKER_URL = 'amqp://localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' myproject/init.py: from __future__ import absolute_import, unicode_literals from myproject.celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os, sys from celery import Celery import django from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py: from __future__ import absolute_import from celery import shared_task from time import sleep import os @shared_task def sleepy(duration): sleep(duration) return None @shared_task def async_task(save_path, name_of_file): sleep(30) completeName = os.path.join(save_path, name_of_file+".html") file1 = open(completeName, "w") toFile = 'test data' file1.write(toFile) file1.close() return 'task complete' views.py def add_product(request): if request.method == 'POST': id_col_data = request.POST.getlist('services') target_col = request.POST.get('target_col') file_name = request.POST.get('file_name') amz_columns_dict = {'id_col': id_col_data, 'target_col': target_col, 'wt_col': None} import os.path save_path = '/home/satyajit/Desktop/' if os.path.exists(save_path): try: from myproject.tasks import async_task name_of_file = file_name status = async_task.delay(save_path, name_of_file) #celery task print('status---->', status) except Exception as e: print('task … -
How to find the index of a queryset after the database is sorted in Django
I am making a leaderboard for my quiz. I made this model: class LeaderBoard(models.Model): name = models.CharField(max_length=200) score = models.DecimalField(max_digits=4, decimal_places=2) This is my code for getting a queryset leaderboad_place = leaderboard.order_by("score").get(name=request.user.username) After I sort my code, I need the index at which my score stands out. I want the index, I mean the location of the queryset after the database is sorted, my code is not working. Please someone help. -
KeyError when I read environment variables while doing makemigrations in django
Context of the problem - I want to migrate from the SQLite database to Postgres. When I makemigrations with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable from the same file does not cause any problems. My secrets file: SECRET_KEY='secret key value' DB_HOST='db host value' DB_NAME='db name value' DB_USER='db user value' DB_PASS='db pass value' DB_PORT='db port value' My dev.py settings: from app.settings.base import * import os from dotenv import load_dotenv import pprint load_dotenv(os.environ.get('ENV_CONFIG', '')) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS += [ ] MIDDLEWARE += [ ] env_var = os.environ print("User's Environment variable:") pprint.pprint(dict(env_var), width=1) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_HOST'], 'PORT': os.environ['DB_PORT'], } } As you see, I import all the content from my base settings file - app.settings.base, where I use my secret key (in the same way as I read my environment variables for database): SECRET_KEY = os.environ.get('SECRET_KEY', '') I use SQLite in my base.py settings and want to use Postgres in my dev.py. However, when I try to ./manage.py makemigrations --settings=app.settings.dev, I get the error: … -
Trouble Creating a webpage
I'm having trouble creating a view. Down below you can find my view. I keep getting template error. I'm not sure where I went wrong.. class PrivacyView(CreateView): model = Post template_name = 'privacy_policy.html' fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('post_list') def post_list(request, tag_slug=None): posts = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) query = request.GET.get("q") if query: posts = Post.published.filter(Q(title__icontains=query) | Q(tags__name__icontains=query)).distinct() paginator = Paginator(posts, 10) # 10 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'post_list.html', {'posts': posts, page: 'pages', 'tag': tag}) Not sure where I'm going wrong here. If you can provide any help, please do. -
Low Speed Connection for VS Code servers to download extensions
Two days ago, i'd installed Ubuntu and deleted windows, than i install VS Code from Snap Store, now i have a problem with VS Code servers to download extensions. I'm from Iran and we have low speed connection, because of it, I get error for low connection. Is there a way to install extensions for VS Code? any help will gratitude. I get the XHR timeout: undefinedms How can i install VS Code extensions due to low connection speed? -
Django Query "caches" until restarting Server
Django "caches" my query. I realized it after updating my Database. When i run the Function with the Query, it takes some old Data before the Update. When i restart the Server, it works fine again. Do anyone know, how i can solve this issue? I use Raw Queries with the connection-function. (connection.cursor(sql)). In the End of each Query, i close the cursor with cursor.close(). I debugged the Code and found out, that after Updating my Database it takes the old Data until i restart my Server. -
Bootstrap modal, django for loop and model | same value displaying error Fixed
Would you like the modal to display corresponding loop values or messages? When I tried to print the order message in modals, it showed the same message for every order, which led me to realize that every time we call the same modal ID, it shows the same message for every order, -
Django Advanced Filtering for a Queryset that can have many related foreign keys
I am trying to sort a query in django on a model that can have multiple foreign keys. I only want the filtering to apply to one of those keys and I am having a hard time getting it to work. models.py class Post(models.Model): content = models.TextField(max_length=1000) reaction_counts = GenericRelation(ReactionCount, related_query_name='post_reaction_counts') class ReactionType(models.TextChoices): LIKE = 'like', ('Like') DISLIKE = 'dislike', ('Dislike') STAR = 'star', ('Star') LOVE = 'love', ('Love') LAUGH = 'laugh', ('Laugh') class ReactionCount(models.Model): count = models.PositiveIntegerField(default=0) type = models.CharField( max_length=7, choices=ReactionType.choices, ) post = models.ForeignKey(Post, related_name="reaction_count", on_delete=models.CASCADE) In this above example the keyed element (Foreign Key Relation) is ReactionCount for Post. I want to sort the posts by the posts with the most likes, dislikes, stars, loves, laughs, etc. I am trying to do this by doing Post.objects.all().order_by('-reaction_count__type', '-reaction_count__count') This however does not work as there are multiple ReactionCount objects for each post causing the ordering to not work. What I need is for a way to specify that I want the ordering of count to only apply only to Posts with a ReactionCount foreign key of a specific type. Is there a way this can be done by changing how the ordering is done on object Posts? … -
Login Button not redirecting back to home page
I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked. urls.py from django.urls import path from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView urlpatterns = [ path('login/', authView.as_view(),name='login'), path('', pplList.as_view(), name='pplLst'), path('people/<int:pk>', pplDetail.as_view(), name='pplDet'), path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'), path('people-create/', pplCreate.as_view(), name='pplCre'), path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'), ] views.py from distutils.log import Log import imp from .models import People from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView # Create your views here. class authView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('pplLst') class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' class pplCreate(CreateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplUpdate(UpdateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplDelete(DeleteView): model = People context_object_name = 'cnd' success_url = reverse_lazy('pplLst') login.html <h1>Login</h1> <from method="POST"> {%csrf_token … -
Django api update/create request from test case never fired the related methods in serializer
How i can send the UPDATE or CREATE request from my test case? When i run my test case the create/update methods never fired in serializer.. What i misunderstand in Django philosophy? Can someone suggest what i have to do? For example: #View class filesPairView (viewsets.ModelViewSet): serializer_class = filesPairViewSerializer def create(self, request): ... return Response(status=status.HTTP_201_CREATED) #Serializer class filesPairViewSerializer(serializers.ModelSerializer): class Meta: ... def create(self, validated_data): print ("filesPairViewSerializer CREATE") def update(self, validated_data): print ("filesPairViewSerializer UPDATE") #Test case class filesPairViewTestCase(APITestCase): def test_barmi(self): print("test_barmi") url = ('http://127.0.0.1:8000/api/filesPairView/') data ={ #some valid data } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) #urls router.register(r'filesPairView', views.filesPairView ) -
【Django】How to show the results of the columns calculated of child-tables
The purpose is to get averages of the columns of child-tables. My models are "One to Many" relations. (Here, One:Professor, Many:Evaluation) Based on each one-table (Model:Professor), I want to gain each averages of values of columns (Model:Evaluation, column:satisfaction). When showing each averages based on professors, results should be shown based on search engine written in views.py. The problem of following codes is that results cannot be shown in professors/professor_list.html. models.py class Professor(models.Model): college = models.CharField(max_length=50, choices=COLLEGE_CHOICES) name = models.CharField(max_length=50) def __str__(self): return self.name class Evaluation(models.Model): name = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_names', null=True) college = models.ForeignKey(Professor, on_delete=models.CASCADE, related_name='evaluation_colleges', null=True) satisfaction = models.IntegerField(choices=SATISFACTION_CHOICES) def __str__(self): return self.comment views.py from .models import Professor, Evaluation from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q, Avg class ProfessorList(generic.ListView): model = Professor template_name = "professors/professor_list.html" def get_queryset(self): q_word = self.request.GET.get('query') selected_name = self.request.GET.get('name') selected_college = self.request.GET.get('college') if q_word: if selected_name and selected_college: professor_list = Professor.objects.filter( Q(name__icontains=q_word) | Q(college__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(name__icontains=q_word) | Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) elif selected_college: professor_list = Professor.objects.filter( Q(college__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) else: professor_list = Professor.objects.filter( Q(name__icontains=q_word) ) s_list = Evaluation.objects.filter( Q(college__icontains=q_word) ).annotate(avg_satisfactions=Avg('satisfaction')) else: professor_list = Professor.objects.all() s_list = Evaluation.objects.annotate(avg_satisfactions=Avg('satisfaction')) return professor_list, s_list professors/professor_list.html <form action="" method="get" class="#"> … -
Filter model method - Django
I want to filter the Preschooler with their BMI tag but BMI tags are from model method. How do I filter Preschoolers with their BMI tag? models.py from pygrowup import Calculator, helpers class Preschooler(Model): birthday = models.DateField(null=True, blank=True) height = models.FloatField(null=True, validators=[MinValueValidator(45.0), MaxValueValidator(120.0)]) weight = models.FloatField(null=True, validators=[MinValueValidator(1.0), MaxValueValidator(28.0)]) gender = models.CharField(max_length=100, choices=GENDER, null=True) def bmi_tag(self): calculator = Calculator(adjust_height_data=False, adjust_weight_scores=False, include_cdc=False, logger_name='pygrowup', log_level='INFO') try: age_months = int((date.today().year - self.birthday.year) * 12) whfa_value = float(calculator.wfl(self.weight, age_months, helpers.get_good_sex(str(self.gender)), self.height)) if whfa_value > 2.0: return 'ABOVE NORMAL' elif whfa_value >= -2.0 and whfa_value <= 2.0: return 'NORMAL' elif whfa_value >= -3.0 and whfa_value < -2.0: return 'BELOW NORMAL' else: return 'SEVERE' except: pass I would like to filter a preschooler like this: preschooler_normal = Preschooler.objects.filter(bmi_tag='NORMAL') But I am aware that we cannot query against model methods. How can I achieve this? Thanks! -
Login page is not working. Why am I getting redirected to my homepage
Whenever I do /login I get redirected to my homepage which is named pplLst. I think it is something wrong with how I am redirecting but I watching this tutorial (https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s) which I used in my code urls.py from django.urls import path from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView urlpatterns = [ path('login/', authView.as_view(),name='login'), path('', pplList.as_view(), name='pplLst'), path('people/<int:pk>', pplDetail.as_view(), name='pplDet'), path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'), path('people-create/', pplCreate.as_view(), name='pplCre'), path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'), ] views.py from distutils.log import Log import imp from .models import People from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView # Create your views here. class authView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('pplLst') class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' class pplCreate(CreateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplUpdate(UpdateView): model = People fields = '__all__' success_url = reverse_lazy('pplLst') class pplDelete(DeleteView): model = People context_object_name = 'cnd' success_url = reverse_lazy('pplLst') -
username=self.kwargs.get('username') returning Not Found: /
Hi I am trying to set the show the items the is only related to a specific user who is currently logged in. I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of Not Found: / I am not sure why? Here is the models.py: class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) Here is the urls.py: urlpatterns = [ path('', home.as_view(), name='home'), I have tried to have a queryset with the filter to the logged in user but returned back the same error. Here is my views that I have tried class home(LoginRequiredMixin, ListView): model = Item template_name = 'app_name/base.html' context_object_name = 'items' # queryset = Item.objects.filter(user=User) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) print(user) # return Item.objects.filter(user=user) In the home.html I added: {% block head_title %} {{ view.kwargs.username }} | {% endblock %} My question: How can I show the list of items that is only related to the logged in user? what am I doing wrong in here? -
Query in Django to sort in one table based on result of another table
I have two models listing model is: class listing(models.Model): productTitle= models.CharField(max_length=60) description = models.TextField() category = models.ForeignKey(category,on_delete=models.CASCADE,null=True) productPrice = models.FloatField(default=0.0) def __str__(self): return self.productTitle my watchlist model is: item = models.ForeignKey(listing, on_delete= models.CASCADE) watchlist = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item In my index.html I want to show the list item if watchlist attribute is False. Now, my views.py for index.html is as follows: def index(request): if request.user != "AnonymousUser": items= listing.objects.exclude(id=watchlist.objects.filter(user=request.user)) else: items = watchlist.objects.all() context = {'items':items} return render(request, "auctions/index.html", context) I couldn't filter the items on listing models based on the result of watchlist model i.e if watchlist=True then I do not want to render items on index.html. Because, I want to render watchlist items in separate pages. How to query in django if there are two models used? -
I have used the international phone numbers(intlTelInput) in my django app but it seems the form isn't saving the number
So i have basically used the intl-tel-input plugin in my registration form. My webapp is in django. But whenever i submit the form, i get an error which is like the phone_number field is required, even though i have filled in the number. Seems like the form isn't saving the phone number data. How can i solve this? form temlplate looks like this: {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/register.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script> </head> <body> </body> </html> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> </body> </html> </head> <body> <div class="container"> <div class="title">REGISTER </div> <div class="content"> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="user-details"> <div class="input-box"> {{form.name|as_crispy_field}} </div> <div class="input-box"> {{form.email|as_crispy_field}} </div> <div class="input-box"> <span class="details">Phone number</span> <input id="phone" type="tel" name="phone" /> </div> <div class="input-box"> {{form.address|as_crispy_field}} </div> <div class="input-box"> {{form.nin|as_crispy_field}} </div> <div class="input-box"> {{form.LC1_letter|as_crispy_field}} </div> <div class="input-box"> {{form.National_Id|as_crispy_field}} </div> <div class="input-box"> {{form.password1|as_crispy_field}} </div> <div class="input-box"> {{form.password2|as_crispy_field}} </div> </div> <div class="form-check d-flex justify-content-center mb-5"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3c" /> <label class="form-check-label" for="form2Example3"> First agree with all statements in <a href="#!">Terms of service</a> to continue </label> </div> <div class="button"> <input type="submit" value="Register" href="#"> <input type="submit" value="Login" style="margin-left: … -
Django drf group by a model date field
I have an attendance model with the below structure class Attendance(models.Model): class PRESENCE(models.TextChoices): P = "P", "Present" A = "A", "Absent" L = "L", "On leave" user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_attendance", blank=False, null=True) leave_reason = models.CharField(max_length=355, blank=True, null=True) date = models.DateField(blank=False, null=True, auto_now=False, auto_now_add=False, editable=True) presence = models.CharField( choices=PRESENCE.choices, max_length=255, blank=False, null=True) attendance_taker = models.ForeignKey( User, on_delete=models.CASCADE, related_name="attendance_taker", blank=False, null=True) def __str__(self): return f'{self.user}' class Meta: verbose_name = _("Attendance") verbose_name_plural = _("Attendance") constraints = [ UniqueConstraint( fields=('user', 'date'), name='unique_attendance_once_per_date') ] I would like to create a table with the list of dates but simply using a generic view wouldn't cut it since different users will have similar dates, I need a way to merge the same dates into one and group the attendance instances that have similar dates. -
Insert i18n language into the request
I'm using the i18next lib, together with react in my front, and i intend to pass the information of my current language to my api through every request. I have a axios client wrapped in a constant that i use in my whole application, like this: ` const client = axios.create({ baseURL: CONSTANTS.API.BASE, headers: { "Content-Type": "application/json", }, timeout: TIME_OUT, }); ` I'd like to know if there some easy way to do this, and then get the language information in the back. By the way, i'm using Django REST Framework in my api. I tried to simply declare a variable into the headers in the client, just for test, but i couldn't get the value in the request in the api -
How to override `Model.__init__` and respect `.using(db)` in Django?
I have the following code: print(f"current database: {self.db}\ninfusate from database: {infusate._state.db}\ntracer from database: {tracer._state.db}") FCirc.objects.using(self.db).get_or_create( serum_sample=sample, tracer=tracer, element=label.element, ) That is producing the following output and exception: current database: validation infusate from database: validation tracer from database: validation Validating FCirc updater: {'update_function': 'is_last_serum_peak_group', 'update_field': 'is_last', 'parent_field': 'serum_sample', 'child_fields': [], 'update_label': 'fcirc_calcs', 'generation': 2} Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 581, in get_or_create return self.get(**kwargs), False File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( DataRepo.models.fcirc.FCirc.DoesNotExist: FCirc matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/views/loading/validation.py", line 91, in validate_load_files call_command( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/management/commands/load_animals_and_samples.py", line 134, in handle loader.load_sample_table( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/utils/sample_table_loader.py", line 426, in load_sample_table FCirc.objects.using(self.db).get_or_create( File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.create(**params), True File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 451, in create obj = self.model(**kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/DataRepo/models/maintained_model.py", line 430, in __init__ super().__init__(*args, **kwargs) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/Users/rleach/PROJECT-local/TRACEBASE/tracebase/.venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 229, in __set__ raise ValueError('Cannot assign "%r": the current database router prevents relation between database "%s" and "%s".' % (value, instance._state.db, value._state.db)) ValueError: Cannot assign "<Tracer: … -
execute django raw querie using ilike sentence
I got a query that compared with ORM is much more simpler using direct sql, Trying to execute it directly is in the part related to the ilike clause, I tried different ways but all fails (added a shorter query just to exemplify the problem) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %%%s%%", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike %s", ["jan"]) cursor.execute("SELECT cc.name FROM customer cc WHERE name ilike '%%%s%%'", ["jan"]) the error: LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike %'jan'% LINE 1: SELECT cc.name FROM customer cc WHERE name ilike 'jan' LINE 1: SELECT cc.name FROM customer cc WHERE name ilike '%'jan'%'