Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotated value gives None, need 0
order_list_cases =(order_list.values('user_id').annotate(dcount=Count('user_id'),customer_paid_sum=(Sum('invoice__transaction_invoice__transaction_amount')) In this code, the customer_paid_sumis returning None, I want to give it as 0 if it is None. I tried else case along with it but didn't work. -
Django-admin filter button
I am trying to create an admin page in Django for my Video model. The view is quite simple, all I want to do view and filter video records based on dropdown and datetime filters. Here is my code. from django.contrib import admin from django_admin_listfilter_dropdown.filters import DropdownFilter from rangefilter.filters import DateTimeRangeFilter @admin.register(Video) class VideoAdmin(admin.ModelAdmin): list_display = ('file_hash', 'file_path', 'height', 'width', 'frames', 'camera_model' 'created_at') list_filter = ( ('frames', DropdownFilter), ('created_at', DateTimeRangeFilter), ('height', DropdownFilter), ('width', DropdownFilter), ('camera_model', DropdownFilter), ) search_fields = ('file_hash', 'file_path', 'model',) The solution works well for reasonable amount of records. However, it becomes very slow when the records saved on db increase significantly (~1M). When filtering with multiple criteria, one has to: Filter by frames Wait for the new response Filter by camera_model Wait again And so on.. Is there a way to trigger the filtering once for all instead of performing it at each field change? -
Conditional component render if user is an owner of post React + Django Rest Framework
I have f.e. User and Post models. User object has an id and Post object has owner id. I want to render the <Edit /> button just when User is the owner of the Post. What is the best way to do this? Simply I can just get the current User id from database using one of my django's endpoints and check if user.id === post.owner but is it the best way? (I am using JWT in my project) Also how can I block or redirect users which are not the owner if someone of them open the site by link. Should I also simply check if if user.id === post.owner? One extra question: I am storing my JWT tokens at the moment in the localStorage. What I should looking for if I want to hide it in my blowser (if I click F12, I can find it in Application tab)? -
How to stop Django function from producing duplicate results?
I'm having trouble with this function that is creating duplicate records. I have a couple pages with documents that contain a response with document as a list of records. Each page contains a different number in this list. When all the records are created in the database, it starts to duplicate them because the amount of pages exceeds the number of pages that have documents in them. Here is what the response for each page looks like: { "page": 3, "limit": 10, "count": 2, "machines": [ { "1234", "location": "123 Random address", "location_name": "Scraton", "location_coordinates": { "latitude": 54.443454, "longitude": -124.9137471 }, { "document_id": "1235", "location": "124 Random address", "location_name": "New York", "location_coordinates": { "latitude": 233.385037, "longitude": -40.1823481 }, ] } Here is the function that is creating duplicates. def sync_all_documents(limit=1000, page_start=0,page_end=10): for page in range(page_start, page_end): try: response_data = get_documents(limit=limit, page=page) logger.info(f"Page Count: {response_data['count']}") if(response_data['count'] == 0): return except RequestError as ex: return # loop short circuits here try: documents = response_data[“documents”] for document in documents: # STEP 1 - Location try: serialized_location = serialize_location_information(document) location, l_created = Location.objects.get_or_create( latitude=serialized_location["latitude"], longitude=serialized_location["longitude"], defaults={ "country": serialized_location["country"], "state": serialized_location["state"], "city": serialized_location["city"], "street_address": serialized_location["street_address"], "postal_code": serialized_location["postal_code"], "name": serialized_location["name"], "status": serialized_location["status"], } ) if l_created: … -
Django Forms - how to access fields inside a class
im working with django forms and want to access the field variable inside its class: class CarPurchase(forms.Form): brand = forms.CharField(max_length=30) color = forms.CharField(max_length=20) @classmethod def set_color(cls, color): cls.color = color and that will give error says CarPurchase has no attribute 'name'. do you guys see what i have problem? -
Django ImageField serializer field is None when accessed in a View
I created a serializer for image uploads and want to access the image in a view when uploaded to that endpoint. serializer class AccountInvestigationFileUploadSerializer(serializers.Serializer): image = serializers.ImageField() view class AccountInvestigationFileUploadView(APIView): permission_classes = [IsAuthenticated] serializer_class = AccountInvestigationFileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data) However when I try accessing the serializer data in the view it is None. > serializer AccountInvestigationFileUploadSerializer(context={'request': <rest_framework.request.Request: POST '/api/v1/investigation/upload/'>}, data=<QueryDict: {'csrfmiddlewaretoken': ['TiblXu6wmpaE7qQJ10eneBEV1vRKRBi7GkwqIZdEhlbu0BfYFM3qAqY4235gv6z3NwNi'], 'image': [<InMemoryUploadedFile: Screen Shot 2021-09-12 at 12.57.25 PM.png (image/png)>]}>): sketch_id = CharField(max_length=255) request_id = CharField(max_length=255) image = ImageField() > serializer.data {'image': None} What am I missing? -
i can only login if i have a lowercase password
I made a custom user model and added some authentication system, but when I try to login into my account, it won't let me, but if I change the password to all lowercase, then it lets me login. I added this custom backend because the email field was case-sensitive, and I didn't want that, and now it messes up my login system. backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend, UserModel class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user views.py from django.shortcuts import redirect, render from django.contrib.auth import login, logout, authenticate from django.contrib import messages from django.template.defaultfilters import slugify # Create your views here. from .forms import MyUserCreationForm, SettingsForm from .decorators import unauthorizedUserCanView, authorizedUserCanView from .models import User @unauthorizedUserCanView def register_view(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.username = slugify(obj.username) obj.save() return redirect('home:home') else: messages.error(request, 'error while creating your account, please try again.') context = {'form': form} return render(request, 'account/register.html', context) @unauthorizedUserCanView def login_view(request): if request.method == 'POST': email = request.POST.get('email') password … -
Websocket connection failed in Django and user matching query does not exist error
I am trying to create a one on one chat application using django channels,websockets and Redis.Tried implementing django channels from (https://youtu.be/RVH05S1qab8) but getting errors like this (from javaScript console).The line 253 is from views.py,the code for which is mentioned below.Also error in line 95 of models.py which is also mentioned in the code below. (from terminal) Also the message is not been sent to the other user in real time and the page has to be refreshed to get the message. Code for thread.html: {% extends "bookexchange/base.html" %} {% block content %} <h3>Thread for {% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</h3> <ul id='chat-items'> {% for chat in object.chatmessage_set.all %} <li>{{ chat.message }} via {{ chat.user }}</li> {% endfor %} </ul> <form id='form' method='POST'> {% csrf_token %} <input type="hidden" id="myUsername" value="{{ user.username }}"> {{form.as_p }} <input type='submit' class='btn btn-primary'/> </form> {% endblock %} {% block script %} <script src="https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js" integrity="sha512-B4skI5FiLurS86aioJx9VfozI1wjqrn6aTdJH+YQUmCZum/ZibPBTX55k5d9XM6EsKePDInkLVrN7vPmJxc1qA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> var loc=window.location var formData=$("#form") var msgInput=$("#id_message") var chatHolder=$("#chat-items") var me=$("#myUsername").val() var wsStart='ws://' if(loc.protocol=='https:'){ wsStart='wss://' } var endpoint =wsStart + loc.host + loc.pathname var socket= new WebSocket(endpoint) socket.onmessage=function(e){ console.log("message",e) var chatDataMsg=JSON.parse(e.data) chatHolder.append("<li>"+ chatDataMsg.message +"via"+ chatDataMsg.username +"</li>") } socket.onopen=function(e){ console.log("open",e) formData.submit(function(event){ event.preventDefault() var … -
Django and postgres: Bad request syntax
I started a new django project to create it around existing postgresql database. I followed django docs and installed psycopg2 and modified my settings file like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'northwind', 'USER': '********', 'PASSWORD': '****************', 'HOST': '127.0.0.1', 'PORT': '5050', } After that I typed inspectdb > models.py command which should create models from existing database and palce them in file. Nothing happened, had to stop process. Then I tried to reload local server but everything I get after using "python manage.py runserver" is this: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). So I stop it with ctrl+c and in the other terminal where I'm running postgre server I get this message: 2021-09-13 19:32:15,510: ERROR werkzeug: 127.0.0.1 - - [13/Sep/2021 19:32:15] code 400, message Bad request syntax ('\x00\x00\x00\x08\x04Ò\x16/') Server was working before that database switching from default sqlite to postgre, now I can't start it up. -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` ..., but received a `<class 'rest_framework.authtoken.models.Token'>`
I am trying to return authenticated user information like username, email, first_name, and last_name on MyProfile.vue using the serializer. I get this error and I can't find a way of solving this. The logic is like that: The authenticated user has token stores in localStorage, I get it via Axios request and send it to the View model in Django, where I use it to find who the user is and send this user to get method to send it back to the MyAccount.vue and show the user info. I am using Django Rest Framework and Vue.js. Hope you can help, I've been dealing with this problem for a week now. Thank you! PS: I am doing this because User.objects.get(current_user=request.user) returns AnonymousUser, even if I am authenticated. This is my Views.py: class UserDetails(APIView): def post(self, request, *args, **kwargs): serializer = UserAccountTokenSendSerializer(data=request.data) global token if serializer.is_valid(): token = serializer.validated_data['token'] user = Token.objects.get(key=token) self.user = user # global current_user # current_user = User.objects.get(username=user) # email = User.objects.get(email=user) # print(current_user, email) return user return Response(serializer.data) def get(self, request, *args, **kwargs): details = Token.objects.get(key=self.user) print(self.user) # HERE I TRY TO PRINT IT TO SEE IF IT WORKS AND THIS IS WHERE I GET THE … -
how to scan document using mobile came - django
i'm trying building a scanner from mobile phone camera to upload some documents into my django project , database is postgres class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) and this is my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = request.FILES.getlist('images') if images: for img in images: photo = Document.objects.create( booking=obj, docs = img ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) return render(request,'booking/add_img.html',{'obj':obj}) and this is my template <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} <div id="main_form" class="text-lg"> <p class="p-2 header rounded-lg text-center text-white">{% trans "adding new documents" %} {{obj.id}}</p> <div class="border border-purple-900 mt-2 rounded-lg p-2 text-center"> <p>{% trans "booking number" %}: {{obj.id}} </p> </div> </div> <hr> <div class="form-group m-3"> <label>{% trans "choose or scan some documents" %}</label> <input required name="images" type="file" multiple class="form-control-file"> </div> <button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button> </form> this only works for uploading existing documents , but i have to let user to upload their documents via their mobile phones .. thanks in advance -
How to retrieve count objects faster on Django?
My goal is to optimize the retrieval of the count of objects I have in my Django model. I have two models: Users Prospects It's a one-to-many relationship. One User can create many Prospects. One Prospect can only be created by one User. I'm trying to get the Prospects created by the user in the last 24 hours. Prospects model has roughly 7 millions rows on my PostgreSQL database. Users only 2000. My current code is taking to much time to get the desired results. I tried to use filter() and count(): import datetime # get the date but 24 hours earlier date_example = datetime.datetime.now() - datetime.timedelta(days = 1) # Filter Prospects that are created by user_id_example # and filter Prospects that got a date greater than date_example (so equal or sooner) today_prospects = Prospect.objects.filter(user_id = 'user_id_example', create_date__gte = date_example) # get the count of prospects that got created in the past 24 hours by user_id_example # this is the problematic call that takes too long to process count_total_today_prospects = today_prospects.count() I works, but it takes too much time (5 minutes). Because it's checking the entire database instead of just checking, what I though it would: only the prospects that … -
Django convert queryset to a list
I am trying to do a bulk insert using jquery ajax and django restframework. When I upload my data using the django restframework interface, it works and when I print the request.data I get this [{'name': 'Tenant 1', 'email': 'tenant1@gmail.com', 'phone_number': 619}, {'name': 'Tenant 2', 'email': 'tenant2@gmail.com', 'phone_number': 911}] However, when I upload it using jquery, I get the data as <QueryDict: {'name': ['Tenant 1', 'Tenant 2'], 'calling_code': ['254', '254'], 'phone_number': ['619', '911'], 'email': ['tenant1@gmail.com', 'tenant2@gmail.com']}> here is my code: in tenantsAdd.html: $(document).on('submit', '#create_tenant_bulk', function (event) { var form_data = new FormData(this); event.preventDefault(); $.ajax({ method: 'POST', url: '{% url "tenants:tenant-listcreate" %}', data: form_data, mimeType:'application/json', contentType: false, dataType: "json", processData: false, In my views.py: class CreateTenantAPIView(generics.ListCreateAPIView): queryset = Tenant.objects.all() serializer_class = TenantSerializer def create(self, request, *args, **kwargs): print('yaaaaaaaaaaaaaaaaaaaaaaaazweeeeeeeeeeeeeh') print(request.data) print(type(request.data)) many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data, many=many) if serializer.is_valid(raise_exception=True): saved_user= serializer.save(added_by=self.request.user) return Response({ 'success': 'user has been added succsfully', }) else: return Response({ 'error': 'you done f@#ckd up', 'error_list':serializer.errors.items() }) So baically, I am trying to turn this: <QueryDict: {'name': ['Tenant 1', 'Tenant 2'], 'calling_code': ['254', '254'], 'phone_number': ['619', '911'], 'email': ['tenant1@gmail.com', 'tenant2@gmail.com']}> Into this: [{'name': 'Tenant 1', 'email': 'tenant1@gmail.com', 'phone_number': 619}, {'name': 'Tenant 2', 'email': 'tenant2@gmail.com', 'phone_number': 911}] -
Bulk GET in Django REST Framework
I'm building an application using Django and Django REST Framework. I'm reasonably comfortable with base Django but I'm very much a newbie with DRF. Hoping someone can help me with the below. I have a list of dictionaries that want to send via my API as a single call, rather than sequentially sending request.get calls in, say, a loop (tediously slow, too many database hits etc.) I've built a list and serialised it to JSON which now looks something like: [ { "kingdom":"Plantae", "phylum":"Tracheophyta", "class_taxonomic":"Magnoliopsida", "order":"Apiales", "family":"Apiaceae", "genus":"Heracleum", "species":"mantegazzianum", "taxon_rank":"SPECIES" }, { "kingdom":"Plantae", "phylum":"Bryophyta", "class_taxonomic":"Bryopsida", "order":"Orthotrichales", "family":"Orthotrichaceae", "genus":"Zygodon", "species":"viridissimus", "taxon_rank":"SPECIES" }, { "kingdom":"Plantae", "phylum":"Tracheophyta", "class_taxonomic":"Magnoliopsida", "order":"Caryophyllales", "family":"Polygonaceae", "genus":"Fallopia", "species":"japonica", "taxon_rank":"SPECIES" } ] Is it possible to send this list to my model (taxonData) and return those model instances if they're present in the above list? If so, what would be the best way to achieve this? Would I need to use generics.ListAPIView and a custom get_queryset method? If I try this with the following code: # models.py class TaxonData(models.Model): kingdom = models.CharField(max_length=64, blank=True, null=True) phylum = models.CharField(max_length=64, blank=True, null=True) class_taxonomic = models.CharField(max_length=64, blank=True, null=True) order = models.CharField(max_length=64, blank=True, null=True) family = models.CharField(max_length=64, blank=True, null=True) genus = models.CharField(max_length=64, blank=True, null=True) species … -
Failed to build wheel for <package>
I've tried to install a package called mazelib, everytime i try to I get cannot build wheel for mazelib. I've tried reinstalling pip, download wheel from pip and even tried to download the uncached version still all dont work. ERROR: Failed building wheel for mazelib Running setup.py clean for mazelib Failed to build mazelib Installing collected packages: mazelib Running setup.py install for mazelib ... error Any help really appreciated. -
Is possible to pass a request parameter in a admin object?
I'd like to pass the request.user.first_name into a model from the admin panel. Is it possible? models.py class News(models.model): text = models.TextField() template.html <div class='container'> {{object.text | safe }} </div> Thanks so much -
Converting html + bootstrap files (using flex) into pdf - Django?
I am trying to create a webapp where, the data comes from a certain API and is saved into the database. Now, I want to create a pdf using the data. I had my html Code ready with custom css and bootstrap ( using display: flex; ). I already tried using the xhtml2pdf, reportlab libraries but am not able to get it right with CSS flex properties. The source for the HTML, and some python file are attached below. HTML File: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Invoice-ID</title> <style type="text/css"> /* Bootstrap CSS */ .col-md-7 { flex: 0 0 auto; width: 58%; } .container { width: 1320px; } .bg-light { background-color: #f8f9fa !important; } .nav { display: flex; flex-wrap: wrap; padding-left: 0; margin-bottom: 0; list-style: none; } .justify-content-center { justify-content: center; } .navbar { position: relative; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; padding-top: .5rem; padding-bottom: .5rem; } .navbar>.container-fluid { display: flex; flex-wrap: inherit; align-items: center; justify-content: space-between; } .navbar-light .navbar-brand { color: rgba(0, 0, 0, .9); } .navbar-brand { padding-top: .3125rem; padding-bottom: .3125rem; margin-right: 1rem; font-size: 1.25rem; text-decoration: none; white-space: nowrap; } .flex-column { flex-direction: column !important; } .d-flex … -
'QuerySet' object has no attribute 'info' in django
i am crating social media share button https://github.com/codingforentrepreneurs/Guides/blob/master/all/social_share_links.md trying this guide ant trying encode my model.info which is char field paste into status <a class="i-links" target="_blank" href="https://twitter.com/home?status=I'm%20going%20to%20learn%20to%20Code...%20Come%20build%20an%20web%20apsp%20with%20me!%20%23CFE%20and%20@justinmitchel%20{{ request.build_absolute_uri|urlencoded }}"> trying from urllib.parse import urlencode, quote_plus def ttt_read(request, title): ttt = movie.objects.filter(urltitle=title) share_string = quote_plus(ttt.info) if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank You For Your Comment') else: form = Commentform() return render(request, 'ttt_read.html',{'ttt':ttt,'form':form,'share_string':share_string}) but when i tried to render it thows above mentioned error so what i am doing wrong here -
Using 2 models in Django CreateView with input fields for only 1 model
I am trying to make a page like this where the quotes are randomly picked from quotes.models.Quote using classmethod Quote.get_random(): Quote1... by Author1 Quote2... by Author2 RichTextfield for user to comment on the quotes. The user should not be able to edit the quotes in this page, just the comment. But I want the relationship between the quotes and user's comment to be saved. I've looked at previous questions and answers but those were for using multiple forms in a view and the user can edit all fields. I also looked at package https://django-extra-views.readthedocs.io/en/latest/index.html but I don't think it helps my problem. I am stuck at displaying the quotes and passing the selected quotes to the form to be saved. Can someone help or suggest how I can make progress? Screenshot of page: Using {% get_quotes %} in the post.html template, I get a list of dictionary for the quotes. {% get_quotes 3 %} also works to generate 3 quotes. [{'id': 81, 'text': '..., 'tags': [76, 77]}, {'id': 75, 'text': ..., 'tags': [74, 75, 76, 77, 78, 79, 80, 81]}] But nothing happens when I try to loop through the list. {% for quote in get_quotes %} {{ quote }} … -
Annotate and compare 2 counts for SubQuery results
I'm trying to get 2 counts of a related table for comparison so I can output different status codes based on that comparison. Problem is I can't seem to get more than one count, as count itself eagerly evaluates the query and I get ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. This is the modelmanager query: class SuccessCode(Enum): SUCCESS = "Success" PARTIAL = "Partial" FAILURE = "Failed" completed = MyModel.objects.filter( backup=OuterRef("pk") ).completed() unsuccessful = ( MyModel.objects.filter(backup=OuterRef("pk")) .completed() .filter(model_field__isnull=False) ) return ( self.active() .annotate(complete=Subquery(completed.count())) .annotate(unsuccessful=Subquery(unsuccessful.count())) .annotate( success=Case( When( complete=F("unsuccessful"), then=Value(SuccessCode.FAILURE), ), When(unsuccessful=0, then=Value(SuccessCode.SUCCESS)), default=Value(SuccessCode.PARTIAL), ) ) ) So I need 2 counts - completed and unsuccessful (unsuccessful will by definition be a subset of completed - anywhere from 0 to all of the completed records). Then I have to compare these values. Any tips? -
Cannot assign "'..'": "ForwardFile.receiver" must be a "User" instance
The goal here is to allow a user who uploads a file to share it with intended recipients who is registered user in the system. The recipient can only then see a file when shared with them. To implement this logic, I have a dropdown where intended recipients are queried from the database. File models.py class ForwardFile(models.Model): file = models.ForeignKey(Document, related_name='documents', on_delete=models.CASCADE) receiver = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE) comment = models.TextField() created_by = models.ForeignKey(User, related_name='documents', on_delete=models.CASCADE) forwarded_at = models.DateTimeField(auto_now_add=True) File views.py for handling file forward function def forward_file(request, file_id): file = Document.objects.get(pk=file_id) managers = Manager.objects.all() users = User.objects.all() if request.method == 'POST': form = FileFowardForm(request.POST) if form.is_valid(): forward = form.save(commit=False) forward.file = file forward.receiver = request.POST.get('receiver', '') forward.created_by = request.user forward.save() create_notification(request, file.receiver, 'forward', extra_id=forward.id) messages.success(request, f"Document Forwarded successfuly to {forward.receiver}") return redirect('dashboard') else: form = FileFowardForm() return render(request, 'doc/file_forward.html', {'form':form, 'users':users}) File forms.py class FileFowardForm(forms.ModelForm): class Meta: model = ForwardFile fields = ['comment'] Template forward_file.html {% extends 'core/base.html' %} {% block content %} <h2 class="title">Forward {{ file.title}} - {{ file.category }}</h2> <form action="" method="POST"> {% csrf_token %} {% if form.errors %} {% for error in form.errors %} <div class="notification is-danger"> {{ error }} </div> {% endfor %} {% endif %} … -
Django Model ForeignKey Reciprocation
I'm wondering what the best way to reciprocate the existence of the ForeignKey would be for a model. I.e. I want to be able to see the associated ForeignKey in the Model in the admin page, not just the initial instance of the model. -
Django: Join Two Models without ForeignKey: (Can i Use Polymorphic Relation, if Yes Then How)
class Services(models.Model): id = models.BigAutoField(primary_key=True) medical_unit = models.ForeignKey(MedicalUnits, models.DO_NOTHING, related_name='services_medical_unit', blank=True, null=True) created_at = models.DateTimeField() updated_at = models.DateTimeField() name = models.CharField(max_length=500, blank=True, null=True) billing_code = models.CharField(max_length=500, blank=True, null=True) department_id = models.IntegerField(blank=True, null=True) assignable_type = models.CharField(max_length=500, blank=True, null=True) assignable_id = models.BigIntegerField(blank=True, null=True) department_service_id = models.IntegerField(blank=True, null=True) user_id = models.IntegerField(blank=True, null=True) is_active = models.BooleanField(blank=True, null=True) ward_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'services' class PackageServices(models.Model): id = models.BigAutoField(primary_key=True) billing_package = models.ForeignKey(BillingPackages, models.DO_NOTHING, blank=True, null=True) assignable_type = models.CharField(max_length=500, blank=True, null=True) assignable_id = models.BigIntegerField(blank=True, null=True) quantity = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: managed = False db_table = 'package_services' I want To access "PackageService" Through "Services". If Any Solution Please Help. -
raise ImproperlyConfigured(error_msg) in django
I am trying to host a django website in gcloud... i did some changes in settings.py file this is my code DATABASES = {"default": env.db()} # If the flag as been set, configure to use proxy if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None): DATABASES["default"]["HOST"] = "127.0.0.1" DATABASES["default"]["PORT"] = 5432 after adding this code into settings.py file i am facing below error File "C:\Users\CHANDU\Downloads\Unisoftone\unisoftone\website\website\settings.py", line 99, in <module> DATABASES = {"default": env.db()} File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 208, in db_url return self.db_url_config(self.get_value(var, default=default), engine=engine) File "C:\Users\CHANDU\AppData\Local\Programs\Python\Python38-32\lib\site- packages\environ\environ.py", line 281, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable can anyone help me -
Fetch Username in python Django using LDAP in intranetwork
We are stuck into the Problem. We have hosted python Django based website on our intraNetwork Linux Server. When any user(client machine) in same network access that website, the system needed to authenticate that user from LDAP directory and pass username to the System, Further System process will work on the same username. Please Note that user is not passing any credentials, because it is already logged in to the active directory on their machine. What we want: We want to Fetch the username of Client Machine using already logged in windows active directory from browser that access intraNetwork python Django Website(Without Providing Credentials again on Browser). The Url looks like: IP/PageName.html Note: Client Remote Machine Can be linux/Windows. Web Server Hosted Machine: Linux I have used: https://docs.djangoproject.com/en/3.2/howto/auth-remote-user/ ldap3 But for that user need to provide credentials on their remote machine when they hit the URL. But we want to authenticate and fetch username by using already logged in active directory. we believe that there must be a solution, so please guide the one. Thanks,