Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to process JSON response from TwelveData API in Template?
In a hobby project, I am using TwelveData API to receive Time Series Data. I am using JSON format response and able to check each data (example: open, close, high, and etc.) from Python side, but the problem arise when I am trying to show those data in Django Template page using the for loop. The JSON response is similar to below image: When I write the following for loop in the template: {%for r in result %} {{r}} {%endfor %} It prints GOOGL, AAPL, AMZN, and TSLA <-- which is pretty good. Now when I write another for loop like: {%for r in result %} {%for k in result.r %} {{k}} {%endfor %} {%endfor %} It prints nothing except blank page. So I rewrite the main for loop as follows: {%for r,v in result %} {{v}} {%endfor %} It prints ValueError: Need 2 values to unpack in for loop; got 5. Does anyone help me to identify how can I run the loop accurately so that I can get/print (maybe inside a table tag) the JSON response data as follows: open, close, high, and etc. Thanks -
Django template access dictionary key
Currently I am passing a dictionary with multiple keys from my views to django template, and the first key contains a list with all the wanted keys, and I want to have a nested loop to loop inside the first key so I can access inside the wanted keys. dict = { "list1" = ["name1", "name5"] "name1" = [] "name2" = [] "name3" = [] "name5" = [] } In this case, I only want to access dict['name1'] and dict['name5'], in Python I can do something like: for name in dict['list1']: for l in dict[name]: do things I want to know if I can do the same with django template inside html file -
django rest framework - how to log a slow API
django - 2.2.12 nginx - 1.14.0 (Ubuntu) uWSGI - 2.0.18 (64bit) My Django is slowing down during busy times. I want to find the cause. I found drf-api-tracking which can take slow log but I couldn't use it because I am using GenericViewSet. Are there any similar libraries or performance debugging methods? It is fast when I test and when there are few people. So it is difficult to debug. When there are the most people, the django server's cpu uses 45% and the AWS RDS cpu uses about 50%. I don't think it's a computer resource problem. So I want to log a slow API. How is it best to do it? Or is there a better way to debug? -
How to Filter by distinct field value in Django? Cannot use distinct() function because of Mysql database
I have a customer group table class customerGroupMaster(models.Model): customer_group_name = models.CharField(max_length=50) customer_group_id = models.CharField(max_length=20, null=True) customer_id = models.ForeignKey(customerMaster, on_delete=models.PROTECT) I want to filter the queryset by unique customer_group_id field in the ListAPIView class. class customerGroupNameFilter(generics.ListAPIView): queryset = customerGroupMaster.objects.annotate(num_of_group=Count('customer_group_name', distinct=True)) serializer_class = customerGroupMasterSerializers permissions_class = [IsAuthenticated] So for exapmle: Customer group table | pk | customer_group_id | customer_group_name | customer_id | -------- | -------------- | -------- | -------------- | | 1 | 1 | group 1 | 1 | | 2 | 1 | group 1 | 2 | | 3 | 2 | group 2 | 3 | | 4 | 3 | group 3 | 4 | | 5 | 3 | group 3 | 5 | After filter: Customer group table | pk | customer_group_id | customer_group_name | customer_id | -------- | -------------- | -------- | -------------- | | 1 | 1 | group 1 | 1 | | 3 | 2 | group 2 | 3 | | 4 | 3 | group 3 | 4 | -
Django - "This Field is Required" error on Password field
On my django website, I'm unable to submit my form. Although I have every field filled out, my password field continues to say "This field is required" even as I have typed something in the password field as well. I have tried removing the required attribute for the password tag but that has not helped. Here is my code: views.py: def signup(request): #If user completes the form (hits the sign up button) #Send form data to url /signup-complete/ (see signup.html) if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = User.objects.create( username= form.cleaned_data['email'], #Note although there is an email field, we don't use it to prevent redundancy first_name = form.cleaned_data['first_name'], last_name = form.cleaned_data['last_name'], password = form.cleaned_data['password'], ) #Extended attribute, must be added seperately user.user_extend.is_student = form.cleaned_data['is_student'] user.save() print('user is now created') return HttpResponseRedirect('') #Render form else: form = SignUpForm() return render(request, 'mainapp/signup.html', {'form': form}) signup.html <!-- action="/signup_complete/"--> <form action="" method="post"> <!--Security, Cross Site Request Forgery Protection --> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} <div class="form-group"> {{ field.errors }} <!--or field.name == 'confirm_password'--> {% if field.name == 'password' %} {{ field.label_tag }} <input name="{{ field.name }}" class="form-control" type="password" required> {% elif field.name == 'email'%} … -
how to set value of range slider to value received from database in django
<input type="range" name="TaxRateRange" class="form-range slider" min="0" value='{{ form.taxrate }}' max="100" step="0.5" id="myRange"> this is range slider, trying to set value of it to the value received from the database -
Filter in ManyToManyRelationship in django
I am a newbie in django so this might be a noob question. I have to models class Field(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class Foo(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=255) fields = models.ManyToManyField('Field') def __str__(self): fields = [field.name for field in self.field.all()] return f'Title: {self.title} Field: {fields}' Now, I see the Foo as ['Title foo with field: [baz, bar]] Now.. I am trying to do this fields = set(Fields.objects.name) for field in fields: filtered_foo = Foo.objects.filter(fields__in =[field] But # print(filtered_foo) returns None My question is.. how do I filter a model based on another model which is manytomany relationship. -
can you help me my django code will not work
I am trying to make a website with django and I think i did every thing write but when i try to go to the website it says that it will not connect and this site can not be reached. My internet is working but i dont know what to do. -
when testing api from test.py getting Doesnot exist , matching query does not exists and while testing same api from postman it runs perfectly
test.py from django.test import TestCase, Client import json from django.urls import reverse from rest_framework import status from ..serializers import * from ..models import * client = Client() class Parking(TestCase): def setUp(self): self.park_data = { "car_id": 36, "slot_id": 327 } def test_unpark(self): unpark_data = { "car_id": 33, } response = client.post( reverse('unpark'), data=json.dumps(unpark_data), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py @api_view(['POST']) @csrf_exempt def unpark_my_car(request): car_id = request.data.get('car_id') if car_id is not None: car_object = Car.objects.get(id=car_id) if car_object: slot_id = car_object.slot_id slot_object = Slot.objects.get(id=slot_id) slot_object.parked_car = None slot_object.status = "VACANT" slot_object.save() park_id = car_object.park_id park_object = ParkingArea.objects.get(id=park_id) valet_id = car_object.valet_assigned_id valet_object = Valet.objects.get(id=valet_id) valet_object.is_Currently_Parking = False valet_object.vehicle_assigned = None valet_object.save() park_object.filled_parking_slots = park_object.filled_parking_slots - 1 if park_object.status == "FULL": park_object.status = "VACANT" notify_owner_car_is_unparked.delay(park_object.id) notify_airport_security_car_is_unparked.delay(park_object.id) park_object.save() car_object.is_parked = False car_object.slot_id = None car_object.park_id = None car_object.valet_assigned_id = None car_object.save() return Response(status=HTTP_200_OK, data={'msg': 'Car Un-parked'}) else: return Response(status=HTTP_400_BAD_REQUEST, data={"msg": 'Car not Found'}) else: return Response(status=HTTP_400_BAD_REQUEST, data={"msg": "car id provided is null"}) console Saurabh@DESKTOP-Q8U2ADF MINGW64 /f/Fellowship/ParkingLot/Parking_Lot (UC-9) $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ........E ====================================================================== ERROR: test_unpark (ParkingSystemApp.tests_parking.test_views.Parking) ---------------------------------------------------------------------- Traceback (most recent call last): File "F:\Fellowship\ParkingLot\Parking_Lot\ParkingSystemApp\tests_parking\test_views.py", line 34, in test_unpark content_type='application/json' File "F:\Fellowship\ParkingLot\VirtualEnv\lib\site-packages\django\test\client.py", line 748, in … -
TemplateDoesNotExist at /index/
web-browser error message Django project I have created folder/Directory under application folder name HTMLFile inside this folder index.html is created. Tree structure of project-django -
Django Rest Framework - How to use "UniqueTogetherValidator" if one of the fields is provided as a URL variable
Hello I have a model with a unique_together constraint but the serializer cant validate it because one of the fields is being passed as a variable in the URL: How can I access the url variable int:pk inside the serializer for the "UniqueTogetherValidator" to work properly. My model: class Review(models.Model): user = models.ForeignKey(CustomUser, related_name='recipe_reviews', on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField() comment = models.TextField(blank=True, null=True) class Meta: unique_together = ['user', 'post'] My url looks like this: path('posts/<int:pk>/reviews/create/', ReviewCreateView.as_view()), My view: class ReviewCreateView(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = ReviewCreateSerializer def perform_create(self, serializer): # Grab post using URL Variable (pk) and save the review post = get_object_or_404(Post, id=self.kwargs['pk']) serializer.save(post=post) And my serializer: class ReviewCreateSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Review fields = ['user', 'post', 'rating', 'comment'] validators = [ serializers.UniqueTogetherValidator( queryset=Review.objects.all(), fields=['user', 'post'] ) ] Since I'm not passing the post ID in the body of the request, I get the following error: { "post": [ "This field is required." ] } Is there any way of creating my own field that grabs the information from the URL variable? (similarly how the HiddenField is grabbing the CurrentUser automatically) I would really appreciate the help. Thanks! -
Value Error: Field 'id' expected a number but got 'favicon.ico
I am getting this error every time I execute an action on my application. Although it is not a fatal error I am sure it does effect the working of my program. Below is the traceback of the error. Can somebody that understands this please help. [04/Jan/2021 07:13:14] "GET / HTTP/1.1" 200 6081 [04/Jan/2021 07:13:14] "GET /static/styles.css HTTP/1.1" 304 0 Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'favicon.ico' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\exception.py", line 4 7, in inner response = get_response(request) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\base.py", line 179, i n _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 106, in get self.object = self.get_object() File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 36, in get_object queryset = queryset.filter(pk=pk) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 942, in f ilter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 962, in _ filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 969, in _ filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ … -
AttributeError: 'Person' object has no attribute 'update' Django
Im having a problem with this query. All I want is to change the paid value if the paid is equals to Yes then it must be change into Paid and if paid is equals to No then it is Unpaid. The problem is Im having this kind of error AttributeError: 'Person' object has no attribute 'update' . It is necessary to use p.update? to change the value from Yes toPaid? This is what I've been trying for p in Person.objects.filter(Q(paid = 'Yes')): p.update(paid="Paid") -
Django + HTML: How to query usernames of those who liked your post
I am trying to query and show the list of usernames that liked the post in the detailed blog post view. So I have 2 models, Account and BlogPost, as such in my html i did blog_post.liked.pk to link from the blog post to the account model, and then i tried to link and query the username, but I was unable to query it. Can anyone advise? thank you! def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['liked'] = liked context['blog_post'] = blog_post context['total_likes'] = total_likes context['total_views'] = total_views return render(request, 'HomeFeed/detail_blog.html', context) def LikeView(request, slug): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect(request.META.get('HTTP_REFERER', '')) models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) brief_description = models.TextField(max_length=300, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) html {% for user in blog_post.liked.pk %} {{ user.username }} {% endfor %} -
django template for loop and if statements to separate search results
I want to separate my search results by category. Here is my search_results.html: {% extends "base.html" %} {% load static %} {% load search_extras %} {% block content %} <h2>Search results for <b>'{{ query }}' </b> (appearing {% if count == 1 %} once): {% else %}{{ count }} times):{% endif %} </h2> <p> <i>Only unique results are shown </i></p> <h3>Word results</h3> {% for query in object_list %} {% if query.target_word or query.source_word %} {{ forloop.counter }} {% with query|class_name as class %} {% if class == 'Word' %} {{query}} {% endif %} {% endwith %} {% endif %} {% empty %} <p>No search results match your query.</p> {% endfor %} <h3>Song results</h3> {% for query in object_list %} {% if query.title or query.artist %} {{ forloop.counter }} {% with query|class_name as class %} {% if class == 'Song' %} {{query}} {% endif %} {% endwith %} {% endif %} {% empty %} <p>No search results match your query.</p> {% endfor %} {% endblock %} And this gives the required output if there are results for both categories, e.g.: Search results for 'x' (appearing 4 times): Only unique results are shown Word results 1 word1 2 word2 Song results 3 … -
How to pass a function name as a parameter for dynamic url?
I am trying to pass a function as a parameter to a dynamic URL. This is the code: path('like/<str:view>', like_view, name='like') I then use that view variable to do a reverse with the view function. However, it raises an error that says "sac_view is not a valid function or view name" even though sac_view is a view function. Is there a datatype like function? I'm really not sure. Thanks! -
! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/owlfacturacion.git'
It is my first time that I am trying to upload a django project to heroku but I get the following error. ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/owlfacturacion.git' I add the code that returns. PS D:\Owltec\Proyectos\sistcomfacv2> git push heroku master Enumerating objects: 1880, done. Counting objects: 100% (1880/1880), done. Delta compression using up to 12 threads Compressing objects: 100% (1861/1861), done. Writing objects: 100% (1880/1880), 10.06 MiB | 323.00 KiB/s, done. Total 1880 (delta 96), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.7 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.1 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: Collecting asgiref==3.2.10 remote: Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) remote: Collecting astroid==2.3.3 remote: Downloading astroid-2.3.3-py3-none-any.whl (205 kB) remote: Collecting autopep8==1.4.4 remote: Downloading autopep8-1.4.4.tar.gz (114 kB) remote: Collecting braintree==4.0.0 remote: Downloading braintree-4.0.0-py2.py3-none-any.whl (122 kB) remote: Collecting certifi==2019.3.9 remote: Downloading certifi-2019.3.9-py2.py3-none-any.whl (158 kB) remote: Collecting chardet==3.0.4 remote: Downloading … -
Like button is working but not changing to Unlike in django
I've been trying to debug this issue for a day together with my expert coder but we were unable to identify the issue here. The like button works perfectly all right and I am able to query the total likes, but the Clap button does not change to unlike and we are unsure why. i believe the error lies in either the html line: {% if liked and post.slug == blog_post.slug %} Unlike {% else %} Like {% endif %} or the django line: context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False Big thanks if you can identify the issue here! views.py def home_feed_view(request, *args, **kwargs): context = {} blog_posts = BlogPost.objects.all() context['blog_posts'] = blog_posts if request.method=="POST": slug=request.POST["submit_slug"] blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False context['total_likes'] = blog_post.total_likes() type_of_post = TypeofPostFilter(request.GET, queryset=BlogPost.objects.all()) context['type_of_post'] = type_of_post paginated_type_of_post = Paginator(type_of_post.qs, 13 ) page = request.GET.get('page') post_page_obj = paginated_type_of_post.get_page(page) context['post_page_obj'] = post_page_obj return render(request, "HomeFeed/snippets/home.html", context) def LikeView(request, slug): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect(request.META.get('HTTP_REFERER', '')) <td class="table-primary"> <form action="{% url 'HomeFeed:like_post' … -
django save image in zip
Client upload zip. Picture after decompression. I want to save the picture to the specified location. But my code cannot be saved to the specified location How to do? models.py def get_upload_path(instance, filename): return f'register/{instance.owner.job_number}/{filename}' class UserRegister(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_upload_path) class Meta: db_table = 'UserRegister' views class AddsUser(View): def get(self, request): data = { 'title': 'AddsUser' } return render(request, './User/adds_user.html', data) def post(self, request): zip_file = request.FILES.get('zip') date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') dir_name = uuid.uuid4().hex zip_dir_path = f'./temp_zip/{dir_name}' with open(f'{zip_dir_path}.zip', 'wb') as files: for i in zip_file.chunks(): files.write(i) files.flush() os.mkdir(zip_dir_path) os.system(f'unzip {zip_dir_path}.zip -d {zip_dir_path}') for image_name in os.listdir(zip_dir_path): image_path = f"{zip_dir_path}/{image_name}" user_profile = UserProfile.objects.create(date=date) user_register = UserRegister.objects.create(owner_id=user_profile.id, image=image_path) return redirect(reverse('admin:adds_user')) This method will not store the picture in the location I specified. -
python-social-auth: Unable to keep logged in newly registered user after setting password
I am certain the problem derives from this statement: user.set_password(local_password) because when I omit it the pipeline ends with the user logged in as expected. Now, as others have pointed out, after using the set_password method django automatically finishes the session so to avoid that we may use update_session_auth_hash (request, user). The problem is that this does not work in the pipeline. I've also tried adding instead: user = authenticate(username=user, password=local_password) login(request, user) This also does not work. I also checked via print statements whether the user is authenticated, it happens to be in all 3 steps that I checked. Lastly, I also tried creating a new pipeline method and calling it afterwards. This one also did not work. @partial def login_users(strategy, request, user, *args, **kwargs): user = authenticate(username=user, password=strategy.session_get('local_password', None)) print(user.is_authenticated) request = strategy.request login(request, user) messages.success(request, "Welcome, you have successfully signed up") return In summary, and to avoid overflowing with data here, everything works as expected, but as soon as I save the password via user.set_password(local_password), the user is logged out and needs to click again on Linkedin to sign in. Otherwise, the behavior would be as expected, i.e. the data collected is saved and the home page … -
Search bar for Django MultipleChoiceField form
First of all sorry if my question is very simple, but i am a beginner in Django. I have a MultipleChoiceField form, containing many cities of US. I just want to add a search bar sto i can type some letter of the city and filter my results instead of scrolling.I also have another form in the same logic but with multiselct including categories. This is my form: from django import forms class CityForm(forms.Form): def __init__(self, *args, **kwargs): cities = kwargs.pop("City") super(CityForm, self).__init__(*args, **kwargs) self.fields["City"] = forms.ChoiceField(choices=cities, label='City name ', widget=forms.Select(attrs={'onchange': 'submit();'})) class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): categories = kwargs.pop("Category") super(CategoryForm, self).__init__(*args, **kwargs) self.fields["Category"] = forms.MultipleChoiceField(choices=categories, label='Categories') I don't want to use modelChoice as i am begginger and it seems very complex This is my html template. <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> body { background-color: white; text-align: center; color: black; font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} </form> <p>Now select one or more categories you are interested in</p> <form action="" method="POST"> {% csrf_token %} {{ form2.as_p }} <input type="submit" value="Submit Category"> </form> </body> </html> Is there any simple way to add a seach bar? -
'EncryptedCharField' error while doing django/python upgrade
I am trying to upgrade my old django application (django 1.1, python 2.7) to latest django3.1 and python3. So created new virtual environment to do this and started installing related packages one by one, and then i encountered this issue: AttributeError: 'EncryptedCharField' object has no attribute 'keydir'. I have installed most of the packages including the crypto ones like cryptography, pycryptodome, encrypted_fields, python3_keyczar, but no luck. Any suggestions! -
how to show thumbnail images from a local url stored in session system in Django?
Django 3 + sorl-thumbnail 12.7.0 Hello! I'm using the session system to store various items like this: request.session['cart'][1] request.session['cart'][2] ... request.session['cart'][n] In every session unit i want to store a product.image.url and other fields of the product: request.session.setdefault('cart', {})[str(request.session['counter'])] = { 'producto': p.pk, 'talla': talla, 'cantidad': cantidad, 'producto_abstracto': p.producto_abstracto.pk, 'imagen': p.imagen_1.url, 'nombre': p.producto_abstracto.nombre_producto, 'marca': p.producto_abstracto.marca.marca, 'precio_venta':p.producto_abstracto.precio_venta, 'nombre_color':p.color_principal_id.nombre, 'color': p.color_principal_id.codigo, } (I can't use pickleserializer to store in session the complete object Product for security concerns). Then I want to show in a view the product.image as a thumbnail but here is the problem. It seems that sorl-thumbnail just work with image Objects but i just have the url. Then in template i try this: {% load thumbnail %} {% thumbnail '{{item.imagen}}' '300x300' as im %} <img class="im" style="width:100%;" src='{{ im.url }}'></img> {% endthumbnail %} As a result i have a 404 not found image with a route in cache like this: media/cache/31/a0/31a02cc7b19899a208a972a08e17fe12.jpg to a file that was not created. As a comment when i use thumnail with classic django objects and images stored it works so i think it is not a problem about media and static routes or memcached. What can i do to solve this problem and show … -
TypeError at /index/ expected str, bytes or os.PathLike object, not tuple
I have no idea about my template format. and this is my index method to do a render ''' def index(request): # return HttpResponse('hello') template = loader.get_template('index.html') context = { } return HttpResponse(template.render(context, request)) This is the trace back Environment: Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 3.1.3 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstWEB'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\74007\PycharmProjects\pythonProject1\firstWEB\views.py", line 11, in index template = loader.get_template('index.html') File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\74007\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\ntpath.py", line 78, in join path = os.fspath(path) Exception Type: TypeError at /index/ Exception Value: expected str, bytes or os.PathLike object, not tuple And in the final … -
Django admin GenericForeignKey object_id lookup
I'm looking for great way of selecting object of selected content_type (component_type). Django serves the raw id field where the user can input an integer. Is there a way to make it look more like the django grappelli solution? Like an 3rd part app to install which modifies admin template and adds ONLY this one feature instead of full django admin template? Or there is a good-looking template which has this option (because grappelli looks so bad). Thanks in advance