Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why only 1 value is bound?
The meaning of the program is to select analogues from the list and link them. I always bind only 1 value (to itself). How to fix it My view: def editpart(request, id, **kwargs): if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog part.analog.add(part.id) My model: class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
Pytest: Test user-editing view, object is not updating
I want to test my account_edit view, if the user's/customer's info is being updated properply. I'm new to pytest. View: @login_required def account_edit(request): if request.method == "POST": user_form = UserEditForm(instance=request.user, data=request.POST) if user_form.is_valid(): user_form.save() else: user_form = UserEditForm(instance=request.user) return render(request, "account/user/edit_account.html", {"user_form": user_form}) Factory: class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = Customer django_get_or_create = ("email",) email = "user1@gmail.com" name = "user1" mobile = "123456789" password = "user1" is_active = True the test_account_views.py: @pytest.mark.django_db def test_account_edit_post(client, customer_factory): user = customer_factory.create() client.force_login(user) response = client.post( "/account/edit/", data={ "name": "newname", "email": "newemail@gmail.com", }, ) print(user.name) assert response.status_code == 200 When Im printing out the email print(user.name) Im expecting it to be updated with newname. However receiving the old one (user1) AND the response status is also OK: 200. So it seems the problem is just that the user isn't updating. The problem is with testing code, not the django app itself(checked it). Thanks in advance for any help. -
Django models. Get all objects and sum duplicates
I have table in MySQl which describe Retail Demand models. row_num full_name quantity 1 4Пивовара - Похищение человеков инопланетянами (IPA - White. OG 17%, ABV 7,5%, IBU 67) 1 2 AF Brew - Autumn Fever Dreams: November (Sour - Fruited. ABV 7%) 1 3 Big Village - ABC-Kölsch (Kölsch. ABV 5.5%, IBU 20) 1 4 Big Village - Distrust (Pale Ale - New England. OG 15%, ABV 6%, IBU 25) 1 5 Big Village - Imaginarium (IPA - American. OG 16%, ABV 7%, IBU 60) 1 6 Big Village - Quartet X (Belgian Quadrupel. ABV 12,5%) 1 7 Gravity Project - It's A Mango (Cider - Other Fruit. ABV 5%) 1 9 Jaws - APA (Pale Ale - American. OG 13,5%, ABV 5%, IBU 43) 2 10 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 11 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 12 Jaws - Populism [Mosaic] (IPA - New England. OG 15%, ABV 6,5%, IBU 20) (Банка 0,45) 1 13 Jaws - Атомная Прачечная (IPA - American. OG 16%, ABV 7,2%, IBU 101) 4 14 Saldens - American Pale Ale Tears of Liberty … -
core error - Script timed out before returning headers: wsgi.py
I'm running a Django app on Apache/2.4.6 (CentOS) with mod_wsgi. When I visit my domain, after few minutes I get "Internal Server Error". The log file shows the following error - [core:error] [pid 9361] [client 132.72.41.107:55906] Script timed out before returning headers: wsgi.py The config file in sites-enable folder - <VirtualHost *:80> ServerName www.meshi1.cs.bgu.ac.il ServerAlias meshi1.cs.bgu.ac.il DocumentRoot "/var/www/meshi1.cs.bgu.ac.il" ErrorLog /var/www/meshi1.cs.bgu.ac.il/log/error.log CustomLog /var/www/meshi1.cs.bgu.ac.il/log/requests.log combined Alias /static /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static> Require all granted </Directory> WSGIDaemonProcess djangonautic python-home=/home/cluster/orelhaz/bin/rom_deshe/myenv/lib/python3.6 WSGIProcessGroup djangonautic WSGIScriptAlias / /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic/wsgi.py <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Thanks! -
Nested Array search in MongoDB/PyMongo while using aggregate
I am trying to search for a keyword inside array of arrays in a mongo document. { "PRODUCT_NAME" : "Truffle Cake", "TAGS": [ ["Cakes", 100], ["Flowers", 100], ] } Usually, i would do something like this and it would work. db.collection.find( {"TAGS":{"$elemMatch":{ "$elemMatch": {"$in":['search_text']} } }} ) But now, I changed this query to an aggregate based query due to other requirements. I've tried $filter , $match but not able to replicate the above query exactly.. Can anyone convert the above code so that it can directly work with aggregate? (I use PyMongo) -
Newer version of botocore breaks integration test
Imagine the follow functions, that should upload and copy something to S3 class TestAttachments(TestCase): # YAML is the only serializer supporting binary @override_env(AWS_DEFAULT_REGION='eu-west-1') # So the test doesn't fail depending on env. vars @my_vcr.use_cassette(serializer='yaml') def test_copy_attachments_to_sent_folder(self): with self.assertRaises( CopyAttachmentException, msg="Failed to copy attachments to sent folder for attachment URL: http://example.com/foo.jpg" ) as cm: copy_attachments_to_sent_folder(["http://example.com/foo.jpg"]) self.assertEqual(cm.exception.__cause__.__class__, InvalidAttachmentURL) TEST_UUIDS = ["uuid_0"] with patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS): result = copy_attachments_to_sent_folder([ f"https://{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}.s3.amazonaws.com/attachments/Test+video.mov" ]) self.assertEqual( [AttachmentMetadata( s3_key=f"attachments/sent/{TEST_UUIDS[0]}/video/quicktime/Test video.mov", filename="Test video.mov", mime_type="video/quicktime", size=178653, )], result ) It should test the following function: def copy_attachments_to_sent_folder(urls: List[str]) -> List[AttachmentMetadata]: # Copy the attachment to the sent folder in parallel with futures.ThreadPoolExecutor(max_workers=4) as executor: urls_by_future = {executor.submit(copy_attachment_to_sent_folder, url): url for url in urls} results_by_url = {} for future in futures.as_completed(urls_by_future.keys()): try: results_by_url[urls_by_future[future]] = future.result() except Exception as e: raise CopyAttachmentException( f"Failed to copy attachments to sent folder for attachment URL: {urls_by_future[future]}" ) from e # The futures can complete out-of-order, so we need to re-order them to match the original order here return [results_by_url[url] for url in urls] Which finally uses this function inside: def copy_attachment_to_sent_folder(url: str) -> AttachmentMetadata: aws_session = attachments_aws_session() s3_client = aws_session.client("s3") parse_result = urlparse(url, allow_fragments=False) # Allow both with/without AWS region in hostname attachment_hostname_regex = fr"{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}\.s3\.(.+?\.)?amazonaws\.com" … -
How to use for loop inside map python
I have a function that returns a list of numbers. But I know in other languages like JS we don't need to set a variable like c = 0. I see about map in python but I don't know how can I do it Here is my function: def get_bought_passenger_count(self): c = 0 for book in self.bookings.all(): c += book.passenger_count return c I want to do this with map function -
Django orm for multiple foreign key
I have a existing old database and I am trying to join 3 tables with django orm: class Orderlist(models.Model): record = models.IntegerField(db_column='RECORD', unique=True, primary_key=True) vechileid = models.CharField(db_column='vechileid ', max_length=10, blank=True, null=True) class Orderitem(models.Model): ' ' orderid= models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='ORDERID', blank=True, null=True) ' ' class Vehicle(models.Model): ' ' vechileid = models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='vechileid ', blank=True, null=True) ' ' I am trying to join as below: Select ... from Orderlist LEFT OUTER Orderitem ON Orderlist.record=Orderitem.orderid, LEFT OUTER JOIN Vehicle ON Orderlist.vechileid =Vechile.vechileid WHERE ... every time i try to join orderlist and vehicle it joins as orderlist.record=vehicle.vechileid How can i write the above sql query into django orm? -
Django: "SELECT field, count(field) FROM table GROUP BY field" being field an object
I've got next issue. Having next tables: products_table: id product_type serial_number 1 1 FX2002 2 1 FX2003 3 2 FX2004 4 2 FX2005 5 2 FX2006 product_types_table: id element 1 laptop 2 mouse 3 screen In products_table, product_type is a foreign key to product_types_table. I need to execute next query: SELECT product_type, count(product_type) AS quantity FROM products_table And get: product_type quantity 1 2 2 3 I've tried: queryset = products_table.objects.all().values("product_type").annotate(quantity=Count("product_type")) What returns next queryset: [{'product_type':1, 'quantity':2}, {'product_type':2, 'quantity':3}] I need 'product_type' field to be an object instead of integer, so element field can be called as: element = queryset[0]['product_type'].element Getting 'laptop' if I print element variable. I need to convert this data into JSON as well, and I need next response: [ { id: 1, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2002' }, { id: 2, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2003' }, { id: 3, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2004' }, { id: 4, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2005' }, { id: 5, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2006' } ] How can I do it??? Thank all of you for your time. -
Django - database exception - custom exception handler
Does Django provide a possibility to implement a custom exception handler over the database layer? I want to catch database exceptions, check error codes, and on some error codes -> wait for a while and retry the query. Is it possible in the Django? -
Two variables in single url pattern without '/'
I want to add 2 variables in single url pattern without '/' like this /<location-name>-<cityname>/. both are slugs. Location name can have 2-3 words and city name also can have 1-4 words. I tried path(/<location-name>-<cityname>/,..) but django is taking last word as city and rest as location. Like If I try /location-name1-city-name2/ then location-name-city is location and name2 is city. How can I do this? -
How to fix 'ManyToManyDescriptor' object has no attribute 'add'?
My viev def editpart(request, id, **kwargs): PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) form = PartForm(request.POST, request.FILES) if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog Part.analog.add(Part.id) My model class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
No module named ldap.filter in /usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py
This error occurs when i was trying to set up a new django project intergreted with django_auth_ldap in Ubuntu server, the environment & prerequisite for ldap are all installed successfully.The other project on the same server runs properly with no issues. Really need help full error message below: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/ldap/project/ldap/ldap/settings.py", line 17, in <module> from django_auth_ldap.config import LDAPSearch File "/usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py", line 36, in <module> import ldap.filter ModuleNotFoundError: No module named 'ldap.filter' During handling of the above exception, another exception occurred: … -
Point is not showing on a right place in admin panel while using geodjango?
I have taken my current location longitude and latitude from google Map. And when I'm adding an entry with that log/lat value. The pointer is not identifying the right place. As you can see in the pictures below. This is how I'm adding point in db. Profile.objects.create( owner=obj.owner, name=obj.ground_name, phone_no=obj.phone_no, location=GEOSGeometry('POINT (31.520370 74.358749)', srid=4326), address=obj.address, state=obj.state, city=obj.city, country=obj.country ) on admin panel on google map -
Request URL: Category 404
I have, Page not found (404) I can't know where is the mistake I made. urls.py from .views import ( PostListView, PostListViewHome, CategoryView, ) from . import views urlpatterns = [ path("", PostListViewHome.as_view(), name="Blog-home"), path("category/<str:cats>", views.CategoryView, name="category"), ] views.py def CategoryView(request, cats): return render(request, 'category.html', {'cats':cats}) -
Blacklist token not working in JWT Django?
My view is like this class LogoutView(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = () def post(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) My url config is urlpatterns = [ path('logout/', LogoutView.as_view(), name='logout') ] When i call this api I get bad request error. I also tried using auth logout view but i get this Forbidden (Origin checking failed - chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop does not match any trusted origins.): logout/ -
How to remove date in pandas dataframe
How to remove date in datetimeformat 2022-06-20 14:59:02.559748+05:30 (14:59:02) #only time df = pd.DataFrame(queryset) df['duration'] = pd.to_datetime(df['stoptime']) - pd.to_datetime(df['starttime']) print(df['duration'] ) # "0 days 00:00:09.892016" TO 00:00:09 -
How to redirect after add/edit/delete in django
when i try to redirect after add/edit/delete operation i'm redirecting to the page i wanted but can not see the existing data, but after click on url section of browser and tap enter on it or go to other page and return to this one than it is showing me the data. Let me share a video link of deleting records. - https://drive.google.com/file/d/1Qyt_gxFoBe74DH_2rLbme9PD58Ll1z3I/view?usp=sharing and here is the code of deleting too. views.py def deleteuser(request, id): # user = get_object_or_404(AddContact, id = id) user = AddContact.objects.filter(id=id).delete() context = { 'user' : user } return render (request, "adduser.html", context) URL.py path('deleteuser/<id>', views.deleteuser, name="deleteuser"), html button <a href="/deleteuser/{{vr.id}}" class="btn btn-danger" data-target="success-modal-delete"><span class="fa fa-trash"></span> Delete</a> -
Why doesn't it print logs to the file?
Please tell me why it does not print a 404 error to a file? It is output to the console, but the file is empty Not Found: / [21/June/2022 11:52:02] "GET / HTTP/1.1" 404 2178 LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', } }, 'handlers': { 'console':{ 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'class':'logging.FileHandler', 'formatter': 'verbose', 'filename': 'information.log' }, }, 'loggers': { 'main': { 'handlers':['console','file'], 'propagate': True, 'level':'INFO', } } } -
Django 4: problem with auth.authenticate, it returns None
I continue my progression with Django 4. But I have a new problem. my login code does not work, yet I followed the doc (I believe). The problem is at this level in my view.py. user=auth.authenticate(email=email, password=password) it returns none Could someone explain to me why the code does not work. Did I forget something? Here is my html code {% extends 'base.html' %} {% block content %} <section class="section-conten padding-y" style="min-height:84vh"> <div class="card mx-auto" style="max-width: 380px; margin-top:100px;"> <div class="card-body"> <h4 class="card-title mb-4">Sign in</h4> {% include 'includes/alerts.html' %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control" placeholder="Email Address" name="email"> </div> <!-- form-group// --> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <!-- form-group// --> <div class="form-group"> <a href="#" class="float-right">Forgot password?</a> </div> <!-- form-group form-check .// --> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Login </button> </div> <!-- form-group// --> </form> </div> <!-- card-body.// --> </div> <!-- card .// --> <p class="text-center mt-4">Don't have account? <a href="{% url 'register' %}">Sign up</a></p> <br><br> </section> {% endblock %} and my view code def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) # messages.success(request, … -
Django Rest Framework: generics.RetrieveUpdateDestroyAPIView not working for the given below condition
In this generic APIView when I'm trying to log in through a non-admin user it is giving "detail": "You do not have permission to perform this action." but working fine for the admin user. I don't whether the problem is in code or permission.py I've shared my Views.py, permissions.py, and models.py for the same. If there is any mistake in my def get_queryset(self): please do let me know. Thank you!! class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsUserOrIsAdmin] # queryset = Booking.objects.all() # serializer_class = BookingSerializer def get_queryset(self): if self.request.user.is_admin == False: user_data= self.request.user book = Booking.objects.filter(user= user_data) return book else: book = Booking.objects.all() return book serializer_class = BookingSerializer permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) views.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def … -
Need help in asinging values for Choices in Choice Field in Django
models.py class Survey_Answer(models.Model): CHOICES = [('Disagree Strongly', 'Disagree Strongly'), ('Disagree', 'Disagree'), ('Undecided', 'Undecided'), ('Agree', 'Agree'), ('Agree Strongly', 'Agree Strongly')] question = models.ForeignKey(Survey_Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=20, choices=CHOICES, default='Undecided') date_published = models.DateTimeField('date published', auto_now_add=True) created_at = models.DateTimeField('created at', auto_now_add=True) def __str__(self): return self.answer_text + ' - ' + self.question.question_text This is my models.py. I need help in assigning value for a particular option in CHOICES( Eg: 5 points for Agree Strongly option). If a user selects an option from choices, he should be getting points based on the option he selected -
I could not return soap response
I need to write a soap service which gets soap request and return soap response. I could handle sending soap request with zeep client library, everythin correct. But i couldnt send any soap response it shows the same error:) import logging from datetime import datetime from spyne import Application, rpc, ServiceBase, AnyDict from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from invoice.api.russian_webservice.complex_models import Consignor, Request1Type, Request31Type, Request91Type, CertificateMaximumType, CertificateMinimumType, Response91Type from exim.models import ExportFSS, ImportFSS class RussianIntegrationApiView(ServiceBase): @rpc(Request91Type, _returns=AnyDict, _out_variable_name="Response91") def getResponse91(ctx, request91type): try: logging.info( f'Initialized objects {str(Request91Type).encode("utf-8")}') error_message = None error_code = None import_fss = ImportFSS.objects.create( number=request91type.certificate.number, given_date=datetime.strptime( request91type.certificate.date, '%d.%m.%Y'), exporter_name=request91type.certificate.consignor.name, exporter_country=request91type.certificate.departure_country, exporter_address=request91type.certificate.consignor.place, importer_name=request91type.certificate.consignee.name, importer_country=request91type.certificate.destination_country, importer_address=request91type.certificate.consignee.place, transport_method=request91type.certificate.transport.declared_type, transport_number=request91type.certificate.transport.number, disinfected_date=datetime.strptime( request91type.certificate.disinfection.date, '%d.%m.%Y'), treatment_method=request91type.certificate.disinfection.method, chemical=request91type.certificate.disinfection.chemical, duration_and_temperature=request91type.certificate.disinfection.temperature_times, concentration=request91type.certificate.disinfection.concentration, extra_info=request91type.certificate.additional_info, ) return { "GUID": CertificateMinimumType.guid_generate(), "SendDateTime": "2022-04-11T19:50:11 ", "Certificate": CertificateMinimumType.generate(), "Status": "Выдан", "StatusCode": "1601", "Inspector": "" } except Exception as e: logging.info(f'Exception occurred: {str(e)}') def on_method_return_string(ctx): ctx.out_string[0] = ctx.out_string[0].replace(b'soap11env', b'soapenv') ctx.out_string[0] = ctx.out_string[0].replace(b'tns', b'mun') ctx.out_string[0] = ctx.out_string[0].replace(b'GUID', b'm:GUID') ctx.out_string[0] = ctx.out_string[0].replace( b'SendDateTime', b'm:SendDateTime') ctx.out_string[0] = ctx.out_string[0].replace(b'Act', b'm:Act') ctx.out_string[0] = ctx.out_string[0].replace(b'Date', b'm:Date') ctx.out_string[0] = ctx.out_string[0].replace(b'Number', b'm:Number') ctx.out_string[0] = ctx.out_string[0].replace(b'Blanc', b'm:Blanc') ctx.out_string[0] = ctx.out_string[0].replace(b'OldDate', b'm:OldDate') ctx.out_string[0] = ctx.out_string[0].replace( b'CountryCode', b'm:CountryCode') ctx.out_string[0] = ctx.out_string[0].replace( b'ExpirationDate', b'm:ExpirationDate') ctx.out_string[0] = … -
Can I use ContentType.objects.get in templatetags?
I kept get this error while attempting to use contenttype in the templatetags. django.contrib.contenttypes.models.ContentType.DoesNotExist: ContentType matching query does not exist. I am trying to get an object by passing the modelname and pk as string to the simple_tag. Below is the codes. I have other custom filters in the same file that work fine. # in templatetags\srrp_tags.py from django import template from django.contrib.contenttypes.models import ContentType register = template.Library() @register.simple_tag def get_object(modelname, id): ctype = ContentType.objects.get(model=modelname) # this line trigger the error model = ctype.model_class() return model.objects.get(pk=id) In my html, model and primary are both string value # in templates\srrp\index.html {% load srrp_tags %} ... {% get_object modelname|title primary %} I have use the exact same code for the Contenttype in the view.py and it retrieve the required model with no issue. # in view.py class srrpListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): ... def get_queryset(self): modelname = self.kwargs.get('modelname') ctype = ContentType.objects.get(model=modelname) # same code self.model = ctype.model_class() return self.model.objects.select_related().values() Any advice is much appreciated. Thank you -
How to prefetch or use select related in reverse generic relation in django?
Assume i have two models: class A: content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) attached_object = fields.GenericForeignKey('content_type', 'object_id') class B: some_field = GenericRelation(class A) Now I have a scenario where i need to list all of class B instances, and in that result list, i need to include some of class A which is related to class B. While trying to do that, obviously it is leading to as many query hits as there are instances of class B. I have searched all online forums to try and reduce queries in this case. instances_of_b = B.objects.all() for instance in instances_of_b: some_list.append(instance.related_instance_of_class_A.some_field_of_class_A) To get related_instance_of_class_A, i am using ContentType.objects.get_for_model(content_object) Is there any way to use select_related/prefetch related in this case?