Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to capture the execution time in django error logs?
class Request(APIView): @api_view(["GET"]) def test_api_method(self): db_logger = logging.getLogger("db") try: 1 / 0 except Exception as e: db_logger.exception( e, extra={ "user": self.user.username, "module_name": __package__, "execution_time": __________, }, ) return Response({"data": True}, status=status.HTTP_200_OK) In the "execution_time" section in the logger part, I want to capture the execution/ response time. How to do that? I have tried time(), process_time() etc. But not working fine -
Why djangoRest framework retrieveAPIView not able to filter with email?
I am trying to use retrieveAPIView to look up details based on 'email'. But its throwing error: Not Found: /apii/list/ [27/May/2021 19:53:28] "GET /apii/list/?email=%22xxx.zzz@gmail.com%22 HTTP/1.1" 404 2801 project level urls.py urlpatterns = [ path('admin/', admin.site.urls), path('apii/', include('AUTHENTICATION.urls')), ] app urls.py urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('login/', loginAPIView.as_view(), name='login'), re_path(r'^list/(?P<email>[\w\-]+)/$', IndividualUserDetails.as_view(), name='list'), ] views.py class IndividualUserDetails(RetrieveAPIView): queryset = NewEmployeeProfile.objects.all() permission_classes = [AllowAny] serializer_class = UserSerializer lookup_field = 'email' The url I am entering in postman is http://127.0.0.1:8000/apii/list/?email="xxx.zzz@gmail.com" I am assuming I am calling the url in a wrong way may be. Please suggest. Thank you -
Tagulous - Getting AutoComplete Fields to work
I have installed Tagulous successfully in to my Django app, and I have created a Tag textfield although, I'm struggling to get the AutoComplete process to work. I have been referencing the Tagulous instructions. I have installed AutoComplete and have included the relevant JS and CSS libraries within my Settings.py. Along with ensuring that "dal" and "dal_select2" is installed under INSTALLED_APPS. When I go to my form, I'm not receiving any errors and the Skills tag field appears. Although, there is no sign of any autocompletion working, the field just currently behaves as a regular tag field without the autocomplete feature. Here's my code so far: Views.py - (I have imported from dal import autocomplete in to this file) class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image', 'skills'] widgets = { 'skills': autocomplete.ModelSelect2(url='skills-autocomplete') } template_name = 'sfsrv/post_new.html' success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Create new post' return data class SkillsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Skills.objects.none() qs = Skills.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs URLs.py (I have imported from sfsrv.views … -
sen_email error define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure()
django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER='myemail' EMAIL_HOST_PASSWORD='mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'myemail' BASE_URL = '127.0.0.1:8000 -
Django: make favorites accessible from home-view. Try to filter for liked posts by user on the frontpage
I know that there are some questions, that are close to what I am asking but still I am struggeling with finding the correct way: In a grid-like-view I am trying to display a heart-icon (filled/not filled) representing if the logged in user has favorited that post or not. My code: views.py def home_view(request): # all posts posts = Post.objects.filter(date_posted__lte=timezone.now(), is_active=True).order_by('-date_posted') is_favorite = False #liked_posts = Post.objects.get(id=request.user.id).liked.all() liked_posts = User.objects.prefetch_related('liked').get(id=request.user.id).liked.all() # https://stackoverflow.com/questions/63547411/django-filter-liked-posts-by-user if liked_posts.exists() : is_favorite = True context = { 'posts':posts, ... 'liked':liked_posts, 'is_favorite':is_favorite, } return render(request, 'blog/home.html', context) @login_required def PostLikeToggle(request): posts = Post.objects.all() user = request.user if request.method == 'POST': post_id = request.POST['post_id'] post = get_object_or_404(posts, id=post_id) user_liked = user in post.liked.all() if user_liked : post.liked.remove(request.user) else: post.liked.add(request.user) return JsonResponse({'liked':user_liked}) models.py class Post(models.Model): liked = models.ManyToManyField(User, related_name='liked') title = models.CharField(max_length=150) date_posted = models.DateTimeField(null=True, blank=True, editable=True, default=timezone.now, verbose_name="Published at") #... class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def __str__(self): return self.title urls.py urlpatterns = [ path('', home_view, name="home"), #... path('like/', PostLikeToggle, name="like"), ] home.html <button data-item-id="{{ post.id }}" class="addToFavsContainer-{{ post.id }}" value="{{ post.id }}"> <i class="thumb-{{ post.id }} fas fa-thumbs-up"></i> </button> <script> $(".addToFavsContainer-{{ post.id }}").click(function () { var item_id = $(this).data('item-id'); $.ajax({ type: "POST", … -
Python not decoding JSON because "encoding" is an unexpected argument
I have a Django 2.2.23 app, running on Python 3.9.4. I have django-extensions 2.2.9. I have a model that has a django_extensions.db.fields.json.JSONField attribute (which, AFAIK, is just a text field auto-serialized). I mention this because when the JSON is deserialized, the django-extensions library does it like this: def loads(txt): value = json.loads( txt, encoding=settings.DEFAULT_CHARSET ) return value The problem is that the library imported by import json gives me an error when it's called this way: Python 3.9.4 (default, Apr 5 2021, 01:50:46) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import json >>> json.loads("{}", encoding="UTF-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 359, in loads return cls(**kw).decode(s) TypeError: __init__() got an unexpected keyword argument 'encoding' >>> The end result is that I am unable to load any of the records that contain a JSONField from the database because the JSONDecoder can't handle being passed an encoding argument. I was under the impression that Python's json library was simplejson. But looking at the source for that, it does handle encoding. But if I look at the json library in "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/init.py" (as specified in the error above), … -
Setting blank = False for email field in django authentication
I am using django built-in authentication and for that authetication system, we are given different fields like username, email, password etc. Username by default is required and also not blank but for email it is not required (i.e, it is null) which makes it blank also. Now for making it required, i added this code; extra_kwags = {'email': {'required': True}} I tried the same with blank; extra_kwags = {'email': {'required': True, 'blank': False}} But it gives error saying blank is not a valid keyword there. So i want to know if there is a way to set blank=False for the email field in django. Though i know a way which is by making the email_verification mandatory and making email the way to autheticate; ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' But i want to know if there is another way as i don't want it to make authentication_method. -
How to bring the values of while loop in the Response in Django Rest Framework?
I am trying to calculate the counts of each day sales/orders made in the last 30 (7 days for now). My view look like this. class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() startdate_1 = datetime.today() - timedelta(days=1) enddate_1 = startdate_1 + timedelta(days=1) startdate_2 = datetime.today() - timedelta(days=2) enddate_2 = startdate_2 + timedelta(days=1) startdate_3 = datetime.today() - timedelta(days=3) enddate_3 = startdate_3 + timedelta(days=1) ...............................#upto 30 days count_8 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_1, enddate_1]).count() count_9 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_2, enddate_2]).count() count_10 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate_3, enddate_3]).count() ..................#upto 30 days return Response( {'active_users_now': count_2, 'total_orders_one_day_ago': count_8, 'total_orders_two_days_ago': count_9, 'total_orders_three_days_ago': count_10, #"total_orders_i_days_ago":count_i, }, status=status.HTTP_200_OK) What I want is to use loop instead of writing such long codes for 30 days. Here is what I have tried: This is just a logic not actual code for python i = 1 while (i<=7): startdate[i] = datetime.today() - timedelta(days=i) enddate[i] = startdate[i] + timedelta(days=1) count[i] = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'], ordered_date__range=[startdate[i], enddate[i]]).count() i+= i return Response( {i:count[i],}, status=status.HTTP_200_OK ) -
Make image file stored outside django root accessible to Django admin
I need to upload images through django admin to a remote directory. I am able upload the images without issues, the problem is that although the file location is correct, the link in admin to the image does not work (displayed as 1/screenTest.png). I only want this image to be accessible from admin, how do I do this? models.py from django.db import models from .storages import upload_to, media_storage class Newsletter(models.Model): image_1 = models.ImageField(upload_to=upload_to, storage=media_storage, null=False, blank=False) storages.py from django.core.files.storage import FileSystemStorage ef upload_to(instance, filename): return '%s/%s' % (instance.pk, filename) media_storage = FileSystemStorage( location='Users/somedirectory/Documents/dev/mediatest/', base_url='Users/somedirectory/Documents/dev/mediatest/' ) Page not found (404) Request Method: GET Request URL: http://localhost:8000/Users/somedirectory/Documents/dev/mediatest/1/an-image.png Using the URLconf defined in backoffice.urls, Django tried these URL patterns, in this order: etc. `` -
Fetch data from django backend having parts of dynamic URL private
Let's say I am developing a django REST api that is secured via token and basic authentication. The idea is to list juices. So I am having an URL that lists all juices from specific brands. So I got a dynamic URL like: path("juices/<str:brand>/" ...) What I want to do now is to show all juices of the brand coca-cola in my frontend where no authentication is required. So all visitors should see the list of juices from coca-cola. I need to use JS fetch since it has to be asynch. Thus my code is something like: async function get_juices() { let juices = await fetch( `${hostname}/api/v1/juices/coca-cola/ ) result = await juices.json(); return juices; } My backend is a simple ListView that dynamically filters by brand. But my problem now is that the API is private and I can't use my credentials in my frontend for obvious security reasons. Because any user could just read the frontend code and use my credentials to access the juices of other brands too. I was reading now in some posts that it is possible to have a proxy server which only accepts requests from a specific client and reroutes the request with credentials … -
How to make sure that when I click the button in django form it redirects me to another page
I am making a forms page and I would like when I click the "Submit" button it renders the person on another page that I will create. Prenotazioni.html {% extends 'base.html' %} {% block content %} <br><br><br><div class="container" style="max-width: 600px;"> <form method='POST'> {% csrf_token %} {{ form.as_p }} <input type='submit' class="btn btn-warning" value='Submit' /> </form> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% endblock %} forms.py from django import forms from .models import Prenotazioni class PrenotazioniForm(forms.ModelForm ): class Meta: model = Prenotazioni fields = [ 'Nome', 'Codice_di_Sicurezza', 'Telegram', 'Livello_di_conoscenza_della_economia_da_1_a_10', ] ] The more I search online, the more confused I get. Many thanks in advance! -
How to insert my django model to postgres?
Whenever i change my model and after running makemigrations , there should be changes in the database. I faced this problem while i was trying to add an user foreign key to my table. no changes were made to the table. So, I delete my entire table and initial migrations . and again, i run makemigrations and migrate to transfer my model to postgresql Ever since , i deleted my model from postgres, I cannot view my table in database. My migrations Migrations for 'affiliation': affiliation\migrations\0001_initial.py - Create model ProductView - Create model ProductDetails - Create model ProductImages - Create model AffProduct After this i checked on postgresql server , but no table was created? -
Django SearchVector doesn't work with search query containing whitespace
I have a name field on which I am trying to annotate with a SearchVector. It works fine if I don't add a whitespace in search string but returns empty list if I add a whitespace. Same string works just fine with regular filter queryset. >>> r = Resource.objects.filter(name__icontains='LAKSHMI NURSING') >>> r <QuerySet [<Resource: LAKSHMI NURSING HOME>]> >>> Using Search vector without a white-space string >>> r = Resource.objects.annotate( ... search=SearchVector('name', 'type') ... ).filter(search__icontains='LAKSHMI') >>> r <QuerySet [<Resource: LAKSHMI NURSING HOME>]> >>> With White-space: >>> r = Resource.objects.annotate( ... search=SearchVector('name', 'type') ... ).filter(search__icontains='LAKSHMI NURSING') >>> r <QuerySet []> >>> -
SyntaxError with ImageField in Python Shell
I am learning forms on django documentation. I got stuck at ImageField. While doing the example it is reflecting Syntax Error The code is exactly as mentioned by Django in documentation Please advise what is wrong in it from PIL import Image from django import forms from django.core.files.uploadedfile import SimpleUploadedFile class ImageForm(forms.Form): img = forms.ImageField() file_data = {'img': SimpleUploadedFile('test.png', <file data>)} form = ImageForm({}, file_data) Please see the syntax error as represents in the python shell file_data = {'img': SimpleUploadedFile('test.png', <file data>)} File "<console>", line 1 file_data = {'img': SimpleUploadedFile('test.png', <file data>)} ^ SyntaxError: invalid syntax Thank You -
Data validation in Serializer return empty OrderedDict
I am trying to add multiple ManytoMany relationship in a model but when I am trying to add the data it shows OrderedDict() in the validated data in serializer Models.py class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) client_shipping_address = models.CharField(max_length=500, default=0,blank=True, null=True) class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) receiver_clients = models.ManyToManyField(ReceiverClient) warehouses = models.ManyToManyField(Warehouse) Views.py class GroupsCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): d = request.data.copy() print(d) serializer = GroupsSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print('error') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serilalizer.py class GroupSenderClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" read_only_fields = ('user',) class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = GroupSenderClientSerializer(many=True) receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("sc objects", sc_objects) if len(sc_objects)>0: for i in sc_objects: print("id", i['id']) inst = Client.objects.get(pk=i['id']) sc.append(inst) if len(rc_objects)>0: … -
How to make a dynamic django model field that can change its type to charfield, datetimefield, manytomanyfiel...etc?
I am trying to create a change tracker, so when I change any model I register the data of the change for statistical perpese. However, I have this field called field_value I set it to char field and I faced a problem later. Because it is a plane text it is hard to tell what are the data represent. For example, when I have the field_value equal to a manytomanyfield with users ids I got a plan text that look like this "<Ojbect User(1) User(2)>" or like this "[1,2]" which is not pleasant to work with or to make statistics one them. class ChangeTrack(SafeDeleteModel): changed_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='user', on_delete=models.DO_NOTHING, null=True,) date_created = models.DateTimeField(auto_now_add=True, null=True) model_target = models.CharField(max_length=50, blank=True) field_target = models.CharField(max_length=50, blank=True) field_value = models.CharField(max_length=50, blank=True) @receiver(signals.post_save) def __init__(instance, sender, signal, *args, **kwargs): new_change = ChangeTrack.create(...) #.... my code # the problem is here I stringfy all sorft of data evnen if they are manytomany field # so how can I make a dynamic fidl that can be char field if I need , or manytomahy fiedl when I need an dsoo one? new_change.field_value.set(str('any value')) -
Mocking query_params using responses and pytest
I would like some help to mock a query_param using responses and pytest. I have this view: @api_view(["GET"]) @csrf_exempt @permission_classes((AllowAny,)) def get_code_and_extra(request): code = request.GET.get("code", "") extra = request.GET.get("extra", "") if code and extra: # do something return HttpResponse("", status=200) return HttpResponse("", status=400) And my test mocked: @responses.activate def test_receive(self, db, client): responses.add( responses.GET, "https://test.com/?code=some-code&extra=extra", json={}, status=200, content_type="application/json", ) resp = client.get(reverse("my-url")) assert resp.status_code == 200 When I run my test works, but the view does not receive the query_params. I would like to pass it so that the test works as expected. A little more context: this view serves as a webhook that receives these parameters from another site. The view is working, but I wanted to have this test. -
Python dynamic attributes and subclasses
I am using Django 3.2 and Python 3.8 I want to move common methods to a base class. class Base: def common1(self): rname = self.get_relation_name() return rname.filter(some_criteria) @abstractmethod def get_relation_name(self): pass @abstractmethod def get_relation_count_name(self): pass class Child1(models.Model, Base): foos = GenericRelation(Foo) foos_count = models.PositiveIntegerField(blank=False, null=False, default=0, db_index=True) def get_relation_name(self): return self.foos def get_relation_count_name(self): return self.foos_count class Meta: abstract = True class Child2(models.Model, Base): foobars = GenericRelation(FooBar) foobars_count = models.PositiveIntegerField(blank=False, null=False, default=0, db_index=True) def get_relation_name(self): return self.foobars def get_relation_count_name(self): return self.foobars_count class Meta: abstract = True When I run python manage.py check I get no errors - but I am not sure if there are any gotchas that will come to bite me later on in the project. My question is - is it safe to dynamically create attributes like this - and/or is there something I need to be aware of? -
DJango doesn't execute request.method == "post" with ajax data submission
It's time first time working with JQuery and Ajax, I've been stuck on this problem for past few hours, searched through various similar solutions but nothing worked for me Problem: Whenever I click on "submit" button Ajax delivers data to DJango view but that if "post" request part refuses to execute but else part executes no matter how many times i change the code HTML <form id="login-form" class="LoginForm" action="" method="post"> {% csrf_token %} <h3 class="text-center text-info">Login</h3> <div class="error"> </div> <div class="box"> <div class="form-group"> <label for="username" class="text-info">Username:</label><br> <input type="text" name="username" id="username" class="form-control"> </div> <div class="form-group"> <label for="password" class="text-info">Password:</label><br> <input type="text" name="password" id="password" class="form-control"> </div> <div class="form-group"> <label for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></label><br> <input type="submit" name="LoginButton" id="LoginButton" class="btn btn-info btn-md" value="submit"> </div> </div> <div id="register-link" class="text-right"> <a href="#" class="text-info">Register here</a> </div> </form> script <script> $(document).ready(function () { $('#LoginButton').click(function () { var username = $('#username').val(); var password = $('#password').val(); if ($.trim(username).length > 0 && $.trim(password).length > 0) { alert("Username and password were trimmed"); console.log("Username = " + username + "\n Password = " + password); $.ajax({ url: '{% url "loginCheck" %}', method: "post", data: { username: username, password: password, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, cache: false, beforeSend: function () { $('#LoginButton').val('Checking...'); … -
Django FloatField not properly display: 54 instead of 5.4 (data store in Postgresql)
I've been looking for error for hours but could not find where is the problem I have a 2 models (Sociodemographique and Clinique) each with a FloatField (dem_hglvaql and cli_tem respectively) I have apply data-mask on each field that correctly works for data entry model.py dem_hgl_val = models.FloatField("Si non, hémoglobine glyquée (%)", null=True, blank=True) cli_tem = models.FloatField('Température', null=True, blank=True) forms.py self.fields['dem_hgl_val'] = forms.FloatField(label = 'Hémoglobine glyquée (%)',widget=forms.TextInput(attrs={'placeholder': '_ _._ _','data-mask':"00.00"}),required=False) self.fields['cli_tem'] = forms.FloatField(label = 'Température',widget=forms.TextInput(attrs={'placeholder': '_ _ . _','data-mask':"00.0"}),required=False) But when I display the Sociodemographique form, dem_hgl_val is not correctly displayed: 54 instead of 5.4 cli_tem field is correctly displayed dem_hgl_val have validation form control and JS conditional behavior but even if I remove all these controls it doesn't seems to change anything forms.py def clean_dem_hgl_val(self): data = self.cleaned_data['dem_hgl_val'] if data: if data > 100: raise forms.ValidationError("Vous ne pouvez pas saisir un pourcentage supérieur à 100%") if data < 0: raise forms.ValidationError("Vous ne pouvez pas saisir un pourcentage négatif") return data JS script // masque la section 3 'Co-morbidités' si la case 'section non applicable' est cochée $("#id_dem_com_nap").on('change', function() { if ($(this).is(':checked')) { $("#id_dem_hgl_val").val(null); }); // affichage conditionné section 'Diabete' $("#id_dem_dia").on('change', function() { if ($(this).val() == 1) { $("#id_dem_hgl_val").val(null); } … -
Getting Error in Django: DoesNotExist at /add-to-cart-2247/
I'm using Django as a backend and PostgresSQL as a DB and HTML CSS & Javascript as a frontend. While I'm adding the product to the cart it show this error. This is the Error where I get in screen while adding to the cart: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 159, in get context = self.get_context_data(**kwargs) File "D:\Visual studio Projects\Django Project\mainproject\buildpc\views.py", line 35, in get_context_data cart_obj = Cart.objects.get(id = cart_id) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /add-to-cart-2247/ Exception Value: Cart matching query does not exist. Traceback Here is my Code: view.py class AddToCartView(TemplateView): template_name = "status.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) processor_id = self.kwargs['pro_id'] processor_obj = Processor.objects.get(id = processor_id) cart_id = self.request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id = cart_id) this_product_in_cart = cart_obj.cartproduct_set.filter(processor = processor_obj) if this_product_in_cart.exists(): cartproduct = this_product_in_cart.last() cartproduct.quantity += 1 cartproduct.subtotal += processor_obj.price cartproduct.save() cart_obj.total += processor_obj.price … -
Saleor storefront invalid credential when resetting password
Saleor is giving me an error when resetting my password in the store it says invalid credential when I’m resetting and invalid token after does anybody encounter this? Thanks -
Delete password, Last login, Superuser status, Groups, User permissions...filed in User tab in Django admin
I have used Django2 and simpleUI to develop a Django web app. Now I want to delete password, Last login, Superuser status, Groups, User permissions...filed in User tab in Django admin. How could I do that? I tried to unregister my user and rewrite it, but failed to delete anything. admin.py: from django.contrib import admin from django.contrib.auth import forms from .models import * from django.contrib.auth.models import Permission admin.site.register(User) -
How do I get the POST result from a url endpoint? Django/Python
I have a system that sends a pin entry request to a client for payment processing. If client accepts payment and enters PIN, I get below results on my endpoint I have tried to run the code below response = requests.get('https://end9m3so3m5u9.x.pipedream.net/') print(response.text) print(response.status_code) How do I access the ResultCode for further processing in my views.py? Please advice. -
How do I use update_or_create In django?
I have problem on using update_or_create method in django I have following model class Search(BaseModel): booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) flight_date = models.DateField() return_date = models.DateField(null=True, blank=True) And I tried creating if not exists or update existing value but I am getting integrity error duplicate key value violates unique constraint "flight_search_booking_id_key" DETAIL: Key (booking_id)=(4) already exists. Here is how I tried saving. def _save_to_db(self): # 14. check if booking id exists previously if exists raise error defaults = {'booking_id': 4} flight_data, _created = Search.objects.update_or_create( booking_id=self._flight_data.get('booking_id'), trip_type=self._query_params.get('flight_type'), flight_date=self._query_params.get('departure_date'), defaults=defaults ) flight_data.save() I learned default should be provided so I did that too but I am getting error.