Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does my reverse url lookup with kwargs not work on viewset action api?
Here is my viewset with an action: class RewardsQueryViewSet(UUIDModelViewSet): queryset = RewardsQuery.objects.all() serializer_class = RewardsQuerySerializer ordering_fields = ("-created_at",) http_method_names = [ "post", "get", ] def create(self, request, **kwargs): serializer = RewardsQuerySerializer(data=request.data) serializer.is_valid(raise_exception=True) transaction = serializer.save() return Response(transaction) @action( detail=True, methods=("get",), url_path="earned-rewards", ) def earned_rewards(self, request, *arg, **kwargs): session = RewardsQuery.objects.get(uuid=self.kwargs["uuid"]) transactions = Rewards.objects.filter(profile=session.profile) return Response({"results": transactions}) in urlconf, I see this entry: api/<version>/ ^applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards/$ [name='rewards-query-earned-rewards'] but when I try to do the reverse lookup, it fails. I've tried both of these: drf_reverse('rewards-query-earned-rewards', kwargs={'client_id': instance.application.client_id, 'uuid': str(instance.uuid)}) reverse('rewards-query-earned-rewards', kwargs={'client_id': instance.application.client_id, 'uuid': str(instance.uuid)}) django debug error: Exception Type: NoReverseMatch Exception Value: Reverse for 'rewards-query-earned-rewards' with keyword arguments '{'client_id': 'FVQI5U57tfCyDV99YjhF3ExdlpiObg5JASvy81Mu', 'uuid': '2057de0f-f5b4-4af4-aa99-ac3681cc6984'}' not found. 2 pattern(s) tried: ['api/(?P<version>[^/]+)/applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards\\.(?P<format>[a-z0-9]+)/?$', 'api/(?P<version>[^/]+)/applications/(?P<client_id>[^/]+)/rewards-queries/(?P<uuid>[^/.]+)/earned-rewards/$'] Why is reverse lookup failing? -
Django rest framework : creating a user ask for authentication
I was using django user, authentication and permission modules but while making a request to create a new user in the POST request, its asking for authentication. and I am getting { "detail": "Authentication credentials were not provided." } Here is my serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user def update(self, instance, validated_data): instance.username = validated_data['username'] instance.set_password(validated_data['password']) instance.save() return instance views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) urls.py from django.urls import path, include from .views import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] -
how to reset datetimefield in django
I doubt in the DateTime field, my 'course' model has a field called "publish_date" and if the course is published then "course.publish_date = datetime.datetime.now ()". Also, there is a chance that the published course will not be published, so I should be able to change it to publish_date = null, But it makes mistakes, give me a solution to fix it. views.py class PublishCourseViewSet(ResponseViewMixin, viewsets.GenericViewSet): def put(self, request, course_id=None, *args, **kwargs): try: course = get_object_or_404(Course, pk=course_id) course_status = course.review_status if course_status == 'review_passed': course.review_status = 'published' course.publish_date = datetime.datetime.now() course.save(update_fields=["review_status", "publish_date"]) serializer = CourseListSerializer(course) return self.jp_response(s_code='HTTP_200_OK', data=serializer.data) else: return self.jp_error_response('HTTP_400_BAD_REQUEST', {"detail": "course not yet ready for publishing"}) except Exception as e: return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) class UnPublishCourseViewSet(ResponseViewMixin, viewsets.GenericViewSet): def put(self, request, course_id=None, *args, **kwargs): try: course = get_object_or_404(Course, pk=course_id) course_status = course.review_status if course_status == 'published': course.review_status = 'review_passed' course.publish_date = null course.save(update_fields=["review_status", "publish_date"]) serializer = CourseListSerializer(course) return self.jp_response(s_code='HTTP_200_OK', data=serializer.data) else: return self.jp_error_response('HTTP_400_BAD_REQUEST', {"detail": "course not yet ready for publishing"}) except Exception as e: return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) -
How come Django templates, Ajax, and form.errors don't work together in a more integrated fashion?
I'm continuing on my Django, Ajax, and form.errors journey...and here's what I can and can't make sense of....If an ajax request submitted by django....has form.errors....how come django can't recognize this in the template? It can if the form is submitted via a traditional form_valid approach...but not as_json. If the error is as_json....you have to manually interrogate the errors. At least this is the most documented method on the internet. Can someone who is way smarter than I am provide a reasonable explanation as to why this wouldn't be possible? It seems like it should be....with just a simple template loop... Instead I've read the way to solve this is ajax with crispy forms...or ajax with manipulating the DOM. Thanks in advance for any feedback on this topic. -
Dropdown List with Django dependent
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. this post(https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = … -
Django 3.2.8 | DetailView url doesn't load base.html if "/" present
I have this weird behavior where the following loads static files : url.py : path('<int:pk>/detail', PropositionsDetailView.as_view(), name='propositions-detail') but if I add a trailing "/" it doesn't seem to find them ; I only get the base.html unformated : path('<int:pk>/detail/', PropositionsDetailView.as_view(), name='propositions-detail') would someone know why that is ? -
placeholder on dependent dropdown filter
I have a django filter with a dependent drop down to filter car manufactures and models. The models use a charfield and pulls the cars from a db entry. I would like a place holder to say manufacture and model on their respected fields. I cant find much online about doing this. The only post I can find relates to using the choice field on the model which wont work for me. filter class CarFilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Post.objects.none() if 'model_manufacture_id' in self.data: try: model_manufacture_id = int(self.data.get('model_manufacture_id')) self.fields['model_id'].queryset = CarModels.objects.filter(model_manufacture_id=model_manufacture_id) except (ValueError, TypeError): pass class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' form = CarFilterForm html <form method="get" id="AllCarsForm" data-cars-url="{% url 'ajax-allcars' %}"> {% render_field myFilter.form.manufacture class="cars-filter-widget" %} {% render_field myFilter.form.model class="cars-filter-widget" %} <button class="btn btn-primary" type="submit">Search</button> </form> -
How to filter an annotated queryset using Window function without changing the annotated field
I have a queryset of users, after annotating the rank of each user using Django Window function, I want to query for a user without modifying the rank value users_points_query = users.order_by( '-total_points' ).annotate( rank=Window( expression=Rank(), order_by=[ F('total_points').desc() ], ) ) this works fine, but when filtering on users_points_query query, the rank is calculated again, so the first user will get a rank of 1, which is based on the first row and so on. -
How to join multiple table with ForeignKey in django
from django.db import models class Employee(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_NAME = models.CharField(max_length=150) ...etc class EMPLOYEE_PERSONAL(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_LINK = models.ForeignKey(Employee) EMP_ADDRESS = models.CharField(max_length=150) ..etc class EMPLOYEE_COMPANY_DETAILS(models.Model): ID = models.AutoField(primary_key=True, db_index=True) EMP_CODE = models.CharField(max_length=150) EMP_LINK = models.ForeignKey(EMPLOYEE_PERSONAL) EMP_COMPANY_NAME = models.CharField(max_length=150) NO_OF_WORKING_DAY = models.CharField(max_length=150) ..etc In here I have EMP_CODE how to get all table data value in single query in orm .for eg( I need EMP_NAME ,EMP_ADDRESS ,EMP_COMPANY_NAME ) Using EMP_CODE . I beginner of python Django -
Django Site matching query error when start
Error: DoesNotExist at /login/ Site matching query does not exist. Git code: https://github.com/Vladislava05/todo.git -
SMTPAuthenticationError at /email/signup/ in my django project on pythonanywhere.com
Django sendmail not working, i got error: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q13sm252028qtx.80 - gsmtp') there are similar question on S.O.,like this. everyone taking about "allow less secure apps", but i already turn that option ON. my auth details are correct, i had tried with two different accounts. two step varification is disabled. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True views.py def sendmail(email,token): subject = 'Varify Email' message = 'Hello User please activate your account by click on this link '+'http://mywebsite.pythonanywhere.com/email/varify/'+token from_email = 'praveexxxxxxxxxxx@gmail.com' recipient_list = [email] send_mail(subject=subject,message=message,from_email=from_email,recipient_list=recipient_list) def signup(request): token = generatedtoken email = someoneemail@gmail.com sendmail(email,token) -
get the currently logged user request.user in utils.py
I need to get the currently logged user 'budget_id' (column from database) in utils.py. Normally in views.py I use: def login_user(request): return request.user.last_name utils.py fragment: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None,): self.year = year self.month = month super(Calendar, self).__init__() def formatday(self, day, events): budget_id = request.user.budget_id // need here -
Set up JSONField in HTML page
I've created this model class RoadConstruction(models.Model): fromCity = models.CharField(max_length=200, null=True) toCity = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True) date_updated = models.DateTimeField(auto_now_add=True, null=True) jsonData = models.JSONField(null=True) profile = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) So when I use Forms and add the form into my html page it generates a text area for jsonData. But here is the catch I know how to like properly define the contents of JSONField but the thing is the JSON is going to be dynamic and it all depends upon the user who is submitting the form. So, I cannot fix the JSONField. I'll explain with examples of what I'm expecting with JSONField. fromCity, toCity, status is self explanatory as it can be very easily implemented with Forms. In xyz.html page there will be initially one row of empty form. colA colB colC valueA valueB valueC Here suppose the user gave above inputs i.e valueA, valueB, valueC. So I want data to be stored in JSONField as [ { 'colA': valueA, 'colB': valueB, 'colC': valueC, } ] Also there will be a ADD button which will add a new row like this and then the user can fill it. | colA | colB | colC | |------|------|------| | … -
django translation get_language returns default language in detail api view
this is the api which sets language when user selects some language this works fine. class SetLanguage(APIView): def get(self, request, *args, **kwargs): user_language = kwargs.get("lan_code") translation.activate(user_language) response = Response(status=status.HTTP_200_OK) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) request.session[LANGUAGE_SESSION_KEY] = user_language return response viewset here with this viewset only in the api blog/{id} the function get_language returning default language code but on other api it working properly. I am not being able to find the issue. What might gone wrong ? class BlogViewSet(ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerilizer detail_serializer_class = BlogDetailSerializer def get_serializer_class(self): if self.action == "retrieve": return self.detail_serializer_class return super().get_serializer_class() def list(self, request, *args, **kwargs): queryset = Blog.objects.filter(parent=None) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) @action(detail=True, methods=["get"]) def childs(self, request, id): child_blogs = Blog.objects.filter(parent_id=id) serializer = self.get_serializer(child_blogs, many=True) return Response(serializer.data) model from django.utils.translation import get_language class MyManager(models.Manager): def get_queryset(self): current_language = get_language() print(current_language) return super().get_queryset().filter(language=current_language) class Blog(models.Model): title = models.CharField(_("Title"), max_length=100) objects = MyManager() -
How can I add two date fields in Django
Is it possible to add two date fields in Django models as single field. typically this field I have added from date range picker JavaScript picker which user can select from n to in the single field. Is any way to achieve it in Django -
'NoneType' object has no attribute 'transform'
AttributeError at /turboai/turboAI/jaaiparameters/ enter image description here def transform_data(df, cols, scaler, n_days_past=120): n_cols = len(cols) # df to np array np_arr = np.array(df.values.flatten().tolist()) np_arr = scaler.transform([np_arr]) np_arr = np_arr.reshape((np_arr.shape[0], n_days_past, n_cols)) return np_arr -
Couldnt save Modelform to database
I am trying to save the model form and getting error that foreign key column is not there. Error: column "connection_type_id" of relation "connection_details_test" does not exist ( There is no column connection_type_id, why its looking for this column, should I change my model?) Models: class ConnectionTypes(models.Model): connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq')) connection_type_name = models.CharField(max_length=100) connection_type_desc = models.CharField(max_length=300) connection_type_category = models.CharField(max_length=100) last_update_date = models.DateTimeField(default=dbcurr_ts) class Meta: managed = False db_table ='connection_types_test' verbose_name = 'connection_types_test' verbose_name_plural = 'connection_types_test' def __str__(self): return str(self.connection_type_id) class ConnectionDetails(models.Model): connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq')) connection_name = models.CharField(max_length=200) connection_type = models.ForeignKey(ConnectionTypes, on_delete=models.CASCADE) endpoint = models.CharField(max_length=100) port = models.IntegerField() login_id = models.CharField(max_length=100) login_password = fields.CharPGPPublicKeyField(max_length=100) connection_string_1 = fields.CharPGPPublicKeyField(max_length=100) connection_string_2 = fields.CharPGPPublicKeyField(max_length=100) connection_string_3 = fields.CharPGPPublicKeyField(max_length=100) aws_region = models.CharField(max_length=20) owner_id = models.IntegerField() last_update_date = models.DateTimeField(default=dbcurr_ts) working_schema = models.CharField(max_length=100) service = models.CharField(max_length=100) def generate_enc(mystrenc): return 'pass' class Meta: managed = False db_table = 'connection_details_test' verbose_name = 'connection_details_test' verbose_name_plural = 'connection_details_test' Model Form : class ConnectionForm(forms.ModelForm): login_password = forms.CharField(widget=forms.PasswordInput()) owner_id = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = ConnectionDetails exclude = ['connection_id','last_update_date'] View.py def addconnection(request): connectionform = ConnectionForm(request.POST or None) if connectionform.is_valid(): ownerqs = AuthUser.objects.values('id').get(username = request.user.username) connectionform.cleaned_data['owner_id'] = int(ownerqs['id']) connectionform.save() messages.success(request, f"sucess!") else: messages.success(request, f"Failure!") return render(request,'main/ssaddconnection.html',{"cform": connectionform,"CanUseMod":UserModules.objects.filter(user_id=request.user.id).filter(module_id=1).count(),"UserIsAuth":request.user.is_authenticated}) Anyone can help me on this?? Thanks, Aruna -
Get Foreign Key objects in the query
I have two models. The first one represents different Projects with a name, an ID and a description The second one is for tracking wich user is in wich Project. So my models look like this: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id In the Userproject there there is only the UserID and the ProjectID, both are ForeignKeys to the other models. When I get a GET-Request with a username, I can get the userID , then I can filter all the Userprojects by the userID and serialize all those where the given ser is present. But How would I include the Project data as well If I want to send the name … -
Import-export module works not with User model for me in Django
I am trying to import new users to original User model form the Django admin site. I used to add the users one-by-one manually to the model but now I need to import lots of users and I need a solution to bulk import. I tried the code below, but I have an error: django.contrib.admin.sites.NotRegistered: The model User is not registered Please help me to solve this. admin.py from django.contrib import admin from django.contrib.auth.models import User from import_export.admin import ImportExportModelAdmin from import_export import resources class UserResource(resources.ModelResource): class Meta: model = User fields = ('id','username','first_name', 'last_name', 'email' 'password1', 'password2') class UserAdmin(ImportExportModelAdmin): list_display = ('id','username','first_name', 'last_name', 'email') resource_class = UserResource pass admin.site.unregister(User) admin.site.register(User, UserAdmin) -
django-ajax-selects autocomplete function doesn't work with inlineformset_factory
Is it possible to use the autocomplete function from django-ajax-selects (https://github.com/crucialfelix/django-ajax-selects) using inlineformset_factory? In my case the autocomplete doesn't work, when I write a letter it doesn't search anything... This is my forms.py: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex",) class FormulariPoolIndexList(ModelForm): class Meta: model = SamplePoolIndexCand fields = ("pool_id", "index_id", "gene_cand_list_id",) pool_id = AutoCompleteSelectField('pool_tag') index_id = AutoCompleteSelectField('index_tag') gene_cand_list_id = AutoCompleteSelectField('list_tag') PoolIndexListFormset = inlineformset_factory(Sample, SamplePoolIndexCand, form=FormulariPoolIndexList, extra=2,) My models.py: class Index(models.Model): id_index = models.AutoField(primary_key=True) index_name = models.CharField(max_length=30) index_id_index_type = models.ForeignKey(IndexType, on_delete=models.CASCADE, db_column='id_index_type', verbose_name="Tipus d'índex") index_id_index_provider = models.ForeignKey(IndexProvider, on_delete=models.CASCADE, db_column='id_index_provider', verbose_name="Proveïdor d'índex") miseq = models.CharField(max_length=9) nextseq = models.CharField(max_length=9) class Meta: db_table = 'index' unique_together = (("index_name", "index_id_index_type", "index_id_index_provider", "miseq", "nextseq"),) def __str__(self): return self.index_name class GeneCandList(models.Model): id_gene_cand_list = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=150, verbose_name="Llista de gens candidats") class Meta: db_table = 'gene_cand_list' def __str__(self): return self.name class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") hibridation = models.BooleanField(verbose_name="Hibridació OK?") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres" class Meta: ordering = ['-id_pool'] db_table = 'pool' def __str__(self): return self.name class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), … -
How to check if django admin is logged in or not?
I have a django project where I have 2 different login page. 1 is in the landing page. ex: https://website.com/ 2 is the django admin login. ex: https://website.com/admin/ For both the login, I am using the same postgres table. The requirement is, When I login from login page, if the user has access to admin, he should be able to login both landing page and admin page and vice versa. When I logout from any of the 2 logins, it should be able to logout from both the logins if the logged in user is same for both the logins. My login and logout code from the landing page @api_view(['POST']) def login(request): """ API for user login -> store username password using posted request.data -> check the username exists in database -> if username exists, authenticate the username,password and return response -> if username does not exists, return response """ if request.method == 'POST' and request.data: data = request.data username = data['username'] password = data['password'] user = auth.authenticate(username=username, password=password) if (user is not None) and (user.is_active): auth.login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"username": str(user), "token": token.key, "status": STATUS['SUCCESS'], "message": MESSAGE_SUCCESS['LOGIN']}, status=status.HTTP_200_OK) return Response({"status": STATUS['ERROR'], "message": MESSAGE_ERROR['LOGIN']}, status=status.HTTP_200_OK) @api_view(['POST']) @authentication_classes((TokenAuthentication,)) … -
What's the best or the most secure Authentication type in django authentication
I would like to know what the best and the most secure authentication is for django, for like a big social media app. Thanks in advance. -
Why the elif part in my if-else statement does not give me desired output even if the condition is True in Django?
I'm using a signal which was working perfectly fine earlier, when it had only one if part: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') But I had another scenario and had to apply an elif and an else part too but that wouldn't work somehow. It looks like this now: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') elif pkg.patient_type == 'CASH': print('patient type: ', pkg.patient_type) print() if instance.deficit_or_surplus_amount<0: print('deficit?', instance.deficit_or_surplus_amount<0) Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') else: pass The if part says that if the patient is using some Government scheme instead of cash payment run the code below. The elif part … -
How to get user first login time and last logout time ,everyday?
all user login & logout number of time, everytime the datetime is storing into the db but i need everyday first logintime and last logout time of every user? models.py class AllLogout(models.Model): user = models.ForeignKey(Account,on_delete= models.CASCADE) login_time = models.DateTimeField(null=True) logout_time = models.DateTimeField(null=True) def __str__(self): return str(self.user) + ': ' + str(self.logout_time) views.py This is my view function @login_required(login_url='login') @allowed_users(allowed_roles=['Manager', 'Admin']) def welcome(request): # list of agent ids im getting data1 = Account.objects.filter(Role='Agent').values_list('id', flat=True) startdate = date.today() enddate = startdate + timedelta(days=5) some_day_last_week = timezone.now().date() - timedelta(days=7) res = [] for agentname in data1: agentdata = AllLogout.objects.filter(user_id=agentname).filter(login_time__range=[startdate,enddate]) agentdata = AllLogout.objects.filter(user_id=agentname).values('logout_time') res.append(agentdata) print(agentdata) lasttime = [] for agentname in data1: agentdatalast = AllLogout.objects.filter(user_id=agentname).filter(logout_time__range=[startdate,enddate]).last() lasttime.append(agentdatalast) zippedList = zip(res, lasttime) return render(request, 'all_adminhtmlpages/welcome.html', {'zippedList': zippedList}) -
Ram size and deep learning model disk size in production
I am trying to host a deep learning model of size 1 GB on a server with ram 512. I am using django framework. But i have confusion, when a query is sent to model, first it load into the ram. So it will give out of memory error. This is my assumption. Is it true? if it is true is there a way to resolve this issue.