Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to calculate average of difference of date time field in Django models and send it to rest API?
I have two models Gigs and Orders. and want to calculate the average of diffrence between order_start_time and order_completed_time of every gig. check my code its giving following error Cannot resolve keyword 'orders' into field. Choices are: category, category_id, details, gig, id, images, price, reviews, seller, seller_id, title please help! Models.py (in seller app) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if self._average_completionTime is not None: return self._average_completionTime return self.gig.aggregate(Avg('order_completed_time'-'order_start_time')) Models.py(in buyer app) focus on item field from seller.models import Gigs class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') order_start_time = models.DateTimeField(default=None) order_completed_time = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate(_average_rating=Avg('orders__time')) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs fields = ['id','title','category','price','details','seller','images','average_completionTime'] -
Move down the webpage upon form button click
I'm creating a webpage with Django, I've got a submit button on a form that once it gets clicked some data will be sent to my server. I could direct the webpage to a new URL once the form is submitted but instead I'd like to stay on the same webpage and simply have the screen focus move down to a new section, is this possible? I've seen a couple of examples of how to scroll down with href but the user won't be clicking an href link, they'll be clicking a submit button where scrolling down is just a secondary action to the button click if that makes sense. -
Is there any way to look up cache by contains and delete cache from MemCached in Django?
I have been working on a Django web app and initially I'm used database level cache. But now I need to change on Memcached. I would like to know about clearing cache from the Memcached. I'm using Python 3.8.10 and Django==3.1. We can clear cache in database level by filter by contains. So like, Is there any way to loop up cache using contains and delete from Memcached? What is the best way to achieve this? -
How to display database content without parsing an ID to the urls in django
I'm still a beginner in Django and building a management system, I wish to display content from the database using a for loop from 2 tables(GoCustomerRegisration and GoCustomerStatus). But unfortunately, when I iterate over one table the other table brings me only the last element of that table. What I really wish to do is iterate over both tables at once and each element should correspond to it on the other table. Check out my code below: something.html {% for item in detail %} <tr> <td> <a class="text-black text-decoration-none" href="{{ item.photo.url }}"> <img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a> </td> <td> <a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a> </td> <td class="text-capitalize">{{ item.type }}</td> <td>{{ item.destination }}</td> <td>{{ item.age }}</td> <td>{{ item.time_of_submission }}</td> <td> <span>{{ hello.value }}%</span> <div class="col"> <div class="progress progress-sm"> <div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ hello.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ h.value }}%;"><span class="visually-hidden"></span> </div> </div> </div> </td> {% endfor %} my views.py @login_required def preview(request): global hello detail = GoCustomerRegistration.objects.all() next_event = Event.objects.last() for i in range(1, (len(detail))+1): print(i) hello = GoCustomerStatus.objects.get(name_id=i) print(hello) context = { 'detail': detail, 'event': next_event, 'hello': hello, } return render(request, 'customers_preview.html', … -
Facebook: Graph API not able to get lead generation forms created for particular page
https://graph.facebook.com/v12.0/page-id/leadgen_forms?token=somethings not able to get data of lead generation forms created for this page anyone any comment meanwhile i am making API on python -
Get read topic count for followed category in a blog
I have a Django blog.. With a Language and SubTopic model. Every subtopic belongs to a language.. Users can follow a language and they'll only topics for that language #follow language, views.py class followLanguageView(TemplateView): template_name = 'lessons/lessons.html' def get(self, request, *args, **kwargs): language_id = kwargs['pk'] language = Language.objects.filter(id=language_id).first() skill_id = kwargs['pk'] skill = Skill.objects.filter(skill_follow__user=self.request.user).first() if language: if request.GET.get('unfollow'): LanguageFollow.objects.filter(language=language, user=self.request.user).delete() SkillFollow.objects.filter(skill=skill, user=self.request.user).delete() elif LanguageFollow.objects.filter(language__language_follow__user=self.request.user).exists(): LanguageFollow.objects.filter(language=language, user=self.request.user).delete() else: LanguageFollow.objects.get_or_create(language=language, user=self.request.user) return redirect(reverse('lessons')) I have a manytomanyfield in subtopic . Where users can mark a topic as read.. I want to get the total count of topics read for the specific category the user is following #read count, views.py @login_required def dashboard(request): language_follow = LanguageFollow.objects.filter(user=request.user) read = LanguageFollow.objects.filter(language__language_follow__user=request.user) read_count = SubTopic.objects.filter(read=read).count() total_topic = SubTopic.objects.filter(language__language_follow__user=request.user).count() percent = topicPercent(read_count, total_topic) return render(request, 'auth_user/userDashboard.html', { "read_count": read_count, "total_topic": total_topic, 'language_follow': language_follow, "percent": percent, }) #models.py class SubTopic(models.Model): title = models.CharField(_("title"), max_length=150) main_title = RichTextUploadingField(max_length=50000, null=True, blank=True, default=None) main_explanations = RichTextUploadingField(null=True, blank=True, default=None) language = models.ForeignKey(Language, verbose_name="topic_language", on_delete=models.CASCADE, related_name='follow_language', default=None) topic = models.ForeignKey(Topic, verbose_name=("topic"), on_delete=models.CASCADE, default=None) published = models.DateField(auto_now_add=True, blank=True, null=True) slug = models.SlugField(unique=True, max_length=50000, blank=True, null=True) read = models.ManyToManyField(User, related_name='read', blank=True) def __str__(self): return self.title def all_user(self): return list(self.subtopic_follow.values_list('user', flat=True)) def save(self, *args, **kwargs): if … -
How to disable add permission in the Django's admin page when the choices drop down field doesn't contain any data?
I have a model which has a template_name field which is shown as drop down in django admin. template_id = models.CharField(max_length=255, choices=template_data, unique=True) The template_data is getting populated from some other script. The format of template_data is : (('123', 'car'), ('456', 'bike')) This works fine when template_data has some values but when the template_data is an empty tuple, then I want to disable any add permission on admin page. Currently when the redis is off, the add button is disabled but how to do the same when the template_data is an empty tuple? Diasbled add permission when redis is off: def has_add_permission(self, request, obj=None): is_redis = RedisCache.is_redis_available() if is_redis is not True: return False return True RedisCache.is_redis_available(): Redis check is happening by calling is_redis_available func of RadisCache class. -
Django Delete a many to many field
I have 2 models User which is Django's auth_user, and HostCourse which has a many to many relationship with User class HostCourse(TimeStamped, models.Model): created_by = models.ManyToManyField(User, blank=True) ... When I delete some data from HostCourse, it throws the following error: ERROR: update or delete on table "courses_hostcourse" violates foreign key constraint "courses_hostcourse_c_hostcourse_id_ec1070c3_fk_courses_h" on table "courses_hostcourse_created_by" If I'll include on_delete=models.CASCASE, will it also delete the users of the respective HostCourse? If yes, how can I find a workaround, so that it deletes courses and not users? -
Annotate count of models by geometric intersection
Problem Assuming these models: class ModelA(models.Model): geometry = models.PolygonField() class ModelB(models.Model): geometry = models.PolygonField() How can I annotate to a ModelA queryset the count of intersecting ModelB instances using purely the ORM? Each ModelA's geometry should be intersected with the ModelBs' geometries and intersecting ModelBs counted. Eventually I would like to order_by the count of ModelB instances and find the ModelA instances that have the highest count of intersecting ModelB instances. What I have tried ModelA.objects.annotate( n_modelb=Count( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")) ), ) --> ProgrammingError: subquery must return only one column ModelA.objects.annotate( n_modelbSubquery( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")).count() ), ) --> ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. ModelA.objects.annotate( modelb_ids=Subquery( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")).values( "id" ), ), n_modelb=Count("modelb_ids"), ) --> CardinalityViolation: more than one row returned by a subquery used as an expression Related questions I think I am basically stuck at this comment to this answer: https://stackoverflow.com/a/46154553/9778755. This solution works when the models have a relationship. If you're trying to count on models without a relationship, this does not work. – Danielle MadeleyMar 17 '20 at 6:36 -
docker doesn't see heroku environment variables
I have django/react/postgres/docker app. When I try to push it to heroku it doesn't see environment variables from heroku config vars tab during build phase Is there a way to get heroku environment variables inside of the docker container? On heroku I attached Heroku Postgres addon, but since my env variables are hidden during build phase I'm getting an error: django.db.utils.OperationalError: could not connect to server Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Dockerfile.prod FROM python:3.8 RUN apt-get install -y curl \ && curl -sL https://deb.nodesource.com/setup_12.x | bash - \ && apt-get install -y nodejs WORKDIR /app/backend COPY ./backend/Pipfile* /app/backend/ RUN pip install pipenv && pipenv install --system WORKDIR /app/frontend COPY ./frontend/package*.json /app/frontend/ RUN npm install COPY . /app/ RUN npm run build WORKDIR /app/frontend/build RUN mkdir root && find . -type f -exec cp {} root \; RUN mkdir /app/backend/staticfiles WORKDIR /app ENV DJANGO_SETTINGS_MODULE=config.settings.prod RUN python backend/manage.py collectstatic --noinput EXPOSE $PORT RUN ["python", "backend/manage.py", "migrate", "--no-input"] CMD [ "python", "backend/manage.py", "runserver", "0.0.0.0", $PORT] settings.py ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env.str("DB_NAME", default="postgres"), 'USER': env.str("DB_USER", default="postgres"), 'PASSWORD': env.str("DB_PASS", default="postgres"), 'HOST': env.str("DB_HOST", default="localhost"), 'PORT': env.decimal("DB_PORT", default=5432) } } -
Django export to csv outputting just one row of data
I have 4 rows of data in a simple database and I would like to output it to a .csv. I have setup Django csv and everything seems to be working ok but I am only getting the first row. Can anyone tell me what is wrong with the code I have used as I obviously need all 4 rows. models.py class account(models.Model): Price = models.DecimalField('price', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) User = models.CharField('user', max_length=120, blank=True, null=True,) Account_Number = models.CharField('account Number', max_length=20, blank=True, null=True,) Date = models.DateField(default=now) def __str__(self): return str(self.User) views.py def stage(request): slist = account.objects.all() return render(request, 'stage.html', {'slist': slist}) def export_csv(request): response=HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['User', 'Account Number', 'Price', 'Date']) for file in account.objects.all().values_list('User', 'Account_Number', 'Price', 'Date'): writer.writerow(file) response['Content-Disposition'] = 'attachment; filename="Expenses.csv"' return response urls.py urlpatterns = [ path('', views.home, name="home"), path('stage/', views.stage, name='stage'), path('export_csv', views.export_csv, name='exportcsv') ] html <table id="dataTable" class="table"> <thead> <tr> <th>User</th> <th>Account Number</th> <th>Price</th> <th>Date</th> </tr> </thead> <tbody> {% for item in slist%} <tr> <td>{{item.User}}</td> <td>{{item.Price}}</td> <td>{{item.Account_Number}}</td> <td>{{item.Date}}</td> </tr> {% endfor %} </tbody> </table> <div><a href="{% url 'exportcsv' %}"> <button type="button" class="button">Export to CSV</button></a></div> -
Webmin alternative for Django, ubuntu server [closed]
A while ago i setup my django website in production by webmin. Unfortunately the django script in webmin became reserved for pro version. Do you know alternative to webmin where i can setup a django server (apache/nginx/psql) easly ? My server is on Ubuntu LTS. Thank for your time. -
how to display manytomanyfields in django admin
I add a likes field in my item models and would like to display all likes against each item in the admin panel. How I can do that currently is what my code looks like. I am getting this error:'User' object has no attribute 'likes' Model: likes = models.ManyToManyField(User, related_name='blog_posts') Admin.py class ItemAdmin(admin.ModelAdmin): list_display = ('title','author','item_category','date','get_products') list_filter = ('item_category',) def get_products(self, obj): return "\n".join([p.likes for p in obj.likes.all()]) -
Django swappable model foreign keys
Suppose I have a reusable app, that defines a model Person and a model Invite. A Person has a OneToOne field to AUTH_USER_MODEL and defines some basic fields (such as birthday). It is a swappable model, so that a project which uses this app can easily add other fields (such as gender, etc.) In my reusable app, I define a setting that provides the swapping model (otherwise, a default one will be used, exactly as django.contrib.auth does it. The Invite model has a OneToOneField to the swappable Person model and an email field. (I think, it's quite clear what this model is for). The model itself is swappable as well, but I don't think that this makes any difference for the kind of problem I am facing. reusable app models: class AbstractPerson(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='person') birthdate = models.DateField() class Meta: abstract = True class Person(AbstractPerson): class Meta(AbstractPerson.Meta): swappable = 'REUSABLEAPP_PERSON_MODEL' class AbstractInvite(models.Model): email = models.EmailField() person = models.OneToOneField(settings.REUSABLEAPP_PERSON_MODEL, on_delete=models.CASCADE, null=False, related_name='+') class Meta: abstract = True class Invite(AbstractInvite): class Meta(AbstractInvite.Meta): swappable = 'REUSABLEAPP_INVITE_MODEL' If I create the initial migration for my reusable app (using a dummy project and not swapping out my models), I get the … -
In django i want to change the date from views
I want to update the date from the backend views in django how can i did that here are my views where i want to do this def refresh_dashboard(request): date = datetime.datetime.now().strftime ("%Y%m%d") m = datetime.date.today() print(f"the date is {m}") customer = Customer.objects.all() for i in customer: # print(i.eligible) period = i.next_payment.strftime("%Y%m%d") if period <= date and i.eligible == True: x = Bill.objects.create(name = i.name,status ="unpaid",price = i.recuring_amount,generate_date = date) x.save() obj = i # obj.next_payment.strftime("%Y%(m+1)%d") obj.eligible = False obj.save() # print(f"the date is {date} and the obtain from the customer is {period}") # print(f"this customer {i.name} bill need to be generated") # print(f"the date is {datetime.datetime.now()}") return redirect('/') -
Can I retrieve the FCM token using Django?
I'm learning push notifications in PWA app using Django. Most of the tutorials seem to suggest retrieving the FCM token in the front end. There are some JS libraries to do this, but I was wondering if that is considered the best practice or should I retrieve the token in the back end? I'm using fcm-django and need to store the token as registration_id in my database. -
uWSGI call randomly injected into Python call stack?
I'm trying to get to the bottom of a weird bug (see here) - basically I'm seeing unexpected DB disconnects. To investigate I added a call stack dump to the disconnect code in Django - now I'm more confused than ever... What I'm seeing in the call stack is a completely unexpected call sequence, e.g.: ... File "/deployment/v_env/lib/python3.8/site-packages/qrcode/base.py", line 326, in __mod__ for item, other_item in zip(self, other)] File "/deployment/v_env/lib/python3.8/site-packages/qrcode/base.py", line 303, in __iter__ return iter(self.num) File "/deployment/v_env/lib/python3.8/site-packages/django/http/response.py", line 292, in close signals.request_finished.send(sender=self._handler_class) File "/deployment/v_env/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ ... Here the QR code library I'm using suddenly jumps to HttpResponse.close(). Another: ... File "/deployment/v_env/lib/python3.8/site-packages/django/db/models/query.py", line 1268, in _insert query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts) File "/deployment/v_env/lib/python3.8/site-packages/django/db/models/sql/subqueries.py", line 141, in __init__ super().__init__(*args, **kwargs) File "/deployment/v_env/lib/python3.8/site-packages/django/http/response.py", line 292, in close signals.request_finished.send(sender=self._handler_class) File "/deployment/v_env/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ ... Here some Django DB query code suddenly jumps to HttpResponse.close(). There's no way that this call stack is right - the code immediately above close() simply does not call that code, nor does it call a close() method that may somehow be bound to the wrong object. Now HttpResponse.close() can be called by uWSGI from the C runtime - the only … -
How to hide or delete the date in finish field without breaking the logic of the program
enter image description here Hi everybody. I am trying to solve this problem, but I do not know how to do it without breaking the logic of the program. I try to delete or hide the date field in finish because the difference between them will be no more than six hours. -
Design for Repetitive CRUD Operations with React and Django
I'm refactoring an old Django project (E-commerce) from server side rendered pages, to using a REST API instead and a React frontend. I'm trying to take learnings from the "v1" of the app and make them better in this refactor. Whilst there is a side to the app that offers business logic including e-commerce, payment functionality and customer facing storefront etc., the sort of "behind the scenes admin" functionality, like adding products, displaying them, adding coupons, displaying them etc., is all super repetitive. It's practically just a bunch of different Models with various fields and it's mostly just CRUD. Nothing complex at all. In the "v1" version, I leveraged Django's built in Forms for this and with this refactored version I plan on using Django REST and leverage their Generic Views and Viewsets where possible to reduce the amount of code needed, but also to keep it clean and generic. I'm a bit stuck on the frontend though. The idea of having to make a Create, Read, Update and Delete component for each "model" to show in the "dashboard" sounds awful. If it has to be done that way fine, but I'm wondering is there any sort of React library … -
django.core.exceptions.SynchronousOnlyOperation in Consumers.py
Here is the exception: Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. ... File "E:\socialnetwork\snsite\anime\consumers.py", line 48, in receive await self.fetch_messages() File "E:\socialnetwork\snsite\anime\consumers.py", line 21, in fetch_messages 'notifications': json.dumps(serializer.data) File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 745, in data ret = super().data File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "E:\socialnetwork\lib\site-packages\rest_framework\serializers.py", line 663, in to_representation return [ File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 280, in __iter__ self._fetch_all() File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "E:\socialnetwork\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "E:\socialnetwork\lib\site-packages\django\db\models\sql\compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "E:\socialnetwork\lib\site-packages\django\utils\asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /ws/like-comment-notification/ [127.0.0.1:50066] This is my consumers.py class NotificationConsumer(AsyncJsonWebsocketConsumer): async def fetch_messages(self): user = self.scope['user'] notifications = await database_sync_to_async(self.get_notifications)(user) serializer = NotificationSerializer(notifications, many=True) content ={ 'command': 'notifications', 'notifications': json.dumps(serializer.data) } await self.send_json(content) Although the WebSocket connection works but an error arises when it calls the fetch_message method. The problem seems to lie in json.dumps(serializer.data). Can you guys show me how to fix this? -
change django auth form password field error message
I have a form for my custom user sign up. like this: class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address') class Meta: # model = User model = Account fields = ('username', 'email', 'password1', 'password2',) def __init__(self, *args, **kwargs): """ specifying styles to fields """ super(SignUpForm, self).__init__(*args, **kwargs) for field in ( self.fields['email'], self.fields['username'], self.fields['password1'], self.fields['password2']): field.widget.attrs.update({'class': 'form-control '}) now I want to override the error messages. specially for password fields. error text: password2 This password is too short. It must contain at least 8 characters.This password is too common.This password is entirely numeric. also I do not want that password2 word in the beggining. -
Running django with ASGI?
I have a django app I using this [docker] (https://github.com/tiangolo/uvicorn-gunicorn-docker) for production deployment when I run the app using: gunicorn --log-level debug --workers 3 myapp.asgi:application --worker-class uvicorn.workers.UvicornWorker I see the warning ASGI 'lifespan' protocol appears unsupported. after reading here I understand that django do not support, but is this have any effect on my app? or where should the effect be? My app is using sync endpoints, for example: class MyViewSet(viewsets.ModelViewSet): queryset = My.objects.all() serializer_class = MySerializer is by running using ASGI the call to the database would be async? I don't use any web sockets I can see online many version for the asgi.py file, with manny different middleware and the django.setup() keyword, where can I find a documentation about the use cases? -
how to dynamically update html table in django
how to dynamically update search content under the hostname column in HTML table. the search content needs to be updated every time and the row number should increase accordingly on the basis of number of hostname entered by the user. this is my index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <body> <div> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website" autocomplete="off"> </label> <input type="submit" class="btn btn-primary" value="Search"> </div> <div> <div id="section2"> <center> <table class = "a"> <tr> <th>ID</th> <th>Hostname</th> <th>IP Address(IPv4)</th> <th>IP Address(IPv6)</th> <th>Port 1</th> <th>Port 2</th> </tr> <tr> <td>1</td> <td>{{ hostname }}</td> <td>{{ ipv4 }}</td> <td>{{ ipv6 }}</td> <td>{{ port1 }}</td> <td></td> </tr> this is my views.py from django.shortcuts import render import dns import dns.resolver import socket import sys def index(request): if request.method == 'POST': search = request.POST.get('search') # search = 'www.google.com' # search = "'" + search + "'" ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() return render(request, 'index.html', {"ipv4": IPv4, "ipv6": IPv6, "hostname": search}) -
Filter django model field based on another field
I have a Django model : class System(models.Model): system = models.CharField(max_length=100,verbose_name = "system ", db_column = "SYSTEM") product = models.ForeignKey(Product,verbose_name="product",db_column="PRODUCT_ID") program = models.ForeignKey(Program, verbose_name = "program", db_column = "PROGRAM_ID") def __str__(self): return self.system class Meta: db_table = 'user_system_data' verbose_name = "System" default_permissions = ('add', 'change', 'delete', 'view') And 3 tables : Product table : id PRODUCT 1 P1 2 P2 3 P3 Program table : id PROGRAM PRODUCT_ID 1 Pr1 1 2 Pr1 2 3 Pr3 3 System table : id SYSTEM PROGRAM_ID 1 S1 1 2 S2 3 My problem is when i try to a new System to a Program that has multiple entries but to different Products , in this case the PROGRAM_ID column value is set randomly and not the one that i want. I tried to add the Product information when adding a new System to filter the Program information but that didn't work. Is there a way i can filter the PROGRAM field based on the PRODUCT selection ? or any solution that i can use to have the correct information stored in the table ? -
Fetching database Items based on Instance Settings
I have created a database model that saved user-added settings to the database. and I would like to read from these database entries to print reports. I have already read from the forms instances to allow the use to edit the settings like this : Url : path('accConnect/setting/<int:setting_pk>', views.viewSettings, name='viewSettings' ), Views: setting = get_object_or_404(SettingsClass, pk=setting_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: form = SettingUpdateForm(request.POST, instance=setting) if form.is_valid(): form.save() return redirect('settingsHome') However while trying to do the same thing to read from the class' instace settings. I cannot seem to get the code right. The below is what I have tried to get these instances but im not sure it works with the model urls.py: #Reports path('reportsHome' , views.reportsHome, name='reportsHome'), path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports') Views.py: pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) This returns that the 'pk' is not found. So i'm not to sure what the proper way to do this is?