Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error when attempting to add items into the database
So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py. from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=150, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Blist(models.Model): name = models.CharField('Business Name', max_length=250) address = models.CharField('Address', max_length=300) city = models.CharField('City', max_length=100) zip_code = models.CharField('Zip Code', max_length=10) phone_number = models.CharField('Phone Number', max_length=20) web = models.URLField('Website') def __str__(self): return self.name But when I go into the shell to add items into the category, I'm getting errors: django.db.utils.ProgrammingError: column listings_category.name does not exist LINE 1: SELECT "listings_category"."id", "listings_category"."name",... What am I doing wrong here? -
Adding dictonary values while using HttpResponseRedirect
I want to redirect to the existing page and display a queryset which would be determined based on the values submitted via the form. The dictionary values I get from function get_context_data display correctly. The dictionary values I try and add in the post function do not display correctly. def post(self, request, *args, **kwargs): RoomBookingsForm = BookRoomsForm(request.POST or None) self.object = self.get_object() # assign the object to the view context = self.get_context_data( *args, **kwargs) context.update({'room_type_queryset': RoomType.objects.all().filter()}) print("all context values") print(context) if request.method == 'POST': return HttpResponseRedirect(self.request.path_info, context ) As well as context.update I also tried context['room_type_queryset'] = RoomType.objects.all().filter() Based on the two print statements above I got all context values {'object': <AmericanHotel: Caesars Palace>, 'americanhotel': <AmericanHotel: Caesars Palace>, 'slug': 'caesars-palace', 'view': <hotel.views.HotelDetailSlugView object at 0x00000210575117F0>, 'cart': <Cart: 5>, 'hotel_extra_photos': <QuerySet [<AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>]>, 'room_type': <QuerySet [<RoomType: Caesars Palace, Triple>, <RoomType: Caesars Palace, Double>]>, 'room_type_queryset': <QuerySet [<RoomType: Caesars Palace, Double>, <RoomType: Caesars Palace, Triple>]>} The results from room_type are correctly displayed in red. {% for instance in room_type %} <H1 style="color:red">{{instance}}</H1> {% endfor %} The results from … -
Django - How to store emojis in postgres DB properly?
I'm running the latest version of Django on postgres. I'm trying to store emojis in my postgres DB in a way that a React Native app can properly render it. Below I have the initial emojis variables setup that'll go into the talbe. I've copy and pasted the emojis from here. As you can see I'm getting an error from PyCharm regarding it being a "BAD_CHARACTER". How do I store emojis in my postgres DB so that a React Native app can render it properly? -
postgres performance is very slow with django
I made a very small web-app in django with sqllite3 and then I just connected the same app to postgres db in which I reccreated the tables using makemigrations and then now when I am using even the admin page, with just one superuser - admin - its very very slow. I tried postgresql.conf file to set the parameters - seq_page_cost = 1.0 and random_page_cost = 1.0 and restarted postgres.sql from services, but to no avail. is there anything I need to do apart from this ?? please let me know. -
Django/Foundation CSS Accordion Not Displaying Contents
When using the sample code here in my Django template, the information in the accordion-content div will not display on the screen, but inspecting the HTML shows that it exists. In my provided code I have both my dynamic version of the accordion and the sample code copy pasted to show both do not work, but that the information is seemingly loaded into the webpage. I can provide more information but I am unsure what would be relevant so I only included my HTML and a screenshot of the webpage. Is it possible Django is interfering with the Foundation CSS/JS? Base.html {% load static %} <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/foundation.css' %}"> <link rel="stylesheet" href="{% static 'css/select2.css' %}"> {% block css %}{% endblock %} </head> <body> <!--Need to fix top bar--> <div class="top bar"> <div class="top-bar-left large-offset-1 medium-offset-1"> </div> <div class="top-bar-right"> <ul class="dropdown menu" data-dropdown-menu> <li class="menu-text">Reading List Website</li> {% if user.is_authenticated %} <li><a href="/logout/">Logout</a></li> {% else %} <li><a href="/login/">Login</a></li> {% endif %} </ul> <ul class="menu"> {% if user.is_authenticated %} {{ user.username }} {% else %} Guest {% endif … -
"created" value of TimeStampedModel is showed diffrently
I am creating the review part in my Django project. When the new review is created, the page will show the new review without redirect(with javascript), and after the page is redirected it will show the same review from DB. but the there is some difference between the created time of new review from javascript and the other one from DB. On the template, the review from DB is showed exactly my local time. But the new review created from javascript that takes the value of "created" from the backend, is different from the same review form DB after redirect. for example, 27-November-2021-00:11 (after the new review is rendered with JS without redirect) 27-Novembre-2021-09:47 (after redirecting, the new review from DB) It seems to me maybe the first one is not applicated UTC time. but printing the value of "created", the console shows 2021-11-27 00:49:57.878138+00:00 the hours are the same as the first one but the minutes are the same as the last one... I can't understand. because these two values are from the same thing, "created" of the TimeStamped Model. How could I make this value the same? models.py class TimeStampedModel(models.Model): """TimeStampledModel Definition""" created = models.DateTimeField( auto_now_add=True ) updated … -
API connection and getting the returned result
I'm sorry for my bad english Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information. payment_card = { 'cardHolderName': kartisim, 'cardNumber': kartno, 'expireMonth': kartskt_ay, 'expireYear': '2030', 'cvc': karcvc, 'registerCard': '0' } buyer = { 'id': adres.id, 'name': adres.adres_uye.username, 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': adres.adres_uye.email, 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': adres.adres_detay, 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [] for bas in uye: basa = { 'id': str(bas.id), 'name': str(bas.sepet_urun.urun_baslik), 'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik), 'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik), 'itemType': 'VIRTUAL', 'price': str(bas.sepet_fiyat) } basket_items.append(basa) print(basket_items) request_payload = { 'locale': 'tr', 'conversationId': '123456789', 'price': str(sepetf), 'paidPrice': str(sepetf), 'currency': 'TRY', 'installment': '1', 'basketId': str(sepetid), 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, 'basketItems': basket_items } payment = iyzipay.Payment().create(request_payload, options) print(payment.read().decode('utf-8')) return HttpResponse(payment["status"]) I cannot use the returned result information. The returned result is as follows The error I get is as follows: 'HTTPResponse' object is not subscriptable -
React django permissions
I am still new in react when I tried to delete an element from API(django rest framework) in my case it's not working Error message : Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/events/delete/3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.enter image description here -
How to save timeslot details when creating a booking instance django
I have a django app in which I am implementing a booking system. I have created a TimeSlot model that has a start_time, end_time, and time_slot_owner. I want to implement a booking system in which the timeslot details, such as the start_time, end_time, and time_slot_owner are added to the Booking Model once it has been created. My TimeSlot model: class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() My Booking Model: class Booking(models.Model): bookings_owner = models.ForeignKey(User, on_delete=models.CASCADE) # time_slot = models.ForeignKey(TimeSlot, on_delete) meals_booked = models.IntegerField(default=0, validators=[MinValueValidator(0)]) start_time = models.TimeField() end_time = models.TimeField() restaurant = models.ForeignKey(User, on_delete=models.CASCADE, related_name="restaurant") What I have in my create_booking function so far in views.py def create_booking(request): instance = Booking() data = request.POST.copy() data["bookings_owner"] = request.user form = BookingForm(data or None, instance=instance) if request.method == "POST" and form.is_valid(): start_time = request.POST.get("start_time") print(start_time) form.save() return HttpResponseRedirect(reverse("food_avail:view_bookings")) return render(request, "food_avail/create_booking.html", {"booking": form}) When I click on Book: It leads me to this page where I can enter number of meals I want to book: Once I enter the number of meals I want the final page to show the following details for each booking: Booking.booking_owner.username | TimeSlot.time_slot_owner.username | TimeSlot.start_time | TimeSlot.end_time | Booking.meals_booked -
Reportlab pdf prints only one page
I am able to create table with reportlab as shown below, but it prints only on one page, how I can print data to multiple pages def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf') -
how to create object in django
is it possible to create new product using the scrap.py in django ? when never i run scrap.py i get this error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. my app models file from django.db import models from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() content = models.TextField(max_length=400) def __str__(self): return self.name scrap.py file from models import Product Product.objects.create( name = 'BMW', age =25 , content = 'cool car' ) -
I need to create a login system with Django
I need to create a login system with Django using something like @login_required, but I don't wanna use the Users in "AUTHENTICATION AND AUTHORIZATION", Users are stored in my app. Can someone help me? I need to store login info in cache or something? -
Why I get an error when adding __init__(self) method to Django rest framework viewset class?
I Am keep getting a error when trying to build a Django API. I have this class: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments import serializers from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from Instruments.models import Instrument from Instruments.serializers import InstrumentsSerializer # Application views live here class InstrumentViewSet(viewsets.ViewSet): # instruments = Instrument.objects.all() def __init__(self): # self.instrument_service = InstrumentsService() # self.instruments = Instrument.objects.all() super().__init__() def list(self, request: HttpRequest): try: self.instruments = Instrument.objects.all() serializer = InstrumentsSerializer(self.instruments, many=True) # data = self.instrument_service.get_instruments() data = serializer.data return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) when the init() method is defining even if it is just doing pass the django server gives me this error when I send a request: TypeError at /api/ __init__() got an unexpected keyword argument 'suffix' If I remove or comment out the init() method it works.why?? -
Accessing static file images through url not working django
I am currently trying to configure my django project so that I can access static file images via url. However, it is currentely saying that the image does no exist. Here are my settings for static files: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/static/images') Here are my base project urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) And my folder structure is, in the root of my project: static->images->[all images in here] Upon trying to access an image via url like this: http://127.0.0.1:8000/images/*proper image name* It tells me that the image doesn't exist. Does anyone know why this may be happening? -
Python remote developer skills requirement
As an absolute beginner in python programming language, I find the language interesting and easy to learn. However, I intend to take up a job later as a python developer. My problem is I'm a little confused on what core areas to dwell on primarily rather than attempting to know all the classes, libraries and modules. I get overwhelmed. What core areas and possibly tutorials do I concentrate on? -
Put DISLIKE by removing LIKE. Django
Maybe someone can help. There is a Django project where I am trying to add a LIKE / DISLIKE function. I figured out how to add or remove LIKE / DISLIKE. But my logic has a gap in that the user can put both LIKE and DISLIKE (this is not entirely correct). Therefore, I want to make a "feint with the ears" as follows: if the user puts LIKE, then changes his mind and puts DISLIKE, then DISLIKE would be added, and LIKE would be canceled automatically (as happens on YouTube). I have the following views: class AddLikeView (View) class RemoveLikeView (View) class AddDisLikeView (View) class RemoveDisLikeView (View) As far as I understand, I need to write some kind of logic in AddDisLikeView and RemoveLikeView. Tell me please. class AddDisLikeView(View): def post(self, request, *args, **kwargs): blog_post_id = int(request.POST.get('blog_post_id')) user_id = int(request.POST.get('user_id')) url_from = request.POST.get('url_from') user_inst = User.objects.get(id=user_id) blog_post_inst = News.objects.get(id=blog_post_id) try: blog_dislike_inst = BlogDisLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst) except Exception as e: blog_dislike = BlogDisLikes(blog_post=blog_post_inst, disliked_by=user_inst, dislike=True) blog_dislike.save() return redirect(url_from) class RemoveLikeView(View): def post(self, request, *args, **kwargs): blog_likes_id = int(request.POST.get('blog_likes_id')) url_from = request.POST.get('url_from') blog_like = BlogLikes.objects.get(id=blog_likes_id) blog_like.delete() return redirect(url_from) -
Unable to send multiple to database in Django
My aim is to send all the Added items to my database. There is no error while posting data to the database but my form populates the database with only one entry, i.e., "The value of the last input among all inputs". I am new to Django development, please guide me on where I am doing wrong. My Html looks like this: Tables in my database: Primary key Table: Foreign Key Table: Table that already contains items. Table that is made to receive the items from table one. I am just trying to learn how to post data of multiple inputs, otherwise there isn't any logic behind this operation. From models.py: class Item(models.Model): Id = models.AutoField(primary_key=True) itemName = models.CharField(max_length=30,unique=True) cId = models.ForeignKey(Category,on_delete=CASCADE) def __str__(self): return self.itemName class TransferedItems(models.Model): Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.ForeignKey(Item, on_delete=CASCADE) From views.py: def transfer(request): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") From HTML: <html lang="en"> <body> <div class="maindiv"> <div class="divA"> <label for="coffee">Coffee</label> <select name="coffee" id="coffee"> {% for opt in opts %} <option value="{{opt.Id}}"> {{opt.itemName}} </option> {% endfor %} </select> <button onclick="addtocart()">ADD</button> </div> <div class="divB"> <form method="post" id="cart-screen-form" action="transfer"> {% csrf_token … -
Django render or redirect not working in view after AJAX POST
I am using navigator.geolocation to get an update on location with it's provided watchPosition function with following code: function updatePosition() { if(navigator.geolocation) { navigator.geolocation.watchPosition(calculateDistance); } else { console.log("Geolocation is not supported by this browser.") } } If then new location coordinates I fetch is under a kilometer in distance, I issue a post request and try to render another view. I use google maps API to calculate the distance with function computeDistanceBetween. Here is the code: function calculateDistance(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, mapOptions.center); if(dis <= 1000 && dis >= 0 && rendered == false) { var url = '/app/near_park/'; var csrftoken = getCookie('csrftoken'); $.ajax({ url: url, type: "POST", data: { csrfmiddlewaretoken: csrftoken, in_proximity : 1 }, success: function() { rendered = true; console.log("Success"); }, error: function(xhr, errmsg, err) { console.log(xhr.status+": "+xhr.responseText); } }); } } Here is the view handling the post request: def index_close(request): context_dict = {} try: current = Owner.objects.get(user=u) context_dict['checked_in'] = current.checked_in except: context_dict['checked_in'] = False print("##########") #return redirect(reverse('dogpark:register')) return render(request, 'dogpark/index_close.html', context=context_dict) Whenever I get a location update using the sensor utility of dev tools, I do see the print of hash marks on terminal but the redirect or … -
serializer.data not showing any data
I'm still getting to know DRF but when I run the command serializer.data it returns an empty set. Here is what I'm working with models.py import datetime from django.db import models from django.db.models.fields.related import ForeignKey from django.utils import timezone from accounts.models import CustomUser class IndustriaCategoria(models.Model): name = models.CharField(max_length=20, null=False, blank=False) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(IndustriaCategoria, on_delete=models.CASCADE) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=512, null=False, blank=False) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) link = models.URLField(max_length=500, null=True) ups = models.IntegerField(default=0) score = models.IntegerField(default=0) hotness = models.IntegerField(default=0) serializers.py from django.db.models import fields from rest_framework import serializers from .models import IndustriaCategoria, Empresa, Post, Comment class IndustriCategoria(serializers.Serializer): class Meta: model = IndustriaCategoria fielst = ('__all__') class PostSerializer(serializers.Serializer): class Meta: model = Post fields = ('__all__') I have a management command which creates some data so I can just start throwing commands. Here is where the problem comes up: >>> from accounts.models import CustomUser >>> from forum.models import IndustriaCategoria, Post >>> from forum.serializers import PostSerializer, IndustriaCategoria >>> u = CustomUser.objects.all().first() >>> i = IndustriaCategoria.objects.all().first() >>> post = Post(category=i, author=u, title='hello world', body='this is a test', link='https://helloworld.com') >>> post.save() >>> serializer = PostSerializer(post) >>> serializer.data {} Any idea why I got an empty … -
Cart delete an item and apply a coupon in js
I am trying to remove an item without removing the cart and reducing a price if the customer has a coupon or exceeds a certain quantity while js before using Django here is the html code js if you have any advice do not hesitate html <div data-name="name" data-price="250" data-id="2"> <img src="x.jpg" alt="" /> <h3>name</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> <script type="text/template" id="cartT"> <% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label"> <%= item.count %> piece<% if(item.count > 1) {%>s <%}%> for <%= item.total %>$</span > </div> <% }); %> </script> js addItem: function (item) { if (this.containsItem(item.id) === false) { this.items.push({ id: item.id, name: item.name, price: item.price, count: item.count, total: item.price * item.count }); storage.saveCart(this.items); } else { this.updateItem(item); } this.total += item.price * item.count; this.count += item.count; helpers.updateView(); }, containsItem: function (id) { if (this.items === undefined) { return false; } for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; if (id == _item.id) { return true; } } return false; }, updateItem: function (object) { for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; … -
Best way to render a sortable table from a Django Model which displays custom fields?
I want to generate a table based on selected fields from a model(decided by an algorithm), and I want to be able to sort the columns in that table. I also want the user to be able to click on a button on each row which leads to a new page generated by a key from that row (ie. "edit") I have tried django-tables2, but it seems that this would prevent me from adding the buttons and adding the algorithms I want which govern what types of fields are on display. The generation of the custom table itself is not a problem - but I can't seem to find any sources on making a sorting function. Where can I find this? -
Incorrect redirect of NGINX with Docker
I'm building my first project with Django, NGINX and Docker. Below the nginx.conf: upstream project { server website:8000; } server { listen 80; server_name MY-DOMAIN; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 4G; } location /static/ { alias /app/static-folder/; } location /media/ { alias /app/media-folder/; } } And the docker-compose: version: '3.7' services: website: container_name: web_project image: project/django build: ./djangodocker restart: always env_file: prod.env command: sh -c "cd djangodocker/ && gunicorn djangodocker.wsgi:application --bind 0.0.0.0:8000" volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder expose: - 8000 nginx: container_name: nginx_web_project image: project/nginx build: ./nginx volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder ports: - 8000:80 depends_on: - website volumes: static-folder: media-folder: I can build the image but I can't see the website into the correct url. I see the website at MY-DOMAIN:8000 instead of MY-DOMAIN and this is my problem. -
How to map different request types to different views using the same exact path in Django?
I want to have a url something like api/instrument/{id} and then based on the request type GET, POST, DELETE route the request to a different view in my Django app. I have these views: from django.shortcuts import render from django.http.response import JsonResponse, from django.http.request import HttpRequest from rest_framework.parsers import JSONParser from rest_framework import status from Instruments.services import instruments_service from models import Instrument from serializers import InstrumentsSerializer from rest_framework.decorators import api_view from services import InstrumentsService # Application views live here @api_view('GET') def get_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.get_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('POST') def update_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() instrument_data = JSONParser().parse(request) data={} try: data = instrument_service.update_instrument_by_id(id, instrument_data) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('DELETE') def delete_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.delete_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) I see that people using django make ONE function to hanlde all requests and then they have logioc inside it but that seems so wrong to me. Is there a way to map the same URL endpoint to different function based on the request type? -
How to read a specific field in a MongoDB collection
I want to print a specific field on html on mongodb, but I am getting an error, how can I do it? I'm getting IndexError: list index out of range error. view py; def deleted2(request): mpid = ('XX') tuy = ('XX') client = MongoClient("XX") print('connectionsuccess') database = client["1"] collection = database["2"] query = {} query["XX"] = mpid query["$or"] = [ { "Tuy": tuy } ] print('querysuccess') cursor = collection.find(query) sonuc= loads(dumps(cursor)) msg=sonuc[0]["_id"] print(msg) client.close() return render(request, 'deleted.html',{'msg':msg}) -
Identity Verification by SMS/Email | Django
Please help me with choosing a solution for implementing identity verification using a one-time token with a limited lifetime. By identity verification, i mean the need to send a token/code to a user via a phone number or email. For example, to reset password. I am interested in a solution that is best for use in a modern web application. Please tell me based on your experience in developing such systems. The solutions I have on my mind: Use redis as storage. In case of working with email, generate a token and save it in redis, where the key - user's email address. In the case of working with SMS, create a code and save it in redis, where the key - user's phone number. Possible disadvantage: since redis is designed to work with a key-value pair, it is impossible to have two tokens/codes at once. (meaning that they will have different purposes). It is possible that this is not necessary at all. Use the Django object model as storage. Something like this: class TokenManager(models.Manager): # Some util-methods. # ... def delete_expired(self): expires = models.ExpressionWrapper( models.F("created_at") + models.F("lifetime"), models.DateTimeField() ) self.annotate(expires_at=expires).filter(expires_at__lte=now()).delete() class Token(models.Model): # Roughly speaking, token identifier. Examples: "password-reset", …