Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with JSON data can't get it rendered on template
I have the models.py with employee and all the info. With one click i want to render all the info of my employee. the thing is, I have 2 columns one for names and one for information. when i click a name the right column has to come up with the array with name last name..... i can see it on the console but i can't get it rendered. Think i have problems with the key but i dont know. here is the code.. views.py in this function i want to get the id of the name by jsonloads by clicking the name and filter the employe with it.(this works) def check(request): if request: if request.method == 'POST': data = json.loads(request.body) employeId = data['id_s'] empinfo = Employe.objects.filter(id=employeId) print(empinfo) print(data) return JsonResponse({'data': list(empinfo.values())}, safe=False, status=200) return HttpResponse() js code is here. in these code i want to get the data by fetch url. i can see it on the console log that the data is recieved(these function works good aswel) function checkEmp(id_s, action){ var url = '/checks/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'id_s': id_s, 'action': action}) }) .then((response)=>{ return response.json() }) .then((data)=>{ console.log(data); }) } index.html i … -
how do i remember the radio button selection in django
i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects. N.B: the value of the radio button is saved in sessions <div class="col-md-1 ps-md-1"> <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> </div> my ajax $('input[type=radio][name=deliveryOption]').on('change', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); </script> my view def cart_update_delivery(request): cart = Cart(request) if request.POST.get("action") == "post": delivery_option = int(request.POST.get("deliveryoption")) delivery_type = DeliveryOptions.objects.get(id=delivery_option) updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price) session = request.session if "purchase" not in request.session: session["purchase"] = { "delivery_id": delivery_type.id, } else: session["purchase"]["delivery_id"] = delivery_type.id session.modified = True response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price}) return response -
Django annotate count of disctinct values of the running quesyset in its children
I was tracing this bug for a while until I found the source I believe it's coming from, and I have been stuck here now. I have the following models below: class ShopItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) store = models.ForeignKey(to=Store, on_delete=models.CASCADE) name = models.CharField(max_length=250) class SelectedProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True) product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders") status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART) number = models.CharField(max_length=36, blank=True, null=True) Lets say for example an order has 5 products, 3 of these products are of the same type (p1, p2, p3) as they reference same shop item; where are the other two products (p4, p5) are different since they reference different shop items. I am trying to annotate how many same products exist on this order as in the following products = order.products.all().annotate(quantity=Count("product")) Attempting to get a queryset of these products with quantity annotated, only thing, I get quantity of 1 for all products, where I am trying to get: p1.quanity > 3 p2.quanity > 3 p3.quanity > 3 p4.quanity > 1 p5.quanity > 1 is there anyway I could … -
How to delete localstorage item from AJAX DOM?
I have localstorage itemcheck on following format: {"images":["png1"],"itemIds":["1","3","4"]}' On Ajax success, DOM is passed on following way: success: function (data) { console.log(data) $.each(data, function (key, value) { if ($.trim(key) == "products") { for (var i = 0; i < data[key].length; i++) { var wishlistUrl = "{% url ecommerce:add_to_wishlist %}"; var featured_image = data[key][i]['featured-images'][0]['image'] var div = '<a href="#" class="btn remove-product"><i class="w-icon-times-solid" id="remove_compare" attr="' + data[key][i].id + '"></i></a>'; $("#items").append(div); On #remove_compare button click, I want to remove item from localstorage having itemIds equal to attr value inside ajax DOM. How can I do this? -
registering user in django des not work and it does not gievs me any error
I was working on a simple register veiw that sends activation code too in django . And the problem is that it does not gives me any error and It does not register any user and I dont know why? Here is my code : veiws.py : def register_page(request): if request.method == 'POST' : form = forms.UserRegister(request.POST) if form.is_valid(): data = form.cleaned_data if data['password_1'] != data['password_2'] and '@' in data['email'] and data['username'] != data['email'] and not User.objects.filter(username = data['username']).exists(): user = User.objects.create_user(username=data["username"] , email = data['email'] , password = data['password1'] , is_active = False) user.save() v = randint(1000 , 5000) subject = 'sample subject' message = f'your code : {v}' email_from = settings.EMAIL_HOST_USER recipient_list = [data['email'] , ] send_mail( subject, message, email_from, recipient_list ) active_code.objects.create(code = v , email = data['email']).save() return redirect('home:activeveiw') else: if data['username'] == data['email']: messages.error(request ,'error 506') if User.objects.filter(username = data['username']).exists(): messages.error(request ,'error 789') if data['password_1'] != data['password_2'] : messages.error(request , 'error 899') else : form = forms.UserRegister() con = {"form" : form } return render (request , 'home/register.html' , con) template : <form action="" method="post"> {% csrf_token %} <input type="text" name="username"> <input type="text" name="email"> <input type="text" name="password_1"> <input type="text" name="password_2"> <button type="submit">send</button> </form> {% if … -
How to show the saved data of 3 forms in my template in Django?
let's say I have a form_1, a form_2 and a form_3, all three forms store information and they are in different html pages. I would like to have a view that presents the information saved in forms 1, 2 and 3 in the same template. How can I do that? -
Can I integrate a django project to an android app?
I am a beginner (about 1 year since i started learning python on web) I was working on a project (for online video conferencing) you can check the developement here (JUST CLICK THE MAKE A MEETING BUTTON) https://pranaam.web.app but now i am in a doubt that i know basic JS (not node) HTML/CSS and python and if i am working on my project then i want to launch it on android platform like in ZOOM meetings we can both join from browser and the exe/apk is there a way to integrate my online functioning website to a mobile app (using python as i dont know any other languages) and also Organise all the buttons and functions in mannered way (not a messed up web view) -
How to abort model instance deletion from django model admin interface based on some condition
I want to abort model deletion from django admin based on some condition. I tried overriding delete_queryset(self, request, queryset) method. def delete_queryset(self, request, queryset): if (<my condition>): message = "Error message" raise ValidationError(message) super().delete_queryset(request, queryset) This doesn't work since django does not handles exception at this stage. -
How can access input value in django view through AJAX without form submission
I am beginner in django.I am working on a single text box in a django form which have number of fields.I wrote AJAX code for passing each value(entered from keyboard). How can i access this value in django class based view code. I want to save this value into a variable. Here i am trying to check given text is already existing or not. checking is done for each keyboardinput. $(document).ready(function () { $('#s_id > input').on('input',function(e){ console.log(e); s_text = e.target.value; $.ajax({ type: 'POST', url: "{% url 'create-studentpage' %}", data: s_text, success: function (response) { console.log("response", response); }, error: function (response) { console.log("error", response.responseJSON.error); } }) }); -
django - model foreign key as logged user
I've got model code as follows: from django.db import models from django.core.validators import MinLengthValidator from django.urls import reverse from django.conf import settings class Doc(models.Model): ... added_by = models.CharField(blank=False,null=True,max_length=100,validators=[MinLengthValidator(10)]) added_by_2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... I can migrate this without any problems, but every when I run server and in admin site try to view all records I get: Exception Type: OperationalError Exception Value: no such column: added_by_2_id What is the cause of this error? How to resolve it? -
Foreign key of foreign key in django-polymorphic
I have the following (simplified) django and django-polymorphic models: class GenericOffer(PolymorphicModel): pass class OfferA(GenericOffer): special = models.IntegerField() class OfferB(GenericOffer): pass class GenericProduct(PolymorphicModel): offer = models.ForeignKey(to=GenericOffer) class ProductA(GenericProduct): pass class ProductB(GenericProduct): pass class Gizmo(models.Model): product = models.ForeignKey(to=GenericProduct) from which I can create the following instances: offer_a = OfferA() product_a = ProductA(offer=offer_a) gizmo_a = Gizmo(product=product_a) Now, I have: assert product_a.offer == offer_a assert gizmo_a.product == product_a But: assert gizmo_a.product_a.offer != offer_a assert gizmo_a.product_a.offer.get_real_instance() == offer_a That is, the foreign key linked to a foreign key of my Gizmo is not automatically cast to its proper type. Is it the expected behavior? Should I use a GenericRelation instead of a ForeignKey in my Gizmo ? Thanks for any advice -
Django view testing (sessions , ajax )
In django e-commerce project, i have view which adds a product in basket via sessions, also this view getting POST request from ajax. I can't find how to test this code. basket/views.py def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty': basketqty}) return response basket/basket.py class Basket(): """ A base Basket class, providing some default behaviors that can be inherited or overrided, as necessary. """ def __init__(self,request): self.session = request.session basket = self.session.get(settings.BASKET_SESSION_ID) if settings.BASKET_SESSION_ID not in request.session: basket = self.session[settings.BASKET_SESSION_ID] = {} self.basket = basket def add(self,product,qty): """Adding and updating the users basket session data """ product_id = str(product.id) if product_id in self.basket: self.basket[product_id]['qty'] = qty else: self.basket[product_id] = {'price': str(product.regular_price),'qty':int(qty)} self.save() how to catch this piece of code in testing? <button type="button" id="add-button" value="{{product.id}}" class="btn btn-success fw500">Add to basket</button> <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { document.getElementById('basket-qty').innerHTML = json.qty }, error: function (xhr, errmsg, err) {} }); }) </script> -
Correct way to define list parameter in django-rest-framework and swagger
Background I have the following view and the accompanying swagger UI is generated by django-spectacular: class AllowedNameType(Enum): BRAND = "BRAND" .... @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class GenerateCompanyNamesViewSet(viewsets.ViewSet): http_method_names = ["get"] def list(self, request: Request, *args, **kwargs) -> Response: """Generate suggested company names""" # query_params: dict = {} allowed_name_types: list[AllowedNameType] = query_params.get("allowed_name_types") suggestions: list[Suggestion] = ... return Response(serializers.SuggestionSerializer(suggestions).data) I want to achieve the following: The swagger UI should have a parameter allowed_name_types which is a list of AllowedNameType values The input should be validated as per the serializer definition Type checking should be enforced on query_params to make sure the allowed_name_types is of type list[AllowedNameType] (ideally, allowed_name_types would actually be a named parameter in (eg list(..., allowed_name_types: list[AllowedNameType]) Attempted Solution class AllowedNameTypesParamSerializer(rest_framework_serializers.Serializer): allowed_name_types = rest_framework_serializers.ListField( child=rest_framework_serializers.ChoiceField(choices=models.AllowedNameType.list()), required=False, allow_empty=True, ) and added the following decorator to the list method: @extend_schema( parameters=[ OpenApiParameter(name="allowed_name_types", required=True, type=AllowedNameTypesParamSerializer), ], responses=serializers.FoodSearchAutoCompleteSerializer, ) def list(....) This leads to the following interface: Unfortunately: The swagger component expects a dictionary of {"allowed_name_types:...} instead of a list the allowed_name_types validation of list elements does not work (i.e I can put a value in the list that is not from AllowedNameType) Strangely, calling request.query_params.get('allowed_name_types') only returns the last … -
Postgresql docker: SCRAM authentication requires libpq version 10 or above
Trying to use PostgreSQL 14 with Django using docker-compose version: '3.7' services: web: build: context: . dockerfile: Dockerfile container_name: dev__app image: backend-dev command: ["/scripts/docker/wait_for_it.sh", "database:5432", "--", "/scripts/docker/docker_start.sh"] volumes: # Make /src directory editable which updates django app when code is changed - ./src:/app depends_on: - database env_file: - .env environment: - DATABASE={'ENGINE':'django.db.backends.postgresql','NAME':'app_dev','USER':'app_dev','PASSWORD':'app_dev','HOST':'database','PORT':'5432'} - CELERY_BROKER_URL=amqp://rabbitmq ports: - "8000:8000" restart: on-failure # database service database: image: postgres:14 container_name: app_db environment: POSTGRES_PASSWORD: app_dev POSTGRES_USER: app_dev POSTGRES_DB: app_dev POSTGRES_HOST_AUTH_METHOD: md5 POSTGRES_INITDB_ARGS: "--auth-host=md5" volumes: - app_database:/var/lib/postgresql/data ports: - "5432:5432" But every time I run it using docker-compose up --build It gives the following error django.db.utils.OperationalError: SCRAM authentication requires libpq version 10 or above -
How to use SearchHeadline with SearchVector on multiple fields
I need a search that searches multiple fields and returns a "headline" which highlights the matching words. My understanding is that SearchVector is the appropriate choice for searching across multiple fields. But all of the examples I've seen of SearchHeadline use only a single field! What's the best way to use SearchHeadline with multiple fields? For example, this works: return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .filter(search_vectors=SearchQuery(search_string)) ) Easy. So the next step is to add SearchHeadline... Here was my guess, but it causes an error in PostgreSQL: return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .annotate(headline=SearchHeadline( SearchVector('name', 'location'), SearchQuery(search_string), start_sel='<strong>', stop_sel='</strong>')) .filter(search_vectors=SearchQuery(search_string)) ) Error: Traceback (most recent call last): File "/vagrant/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function ts_headline(tsvector, tsquery, unknown) does not exist LINE 1: ...app_author"."location", '')) AS "search_vectors", ts_headlin... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Is SearchVector() not a valid expression? Using Concat() gets the job done, but this doesn't allow me to leverage the built in indexing capabilities of a ts_vector. It feels like a hack solution to me. return ( Author.objects .annotate(search_vectors=SearchVector('name', 'location'), ) .annotate(headline=SearchHeadline( Concat(F('name'), Value(' '), F('location')), SearchQuery(search_string), start_sel='<strong>', stop_sel='</strong>')) .filter(search_vectors=SearchQuery(search_string)) … -
Is using any with a QuerySet unoptimal?
Many times, one needs to check if there is at least one element inside a QuerySet. Mostly, I use exists: if queryset.exists(): ... However, I've seen colleagues using python's any function: if any(queryset): ... Is using python's any function unoptimal? My intuition tells me that this is a similar dilemma to one between using count and len: any will iterate through the QuerySet and, therefore, will need to evaluate it. In a case where we will use the QuerySet items, this doesn't create any slowdowns. However, if we need just to check if any pieces of data that satisfy a query exist, this might load data that we do not need. -
In Django, how do you enforce a relationship across tables without using constraint?
I'm creating a simple list app that has Groups and Items, each with an associated User. How can I enforce, in the model, that an item created by one user can never be linked to a group created by another user? Here's the model: class Group(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Item(models.Model): name = models.CharField(max_length=200) group = models.ForeignKey(Group, on_delete=models.PROTECT) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've figured out this is impossible to do with a CheckConstraint in class Meta because constraints are apparently made in the database itself (I'm using postgres) and cross-table constraints are not allowed. Coding without a framework, you would simply query the group before saving a link and throw an exception if the users didn't match. So how do you do that in django? -
Django forms - how to dynamically alter field labels
How do I dynamically alter field labels in forms in Django In the below code, the labels word in the def clean_passport function is 'greyed out', saying 'labels' not accessed class LegalDocumentUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Legal_Document fields = ('document_type', 'name_on_document', 'number_on_document', 'issuing_country', 'issuance_date', 'expiry_date', 'document_location') labels = { 'document_type': _("Document Type*"), 'name_on_document': _("Name on Document*"), 'number_on_document': _("Document Number"), 'issuing_country': _("Issuing Country"), 'issuance_date': _("Issuance Date"), 'expiry_date': _("Expiry Date"), 'document_location': _("Document Location*") } # SANITIZATION & VALIDATION CHECKS def clean_passport(self): document_type = self.cleaned_data['document_type'] number_on_document = self.cleaned_data['number_on_document'] issuing_country = self.cleaned_data['issuing_country'] expiry_date = self.cleaned_data['expiry_date'] if document_type == 'Passport': labels = { 'name_on_document': _("Passport Full Name*"), 'number_on_document': _("Passport Number*"), 'issuing_country': _("Issuing Country*"), 'expiry_date': _("Passport Expiry Date*"), } if number_on_document == None: raise forms.ValidationError(_("Please enter the Passport Number.")) if issuing_country == None: raise forms.ValidationError(_("Please enter the Passport's Issuing Country.")) if expiry_date == None: raise forms.ValidationError(_("Please enter the Passport's Expiry Date.")) -
What is the syntax to pass a query in the ajax url using Django
I'm opening a modal with ajax, but I'm having a problem because I need to access a url on my site that needs a query <script> document.getElementById('myBtn2').onclick = function(){ $.ajax({ url:"{% url 'add_data' %}?filter=crew", type:'GET', success: function(data){ $('#modal-content2').html(data); } }); } </script> I can't access url with the query, just the url alone. for example: url:"{% url 'index' %}" But if I put a query in the url it still doesn't work. I think the syntax is wrong and I can't figure out what it looks like. url:"{% url 'add_dados' %}?filter=crew" --> doesn't work Any suggests? -
django ValidationError in admin save_model
Models.py class user(AbstractUser): salary_number = models.IntegerField(unique=True, null=True, blank=True) Admin.py def save_model(self, request, obj, form, change): if obj.salary_number == None: raise ValidationError("ERROR salary number!") .... obj.save() I'm trying to show error for user if they forget to fill salary number, but I got error ValidationError at /admin/information/user/add/. How can I fixed that? I have a reason to not set salary_number null & blank = False. -
Django Session auth and React token auth using one login page
I am working on converting an existing Django app (templates) to a microservices architecture - with a React frontend and a Django REST backend and am looking into how to handle authentication from a separately served (Nginx) React app where the user will be logging in using Django Session auth. Both frontend and backend will be served from the same domain using Nginx. Every service is packaged up in a separate Docker container. I am currently using the built in django.contrib.auth views for Session Auth: # authentication path('login/', auth_views.LoginView.as_view( template_name='users/login.html', authentication_form=AuthForm), name='login'), path('logout/', auth_views.LogoutView.as_view( template_name='users/logout.html'), name='logout'), The change will begin with writing new pages in React. Since these built-in Django auth views use Session Auth, and React usually relies on Token Auth, what are my options for using both Session and Token auth? My thought was to login using the built-in session auth and send a token with the response at the same time as the session response. Since the session will be authenticated, can the built-in session auth views be extended to send a JWT with the response then save it to local storage for access by React? Or should I focus on implementing session auth usage in React … -
Adding watchlist. Watchlist not displaying added items Django
I am trying to work on a project and one of the features is that users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. So far, I am redirected and receive the pop-up message when 'add to watchlist' is clicked but it does not bring up the button of 'remove from watchlist' and also when it redirects me to the watchlist page (where i should view the users entire watchlist), it shows me 'No watchlist found.'. I have triple-checked and I am iterating properly (I think) but I don't know why it is not showing any of the watchlist) URLS.PY path("add_watchlist/<int:listing_id>/", views.add_watchlist, name="add_watchlist"), path("watchlist", views.watchlist, name="watchlist"), MODELS.PY class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ManyToManyField(Auction) def __str__(self): return f"{self.user}'s watchlist" LAYOUT.HTML <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">Category</a> <li class="nav-item"> <a class="nav-link" href="{% url 'create_listing' %}">Sell</a> </li> <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a> {% endif %} </li> </ul> VIEWS.PY @login_required def add_watchlist(request, listing_id): items = Auction.objects.get(pk=listing_id) watched = Watchlist.objects.filter(user=request.user, item=listing_id) if request.method == 'POST': if watched.exists(): watched.delete() messages.success(request, 'Listing removed from watchlist') … -
Can someone help me use react integrated paycard template in open layer payment gateway
I want to put my custom UI instead of open layer payment gateway UI but I am having issues understanding the code of the gateway. From what I have understand that it is ready made UI Payment Gateway and I am having issues replacing styling of this gateway. My website is using Django + React frameworks. Payment Gateway I am integrating in my website: https://github.com/bankopen/layer-sdk-python React Paycard template I want to use: https://github.com/jasminmif/react-interactive-paycard Warm Regards Keshav -
How to sort a model for a month's data in django?
This is for a project where we can enter income and expenditure and save it in the model. I need to sort records in a model according to month basis, like record for previous month. -
Django Password Recovery via Gmail [Errno 110] Connection timed out
I had a password recovery system via email in my web app, which was working perfectly before deployment. However, now that I have succesfully deployed, password recovery is the only feature that is not working, when solicited it stays loading for some time until the error TimeoutError at /password-reset/ [Errno 110] Connection timed out Here is my settings.py file email configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = config.get('EMAIL_PASS') The credentials are tucked away into config file. What could be causing this issue?