Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am making an affiliate website where we can copy product link and share it in other medias. please help to get me with it with a little idea
This is the product page. I have highlighted the portion of which i want to convey about. Here, in the 'Get Link' option i want to create a link for this product so that if a user copies and shares it to other media, it will open this page. P.S: Project is still in development URLS.py urlpatterns = [ path('', views.blink_network), # redirect to root - path path('blink_network/', views.blink_network, name='blink_network'), path('AddNewProduct/', views.AddNewProduct, name='AddNewProduct'), path('blink_viewproduct/', views.showproduct), path('blink_viewproduct/', views.blink_viewproduct, name='blink_viewproduct'), path('blink_updateproduct/', views.blink_updateproduct, name='blink_updateproduct'), ]+static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views.py def AddNewProduct(request): if request.method == "POST": current_user = request.user product_title =request.POST['product_title'] uid = request.POST['uid'] specification =request.POST['specification'] sale_price = request.POST['sale_price'] discount = request.POST['discount'] img1 = request.FILES['img1'] img2 = request.FILES['img2'] promote_method = request.POST['promote_method'] terms_conditions = request.POST['terms_conditions'] newproduct = AffProduct(user_id=current_user.id, product_title=product_title, uid=uid, specification=specification, sale_price=sale_price, discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'), promote_method=promote_method, terms_conditions=terms_conditions) newproduct.save() # Status message messages.success(request, 'Product added successfully') return render(request, 'blink_network.html') else: return render(request, 'blink_network.html') #Display only single-user products def showproduct(request): if request.user.is_authenticated: current_user = request.user# define current user result = AffProduct.objects.filter(user_id=current_user.id) return render(request, 'blink_viewproduct.html', {'result': result}) HTML File <div class="row py-3"> <div class="col-lg-12 col-md-12"> <h5 class="text-center"><b>Product Details</b></h5> <table class="table table-striped table-hover table table-responsive table-responsive-lg table-responsive-md table-responsive-sm"> <thead> <tr class="bg-primary text-white"> <th scope="col">Product ID</th> <th scope="col">Product Title</th> <th scope="col">Sale … -
if request.method == "POST": the pointer is not coming in the if statement can anybody tell?
views.py ... @login_required() def candidate_view(request): if request.method == "POST": can = candidate.objects.filter(position = 'President') return render(request,'poll/candidate.html',{'can':can}) else: return render(request, 'poll/candidate.html') ... ... vote.html {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% endblock %} ... Caandidate.html ... {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% end block %} ... -
How to pass a decimal value when making a post request in django?
I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem. request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error: decimal is not json serializable print('"%s"' % round((order.amount),2) #"5000.23" request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"} but when hardcoding amount then it is working request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer") -
Handling oracle database clob field in djangorestframework to get rid of to_clob()
I have an oracle database with a clob field as below: Name Null? Type ----------------------- -------- ------------- ID NOT NULL NUMBER MOVIE NOT NULL VARCHAR2(100) PLOT CLOB I am writing an API to retrieve this data and have the models.py defined as below: class MovieInfo(models.Model): id = models.IntegerField(primary_key=True) movie = models.CharField(max_length=100, unique=True) plot = models.TextField(null=True, blank=True) class Meta: managed = False db_table = 'movie_info' My serializer is defined as: class MovieInfoSerializer(serializers.ModelSerializer): class Meta: model = MovieInfo fields = '__all__' Views: class MovieInfoViewSet(viewsets.ModelViewSet): queryset = MovieInfo.objects.all() serializer_class = MovieInfoSerializer http_method_names = ['get'] However when I issue a get request, the data I'm getting looks as below: {"id":1,"movie":"Gravity","plot":"to_clob('The crew of the Space Shuttle Explorer is working on the STS-157 mission. Mission Commander Matt Kowalski, medical engineer Dr. Ryan Stone - who is on her first ever space mission - and flight engineer Shariff Dasari are on a space walk when they learn from Houston control that an explosion has just occurred at a Russian satellite. Before the crew can do anything about it, the explosion debris comes hurtling toward Explorer, irreparably damaging the shuttle and station, immediately killing all the crew except Kowalski and Stone, and knocking out at least incoming communication … -
im getting that type of error send_mail got multiple values for argument fail_silently
I'm writing a simple little program ... when I'm trying to email this info. from that form, I got that type of error I'm writing a simple little program ... when I'm trying to email this info. from that form, I got that type of error -
Field defines a relation with the model 'auth.User', which has been swapped out.(fields.E301)
I'm getting this error. ERRORS: subscriptions.StripeCustomer.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I'm trying to configure Django Stripe Subscriptions following this manual https://testdriven.io/blog/django-stripe-subscriptions/ My models.py from django.contrib.auth.models import User from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username My admin.py from django.contrib import admin from subscriptions.models import StripeCustomer admin.site.register(StripeCustomer) My settings.py AUTH_USER_MODEL = 'accounts.CustomUser' DEFAULT_AUTO_FIELD='django.db.models.AutoField' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_VERIFICATION = "none" After setting above, I executed "python manage.py makemigrations && python manage.py migrate" then the error occurred. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Django Account Switching
I am creating a request approval system in Django with 4 user roles Request Initiator with rights to only raise the request and view it Approver with rights to approve the request and view it Viewer with only viewing rights Admin with all the rights I need to create a functionality that can switch me between first 3 users if I am logged in as the Admin so that I can test the functioning of system without having to log in and log out again and again. Basically I need to create a switch account that will show me the webpage as some other user will see it on a single button click, I created a view that switch the account to the other user but once I am switched to this other user I lose the functionality to switch again because now I am not logged in as Admin...can I modify this function to see how a web page will look like if some other user with different access rights was to view the page without logging out as the admin ? def switch_account(request): new_user_id = request.POST.get('userID') new_user_pwd = request.POST.get('password') user = fetch_user(request, new_user_id , pwdnew_user_pwd admin = check_if_admin(str(request.user)) … -
PyCharm debug Django REST framework apis: breakpoints don't stop
I'm trying to debug my Django REST framework apis with PyCharm. I followed the answer from PyCharm: debug Django Rest Viewsets but breakpoints don't stop. With the same debug setting on a regular django app, breakpoints work as I expect but with Django REST framework they don't. When I hit the debug icon, it stops where my breakpoints are, but when I call the api from chrome, it never stops. I have PyCharm Professional 2021.1 and my settings are below. Does anyone have a clue? Thank you. -
Providing user with logs for a long API call
I have a web app that is used to interface with some network devices. There's an API endpoint to query for network device state. Once user calls it (post request with json body containing device to connect to, credentials and what state to collect), server will establish SSH connection to network device, run bunch of commands, parse output and return dictionary to the user. I have also built a web page with javascript that takes in user input and makes a POST ajax call to the endpoint. All that is working fine. The problem is, some devices are quite far away (geographically) and due to that, it may take very significant time to query this device - sometimes up to a minute. Obviously it's not a good user experience to sit around without any feedback. I do have access to SSH session logs (they are available as any normal python logs, i.e. I can log them to a file or print them to console, I am sure I can do more as well, just never looked into it much). My question is - what's the best way to handle providing live feedback to users while the API call is being … -
Django - Cannot filter a query once a slice has been taken
I'm using class based views, and when I try to use the "paginate_by = 6" with the "def get_context_data(self, **kwargs):", I get the following error: AssertionError at / Cannot filter a query once a slice has been taken. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: AssertionError Exception Value: Cannot filter a query once a slice has been taken. Exception Location: C:\Users\xxxx\xxxx\xxxx\env\lib\site-packages\django\db\models\query.py, line 953, in _filter_or_exclude Python Executable: C:\Users\xxxx\xxxx\xxxx\env\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\xxxx\\xxxx\\xxxx', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\xxxx\\xxxx\\xxxx\\env', 'C:\\Users\\xxxx\\xxxx\\xxxx\\env\\lib\\site-packages'] Server time: Sat, 29 May 2021 00:11:20 +0000 I'm trying to do the pagination for the filters result, like if no filters applied it should do the pagination for all Tasks. I've only found solution that do not use the functions with the Paginator. I would like to know if it is possible to do with the class based view and how, I'm a little lost in this. my views.py: class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = "tasks" template_name = "todo/tasks.html" paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tasks"] = context["tasks"].filter(user=self.request.user) context["count"] = context["tasks"].filter(complete=False).count() context["projects"] = Project.objects.all() search_input = self.request.GET.get("search") or "" project_input = self.request.GET.get("project") or "" complete_input = … -
Different behaviour of Count function on Django
I have a very strange case, in which the behaviour of Count() differs if it is applied to a filtered model by id, or from other filters. I have these models: class Segment(models.Model): is_completed = models.BooleanField(default=False) class Waypoint(models.Model): is_visited = models.BooleanField("is visited", default=False) segment = models.ForeignKey("Segment", on_delete=models.PROTECT, related_name="waypoints", null=True, default=None) Let say we have two waypoints both not visited yet, both related to the same segment. I have one of these waypoints in a queryset, call it wp. Now if I perform: to_visit_filter = Q(waypoints__is_visited=False) seg = Segment.objects.filter(waypoints__in=wp, is_completed=False).annotate( wp_to_visit=Count('waypoints', filter=to_visit_filter)) print(seg.first().wp_to_visit) // 1 Instead, if I do: to_visit_filter = Q(waypoints__is_visited=False) segm_id = [w.segment.id for w in wp] seg = Segment.objects.filter(id__in=segm_id, is_completed=False).annotate( wp_to_visit=Count('waypoints', filter=to_visit_filter)) print(seg.first().wp_to_visit) // 2 In both cases seg.first() give the same object instance, but the number of waypoint to visit is different. Why? -
So can't use weasyprint what is the best thing to do?
Thanks in advance. I am trying to load a django project onto a server. I realized I was unable to update Cairo for weasyrprint. I would like to to change the code to some thing else. I was thinking pylatex?? This is for html to pdf. In my orders app views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/order/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css')]) return response In my payment tasks.py # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach(f'order_{order.id}.pdf', out.getvalue(), 'application/pdf') Finally in my orders app pdf.html <html> <body> <h1>Mom and Pops</h1> <p> Invoice no. {{ order.id }}</br> <span class="secondary"> {{ order.created|date:"M d, Y" }} </span> </p> <h3>Bill to</h3> <p> {{ order.first_name }} {{ order.last_name }}<br> {{ order.email }}<br> {{ order.address }}<br> {{ order.postal_code }}, {{ order.city }} </p> <h3>Items bought</h3> <table> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Cost</th> </tr> </thead> <tbody> {% for item in order.items.all %} <tr class="row{% cycle "1" "2" %}"> <td>{{ item.product.name }}</td> <td class="num">${{ item.price }}</td> <td class="num">{{ item.quantity }}</td> <td class="num">${{ item.get_cost }}</td> </tr> {% endfor %} <tr class="total"> <td colspan="3">Total</td> <td … -
Angular "Uncaught (in promise): ChunkLoadError: Loading chunk 12 failed." error
I have recently rewritten my angular application. The previous project worked fine and I've not changed my django or apache2 configuration as it should just slip in. n.b. I have changed the django home.html to include "-es2015" in the appropriate file names. I'm currently getting the below errors in the inspector Resource interpreted as Stylesheet but transferred with MIME type application/javascript: "http://146.148.41.45/static/assets/js/frontendwikiconverter.js". 146.148.41.45/:33 GET https://p.typekit.net/p.css?s=1&k=oov2wcw&ht=tk&f=39203&a=2613646&app=typekit&e=css net::ERR_CONNECTION_REFUSED oov2wcw.css:1 Uncaught SyntaxError: Invalid or unexpected token styles.css:1 Uncaught SyntaxError: Unexpected token '<' 12-es5.js:2 ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 12 failed. main-es5.js:1 My app.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core'; import { LocationStrategy, HashLocationStrategy } from '@angular/common'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar'; import { PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar'; import { ToastrModule } from 'ngx-toastr'; import { JwtTokenService } from './services/jwt-token.service' import { IconModule, IconSetModule, IconSetService } from '@coreui/icons-angular'; import { LocalStorageService } from './services/local-storage-service.service'; import { NgxSmartModalModule } from 'ngx-smart-modal'; const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = { suppressScrollX: true }; import { AppComponent } from './app.component'; import { DefaultLayoutComponent } from './containers'; import { CommonModule } from "@angular/common"; import {AddToPlannerModule} from './views/planner/add-to-planner.module' import { TooltipModule } from 'ngx-bootstrap/tooltip'; const … -
How to refactor ViewSet that retrieves records created by authenticated user
I need these methods to retrieve/update/delete records created by authenticated user only. I'm clearly violating one of the key principles of web/software development. How can i refactor this viewset? class AddressViewSet(viewsets.ModelViewSet): queryset = Address.objects.all() serializer_class = AddressSerializer authentication_classes = (JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) def list(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).list(request, *args, **kwargs) def create(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).create(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).retrieve(request, *args, **kwargs) def update(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).update(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).destroy(request, *args, **kwargs) -
How to filter by JsonField tuple or list (Filtering only works for dictionaries?)
The documentation has info on querying JsonFields for dictionaries but not for lists or tuples. # models.py class Item(model): numbers = JSONField() # tests.py a = Item.objects.create(numbers=(1, 2, 3)) b = Item.objects.create(numbers=(4, 5, 6)) Item.objects.filter(numbers=a.numbers).count() # returns 0 Item.objects.filter(numbers__0=a.numbers[0]).count() # returns 0 Item.objects.all().count() # correctly returns 2 a.numbers # correctly returns (1, 2, 3) a.numbers[0] # correctly returns 1 How can I query or filter by a JsonField if that field is a tuple or list? -
Add Allauth login_required decorator to Baton.Autodiscover Admin subclass
I'm using Django-Baton, which injects CSS and JS styles and utilities around core Django template files, along with Django-AllAuth for more robust authentication and account access features. I'm using the documented method to redirect admin login to the AllAuth login page: from django.contrib import admin from django.contrib.auth.decorators import login_required admin.site.login = login_required(admin.site.login) Which I'm supposed to apply to "every instance of AdminSite." URLs: from baton.autodiscover import admin from django.urls import path, include urlpatterns = [ path("", admin.site.urls), path("baton/", include("baton.urls")), path("integrations/", include("integrations.urls")), path("queryfilter/", include("core.urls")), path("accounts/", include("allauth.urls")), ] Without baton.autodiscover, http://127.0.0.1:8000/ forwards, as desired, to accounts/login, but not so with autodiscover present. INSTALLED_APPS = [ "dal", "dal_select2", "dal_queryset_sequence", "baton", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # required for allauth "users", "core", "integrations", "allauth", "allauth.account", "allauth.socialaccount", "baton.autodiscover", ] Wondering if I need to subclass django.contrib.admin and apply the auth decorator somehow prior to baton.autodiscover, but not sure how/where to do it. Thanks for your input, and I'm pretty new to Django so thanks also for your patience. -
I'm having a TypeError: 'module' object isn't iterable when i run "python mange.py runserver in termux
Exception in thread django-main-thread: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/data/data/com.termux/files/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, in check for pattern in self.url_patterns: File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from '/storage/emulated/0/application/blog/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Search Error with django-datatable-view 0.9.0 using custom processor
I'm using a custom processor with django-datatable-view to provide a link to a related record. The DataTable search breaks when I use this approach. Sorting works fine. If I remove the custom processor, search works fine. Chrome console shows 500 (Internal Server Error) for the GET request. Is there a way to resolve this issue or approach the link in a different way? class MyDatatable(Datatable): some_id = columns.TextColumn( 'Some ID', sources='some_id', processor='get_some_id_link') class Meta: model = MyInventory columns = ['some_id', 'city', 'county', 'state', ] ordering = ['some_id'] def get_some_id_link(self, instance, *args, **kwargs): url = reverse('detail_view', kwargs={'slug': instance}) return '%s%s%s%s%s' % ("<a href='", url, "'>", instance, "</a>") -
not able to authenticate user
views.py def Login(request): if request.method == "POST" : username1=request.POST['usernm'] password1=request.POST['passwd'] user=authenticate( username=username1 , password=password1) if user is not None: login(request, user) return render(request,'loginsuccess.html') else: return render(request,'login.html') model.py class My_User(models.Model): first_name=models.CharField(max_length=70,primary_key=True) last_name=models.CharField(max_length=70) mail=models.EmailField() username=models.CharField(max_length=70) password=models.IntegerField(max_length=60) html form {% csrf_token %} username =<input type="text" name="usernm" id="usernm" ><br> password =<input type="password" name="passwd" id="passwd" ><br> <button type="submit" > Login </button> </form> here i am not able to authenticate data i don't know whats the issue i am facing here, i am getting the user in the views as none because of which i am not able to login -
Django Admin Inline indirect
i have an app caso and it has an inline from casov, this is possible because casov has a fk from caso, but now i have aggressor that has a fk to casov so it is indirectly connected to caso, i need to make an inline in caso, help please. hola, tengo una app caso y esta tiene un inline de casov, esto se puede por que casov tiene una fk de caso, pero ahora tengo agresor que tiene una fk hacia casov por lo cual esta indirectamente conectado a caso, requiero hacer un inlines en caso, ayuda por favor. -
Adding historical field value in Django queryset using django-simple-history and django-queryable-properties
So some quick background: I'm trying to build a queryset to link to admin panels and incorporate it across the full application stack. It would help me provide my end-users with the information they need on-demand while reducing the need for me to create and share reports manually. I'm try to accomplish the following: from queryable_properties.properties import queryableproperty from simple_history.models import HistoricalModel from datetime import date, timedelta from django.db import models class DataReport(models.Model): history = HistoricalRecord() formatted_date = models.DateTimeField(verbose_name="FormattedDate") date = models.CharField(verbose_name="Date", max_length=255, null=True) report_title= models.CharField(verbose_name="Report Title", max_length=255, null=True) severity_score = models.IntegerField(blank=True, null=True) @queryableproperty def get_prev_score(self): exclude_filters = { "severity_score__isnull": True, "date__lte": date.today() - timedelta(30) } hist_qs = self.history.exclude(**exclude_filters) prev_score = hist_qs.order_by('date').first() return prev_score.severity_score if prev_score else return None from here I would ideally run DateReport.objects.filter(severity_score__gt=F('get_prev_score') but this would not work since it would require annotation and you can't annotate without explicitly referencing a data field via F objects, and you can't use HistoricalRecord with F objects. I've tried using subqueries but can only get null values returned when annotating. Any ideas, hivemind? -
Sort results by a part of a fields' string in django
I have such Django models: class SavedVariant(models.Model): family = models.ForeignKey('Family', on_delete=models.CASCADE) class Family(models.Model): family_id = models.CharField(db_index=True, max_length=100) family_id is of such a pattern: CCNNNNNN_CCC_CCCC where C is a character and N is an integer, e.g. SF0637658_WGS_HGSC. I want to order (django order_by?) my SavedVariant models first by preceding chars - CC - then by the number - NNNNNN - and finally by the last chars. Is it possible to do in Django? What would you recommend? -
Is there a way to save each value several times? Please help me
great developers. I'm a student learning Django. I am implementing the product registration part, and I want to register after receiving the price twice in the designated part of the model. One is the price of the product itself, and the other is the product option cost added. The problem is that when I checked with admin, the price is two fields, so it's not stored one by one, but only one with one price. I would like to be registered with two pieces of information, one with the price of the product and one with the price of the option. How can I solve this part? In addition to this issue, if there is an option called 'color', you should specify an option value such as 'red' and 'blue' that corresponds to 'color' and save only one option value that corresponds to 'option'. How can I save this problem? Great developers, please reply. In short, for example, ex) Price 1, if you have Price 2, you have 1 information that is different from Price 1, and you have 1 information that is different from Price 2, and you have 1 information that is different from Price 2. Model.py # … -
Notification when a certain point in time is exceeded (Python)
I would like to create a To-Do list in which I can schedule date and time of each task. My goal is to get some sort of response whenever the supplied datetime is equal to the current time. For example I scheduled Do laundry for Monday at 6pm on a Saturday evening. Two days later (on Monday at 6pm) I would like to get a notification that I should Do laundry. Notice that the key idea can be found in the index() function in views.py in the first rows including the if-statement. Here is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details"), path("add/", views.add, name="add"), path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"), path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"), path("update/<int:aufgabenzettel_id>", views.update, name="update") ] models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) Datum = models.DateTimeField(auto_now_add=True) Geplant = models.DateTimeField(auto_now_add=False, auto_now=False) def __str__(self): return f"{self.Aufgabeselbst}" views.py (the important part can be found in the index function in the first rows including the if-statement) from django.db.models.fields import DateTimeField from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.utils import timezone from datetime import datetime from .models import Aufgabenzettel # … -
How many foreign keys can a table have in postgreSQL?
I am working on a Django project with a database in PostgreSQL. During my schema design, I have noticed that one table is referencing many foreign keys from other tables. Just curious that how many foreign keys can be referenced from/to one table? I also searched and found that the SQL server 2014 can reference up to253 foreign keys.