Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't execute queries when insert multi related objects in Django migration file
I want to initiate basic data of 4 related model in migration file. This is list of my models: Test QuestionCategory(with `Test` FK) Question(with `QuestionCategory` and `Test` FK) And also this is my function that import data in migration file: def step3(apps, db_alias): import pandas as pd import os file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'initial_data/PyTest-BasicData.xlsx') questions_df = pd.read_excel(file_path, sheet_name='Questions', engine='openpyxl', ) questions_list = questions_df.T.to_dict().values() QuestionCategory = apps.get_model("PsyTest", "QuestionCategory") Question = apps.get_model("PsyTest", "Question") for item in questions_list: category_title = None if pd.isna(item["category_title"]) else item["category_title"] category_type_choice = None if pd.isna(item["category_type_choice"]) else item["category_type_choice"] category_reference_title = None if pd.isna(item["category_reference_title"]) else item["category_reference_title"] reference = None int_test_pk =int(item["test_pk"]) if category_reference_title: try: reference = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_reference_title) except QuestionCategory.DoesNotExist: reference = QuestionCategory(test_id=int_test_pk, title=category_reference_title, category=1) reference.save() try: category = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_title) except QuestionCategory.DoesNotExist: category = QuestionCategory(test_id=int_test_pk, title=category_title, category=int(category_type_choice), reference=reference) category.save() try: _ = Question.objects.using(db_alias).get(test_id=int_test_pk, title=item["title"]) except Question.DoesNotExist: question = Question(test_id=int_test_pk, title=item["title"], row=int(item["row"]), is_active=item["is_active"], category=category) question.save() In another function I imported Test objects in migration file and all things goes well, But when I use multi models and relations in migration file -like above function-, I got this error: raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. How can … -
Django ModelsConditional ForeignKey
i have 4 Django Models (Team, Player, Game, Throw): class Team(models.Model): team_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Player(models.Model): player_id = models.AutoField(primary_key=True) team_id = models.ForeignKey(Team, on_delete=models.DO_NOTHING) name = models.CharField(max_length=50) class Game(models.Model): game_id = models.AutoField(primary_key=True) team1_id = models.ForeignKey(Team, related_name='team1', on_delete=models.DO_NOTHING) team2_id = models.ForeignKey(Team, related_name='team2', on_delete=models.DO_NOTHING) class Throw(models.Model): throw_id = models.AutoField(primary_key=True) game_id = models.ForeignKey(Game, on_delete=models.CASCADE) player_id = models.ForeignKey(???) score = models.IntegerField() Is there any option for the Throw model to set a condition on field player_id = models.ForeignKey(???), so that i can only select the players from the two teams in the game model ? -
Django: How do I change an image type to WebP in upload?
I have a website that has a blog, and the upload images are served just right but the image format slows down the website and I wanted to make them all be converted to WebP, which loads faster, on upload, is there any way to do that? my image field: from django_resized import ResizedImageField class Post(models.Model) image = ResizedImageField(size=[600, 500], quality=100, upload_to ='media/', default = 'media/placeholder.png') -
What is the difference between serializers in django-rest-framework and forms in django?
Just wanted to the difference between serializers.py in the Django-rest framework to forms.py in the Django app. I'm new to this concept and is not able to get a hold of it properly when I shifted to DRF from Django. Can Somebody Explain it? -
Updating serialized data's field Django
I have serialized data that was returned from a serializer and I want to update one field how can I do that? the first method which I am thinking of is to make another serializer that only updates the data and serialized it again. the second method which i am thinking to write a get method to fetch the serialized data and update by iterating a Response(serializer.data) can anyone help me on which method is good and how to proceed further? -
ManyToManyField makes an incorrect model
Please help me out my models.py # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.CharField(max_length=100, primary_key=True) found_articles = models.ManyToManyField( Information) search_details = models.ManyToManyField( Search) In my mysql workbench i can see that the table article_search is filled. BUT When i go to the admin page of my django project, i also see different objects, when i try to read them i get a weird error: Table 'kcbbe2.database_article_search_found_articles' doesn't exist", '42S02') I add some pictures picture of the admin page in django so to make clear, when i click on the object here in the picture i get the error. What did i do wrong with setting up my models? -
Django 'User' object has no attribute 'userprofile'
I'm using Django allauth for authentication and have created a UserProfile model to store additional details which a user can updated at a later stage. I'm trying to use signals to have the UserProfile instance created whenever a User is first created and to only update the UserProfile if it already exists. The problem I face is the UserProfile instance is not created, giving out this error: Traceback (most recent call last): File "/Users/QP/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/QP/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 99, in add_view return self._add_view(request, form_url, extra_context) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 126, in _add_view return super().add_view(request, form_url, extra_context) File "/Users/QP/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, … -
how to convert url() to path() in Django?
url_patterns=[ url(r'^(?P<postid>\d+)/preference/(?P<userpreference>\d+)/$', views.postpreference, name='postpreference'), ] I got this code from stackoverflow only but i know only path() but don't know url() I tried to understand and convert this url(r'^......) to path(...) using url() to path() but i also want to know how to use "\d+" in path() . If you know the answer do comment below whole path(....) -----> thanku in advance🙌 -
Django: join onto subquery without model
I'm looking to create a query that joins onto Postgres generate_series() function, to fill empty date intervals from a query. In essence I have a query like so: Select (case when DATE_TRUNC('week', foobar.date_key) is not null then DATE_TRUNC('week', foobar.date_key) else date.date end ) as "x_axis_time" from foobar left join ( select DATE_TRUNC( 'week', generate_series( some_start_date, some_end_date, '1 week'::interval ) AT TIME ZONE 'UTC') as "date" ) This creates a result set that has a entry for every week between 2 dates, with empty dates from FooBar filled by the left join onto DATE_TRUNC I'd like to do something similar in Django. I have a function for creating left join (subquery) which is fairly easy to do, but what I'm having trouble doing is creating a model that can generate the desired SQL for the select date_trunc(.... The Django Date_Trunc is as follows: join_subquery = Trunc( GenerateSeries( Cast(Value(datetime_start), output_field=DateTimeField()), Cast(Value(datetime_end), output_field=DateTimeField()), Cast(Value('1 week'), output_field=DurationField()), output_field=DateTimeField() ), 'week', output_field=DateTimeField() ) where GenerateSeries is: class GenerateSeries(Func): function = 'generate_series' def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function=self.function, template="%(function)s('%(expressions)s)", **extra_context ) This doesn't quite work though because it's just a Func, not a Queryset. Is there a way to create a model … -
How to do custom permission check for nested serializer with nested models having different permission in django
I'm building a webapp, where a user can create a team and add members and his/her projects. Everything is working fine, but now comes the permission part. One model will be Team and another Project. Right now i have written custom permission for both the models extending BasePermission. The operation/permission would be : User1 created a team Team1, can add any members and add his projects (no permission to add others project) members of Team1 can add their own projects and edit (CRU) projects added by others. No permission for the members to delete Team1, only creator can delete the team. A project can only be edited by the members of the team to which it is added. Others cannot. Only creator of the project can delete it. Permissions: from rest_framework import permissions from .models import Team,Project from rest_framework import serializers class ProjectPermission(permissions.BasePermission): message = "You do not have permission to perform this action with Project that doesn't belong to you or you are not a member of the team for this Project" def has_object_permission(self, request,view, obj): if not request.method in permissions.SAFE_METHODS: if request.method != "DELETE": if obj.team: #Team can be null when creating a project return obj.created_by == request.user … -
drf - trailing / in url throwing error while calling post api
views.py class FurnitureViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): permission_classes = [AllowAny] serializer_class = FurnitureSerializer queryset = Furniture.objects.all() @nested_view_set(FurnitureViewSet, 'furniture_id') class TablesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): permission_classes = [AllowAny] serializer_class = TableSerializer queryset = Table.objects.all() class OrdersViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet): authentication_classes = [] permission_classes = [AllowAny] queryset = Orders.objects.all() urls.py router = ExtendedSimpleRouter() furniture_router = router.register('furnitures', FurnitureViewSet, basename='furnitures') furniture_router.register('tables', TablesViewSet, basename="tables",parents_query_lookups=['furniture_id']) order_router = router.register('orders', OrdersViewSet, basename="orders") urlpatterns = [ path('', include(router.urls)), ] I have created a few apis for third party integration in my project. Furniture and Tables apis are working fine when called from their testing portal. Order post api is called as someurl.url/orders which throws 500 error. You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to someurl.url/orders/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I can't change the settings for the whole project for just 3 apis. How can I solve the url issue while still using ExtendedSimpleRouter since I'm using nested viewsets? -
Django, set formset/object date manually
I want to make a simple app for car mechanics but i have a problem which i cant figure out on my own since im a newbie. From start, i have list of services made to a car, and parts used, grouped by day in bootstrap accordion (like this https://ibb.co/8XWJx1S). In my edit view i grab all of services and parts from one certain day. In edit template i can add formsets dynamically (https://ibb.co/qBKL4Tk). The problem is when i add new service or part while editing, it saves with different date and then in list view its not grouped with services i want since its date is different. Is there a way to set this date manually to be the same as the other objects? Second option, not wanted but acceptable would be to update DATE.FIELD of other objects based on the new one, ive tried but failed models.py class Service(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) car = models.ForeignKey(Car, on_delete=models.CASCADE) service_name = models.CharField(max_length=150, verbose_name='Service', default=None) service_price = models.DecimalField(max_digits=20, decimal_places=2, default=None) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.service_name def save(self, *args, **kwargs): """Update parent model date_updated field whenever child object is added/edited""" self.car.save(update_fields=['date_updated']) super(Service, self).save(*args, **kwargs) class CarPart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, … -
PDF random massive white space added between HTML blocks
I have a problem with making a HTML template for a generated PDF file. The problem I have is randomly generated massive white spaces between HTML blocks. There's no styles added that could make that happen. I tried tinkering with page-break but that also didn't have anything to do with it. The problem also is that this does not happen when I try to save the PDF using a script that opens browsers' print option with a destination to save as a PDF like this . It happens only when I try to generate the PDF file beforehand like this . You can see on the left the massive white space randomly generated like here. The PDF is generated using WheesyPrint. <div> <h2>Zdjęcia funkcji w standardzie:</h2> <p class='m-0 p-0'><small>*Zdjęcie podlądowe. Wyposażenie może się różnić w zależności od modelu wózka oraz producenta</small></p> <div style="display:flex;flex-wrap:wrap;justify-content:flex-start;align-items:center;page-break-before:avoid;"> {{ wheelchair|function_photos_pdf:'standards' }} </div> </div> <div> <h2>Zdjęcia funkcji w opcji:</h2> <p class='m-0 p-0'><small>*Zdjęcie podlądowe. Wyposażenie może się różnić w zależności od modelu wózka oraz producenta</small></p> <div style="display:flex;flex-wrap:wrap;justify-content:flex-start;align-items:center;page-break-before:avoid;"> {{ wheelchair|function_photos_pdf:'optionals' }} </div> </div> This is the code where the white spaces are generated and just so You know I tried using and not using the page-break-before. The first … -
FieldError when trying to build REST API with Django REST framework
I am trying to build a REST API with Django REST framework with the intention of using this to interact with my React front end app. This is the general structure of my project --django-project ----peerplatform manage.py ------accounts models.py serializers.py urls.py views.py ------reactApp ------signup urls.py settings.py This is what I have in my views.py from rest_framework import viewsets from .serializers import ProfileSerializer from .models import Profile from .forms import SignUpForm from .tokens import account_activation_token class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all().order_by('name') serializer_class = ProfileSerializer My models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Serializers.py from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('user', 'full_ name', 'location', 'email', 'signup_confirmation') accounts.urls.py: from django.urls import path, include from rest_framework import routers from .import views router = routers.DefaultRouter() router.register(r'profiles', views.ProfileViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] and signup.urls.py: from django.contrib import admin from django.urls import path, include from django.urls import … -
Efficiently updating a large number of records based on a field in that record using Django
I have about a million Comment records that I want to update based on that comment's body field. I'm trying to figure out how to do this efficiently. Right now, my approach looks like this: update_list = [] qs = Comments.objects.filter(word_count=0) for comment in qs: model_obj = Comments.objects.get(id=comment.id) model_obj.word_count = len(model_obj.body.split()) update_list.append(model_obj) Comment.objects.bulk_update(update_list, ['word_count']) However, this hangs and seems to time out in my migration process. Does anybody have suggestions on how I can accomplish this? -
Django Related Through Models Not Using Soft Delete Model Manager
i am trying to retrieve only rows in a through model that are not deleted but keep getting all rows including the deleted ones. learnt it's a bug with using use_for_related_fields in the model manager according to this link: https://code.djangoproject.com/ticket/17746 i am trying to implement a follow/unfollow system like on social media platforms below is my code sample class BasicModelQuerySet(models.QuerySet): def delete(self): return self.update(is_deleted = True, deleted_at = timezone.now()) def erase(self): return super(BasicModelQuerySet, self).delete() class BasicModelManager(models.Manager): use_for_related_fields = True def get_queryset(self): return BasicModelQuerySet(self.model, self._db).filter(is_deleted = False).filter(deleted_at__isnull = True) class BasicModel(models.Model): deleted_at = models.DateTimeField(blank = True, null = True) is_deleted = models.BooleanField(default = False) objects = BasicModelManager() everything = models.Manager() class Meta: abstract = True class Listing(BasicModel): watchers = models.ManyToManyField(User, through = 'Watching', related_name = 'watchers') class Watching(BasicModel): user = models.ForeignKey(User, on_delete = models.RESTRICT, related_name = 'watching') listing = models.ForeignKey(Listing, on_delete = models.RESTRICT, related_name = 'spectators') sample tables id | user | ------------- 1 | User A | 2 | User B | id | listing | ---------------- 1 | Listing A | 2 | Listing B | # watchings table id | user | listing | deleted_at | is_deleted | ------------------------------------------------------------ 1 | User A | Listing A | | … -
error "Can only use .dt accessor with datetimelike values"
how can say me why i gived an error when i add this part in my views django new = output_df.groupby([output_df['Date and Time'].dt.date, 'PCR POS/Neg']).size().unstack(fill_value=0) new.sort_values(by=['Date and Time'], ascending=True) new['Total per date'] = output_df.groupby([output_df['Date and Time'].dt.date])['PCR POS/Neg'].count() new.loc['Total', :] = new.sum(axis=0) -
Django datetime fromisoformat: argument must be str
Hi I had this error while try to running server. It may cause by the datetime field. Can someone check it for me. models.py class Post(models.Model): author = models.ForeignKey("auth.User", on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approve_comment=True) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('mblog.Post', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=100) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) approve_comment = models.BooleanField(default=False) def approve(self): self.approve_comment = True self.save() def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def __str__(self): return self.text views.py class PostListView(ListView): model = models.Post def get_queryset(self): return models.Post.objects.filter(published_date__lte=timezone).order_by('-published_date') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'mblog/post_list.html' model = models.Post def get_queryset(self): return models.Post.objects.filter(published_date__isnull=True).order_by('created_date') And had anyway better to set default for the DateTimeField? Thanks for your time. -
django-session-security forcefully log out when closes tab
I'm currently using Django 3.2 and just try to integrate django-session-security to logout after session expiring. It's working fine. But I would like to ask, Is it possible to set forcefully log out when user closes tab? -
Django Model method that uses data from the model
I want to generate unique codes (e.g. "DXGH") and save it as a field in one of my models. The problem I have is that I do not know how to check against previously generated codes whenever a new object is created. Currently my models.py looks something like this: def code_gen(): random_string = '' for _ in range(4): random_string += chr(random.randint(97,122)) return random_string class Room(models.Model): room_code = models.CharField(default=code_gen) #other fields def __str__(self): return self.room_code #other methods def code_gen_unique(self): #I know the code below is incorrect code_list = [] for object in Room.Objects.all(): code_list.append(object.room_code) while True: temp_code = code_gen() if temp_code in code_list: continue break return temp_code Ideally I would set the default value of room_code to code_gen_unique, but I can't declare code_gen_unique() before my Room class, nor after it. I expect there is a much easier solution than I have considered, and would appreciate any help very much! Cheers -
Is there a way to access a private .zip S3 object with a django app's .ebextension config file deployed on elastic beanstalk
We have a django app deployed on elastic beanstalk, and added a feature that accesses an oracle DB. cx-Oracle requires the Oracle client library (instant client), and we would like to have the .zip for the library available as a private object in our S3 bucket, public object is not an option. We want to avoid depending on an Oracle link with wget. I am struggling to develop a .config file in the .ebextensions directory that will install the .zip S3 any time it is deployed. How can was set-up the config to install on deployment? os: Amazon Linux AMI 1 -
Import & Export Django Package Foreign Key CSV File Import Issue
I'm trying to import scores for student data and I keep getting the error message that the query doesn't match on the import. I tried designating the import to look at the state_province field as the foreign key, but I don't think I have it written correctly. Secondly for some reason on my date field keeps failing the null constraint which I'm not understanding why since the excel file data is in the correct format. I set in the model null=true for now to bypass.Here is my code. I appreciate the help. Thank you STUDENT MODEL # Where Basic Student Data Is Stored class Student(models.Model): studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True) student_name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50, default = "") last_name = models.CharField(max_length = 50,default = "") gender = models.CharField(max_length = 1,default = "") birth_date = models.DateField(blank= True) student_grade = models.CharField(max_length = 2, default = "") home_room = models.CharField(max_length = 5, default = "") student_enrollment = models.CharField(max_length = 2, default = "") school_number = models.CharField(max_length = 15, default = "") email = models.EmailField(default = "") projected_graduation_year = models.CharField(max_length = 4, default = "") counseling_goal = models.TextField(max_length = 500, … -
How to correctly use Fetch in JavaScript and Django?
I am trying to make a METAR decoder as shown: I am using fetch in Vanilla js and I plan to send the entered code to a Django view. From the Django view, the decoded data will be taken and displayed in the template. views.py def ToolsPageView(request): if request.method == "POST": jsonData = json.loads(request.body) metarCode = jsonData.get('Metar') return JsonResponse("Success", safe=False) return render(request, 'app/tools.html') urls.py ... path("tools", views.ToolsPageView, name="tools") tools.html <div class="metar-code-decode"> <form method="POST" action="{% url 'tools' %}" id="metar-form"> {% csrf_token %} <input type="text" placeholder="Enter METAR: " id="metar-value"> <br> <input type="submit" id="metar-button"> </form> </div> tool.js function getDecodedMetar() { let formButton = document.querySelector("#metar-button"); formButton.onclick = function (e) { let metarCode = document.querySelector("#metar-value").value; sendMetar(metarCode); //e.preventDefault(); //getMetar(metarCode); }; } function sendMetar(metarCode) { fetch('/tools', { method: "POST", headers: { "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({ Metar: metarCode, }), }); } I have used the same code for POST using fetch where I had to let user update his/her profile. And that worked. But, this does not work and the error keeps on changing from time to time after restarting the server. At the first try, there was no error produced and the server also showed a POST request being made. And the latest error which I … -
django error "Can only use .dt accessor with datetimelike values"
On my django app i gived this error AttributeError at / Can only use .dt accessor with datetimelike values line 28, in home results,output_df,new =results1(file_directory,file_directory2) line 111, in results1 new = output_df.groupby([output_df['Date and Time'].dt.date, 'PCR POS/Neg']).size().unstack(fill_value=0) Who can explain me what i have to change ? views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df,new =results1(file_directory,file_directory2) return render(request,"results.html",{"results":results,"output_df":output_df,"new":new}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) with open(names_loc, "r") as fp: for line in fp.readlines(): line = line.rstrip("\\\n") full_name = line.split(',') sample_name = full_name[0].split('_mean') try: if len(sample_name[0].split('SCO_')) > 1: sample_id = int(sample_name[0].split('SCO_')[1]) else: sample_id = int(sample_name[0].split('SCO')[1]) except: sample_id = sample_name[0] try: if listing_file['Test ID'].isin([sample_id]).any(): line_data = listing_file.loc[listing_file['Test ID'].isin([sample_id])] vector_name = line d_t = full_name[1].split('us_')[1].split('_') date_time = td(int(d_t[0]), int(d_t[1]), int(d_t[2]), int(d_t[3]), int(d_t[4]), int(d_t[5])) date_index = list(line_data['Collecting Date from the subject'].iteritems()) for x in … -
Access information from manytomany field django
my models.py file: # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.CharField(max_length=100, primary_key=True) found_articles = models.ManyToManyField( Information) search_details = models.ManyToManyField( Search) my views.py def show_articles_with_this_filter_id(request): results = Article_search.objects.filter(pk=1) for i in results: print(i.found_articles) what gets printed in my terminal: database.Information.None my db is filled: how my db looks like I would like to print out the found_articles value. in this case: https:__www.sciencedaily.com_releases_2021_12_211202141501.htmAircraft_reveal_a_surprisingly How can I achieve this?