Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Authentication credentials were not provided for magiclink
I am trying to create authenticaiton sytem where a user can loging using a magic link. i am usign a custom user mode. class UserAuthView(CreateAPIView): http_method_names = ['post'] serializer_class = TestUserListSerializer permission_classes = (IsAuthenticatedTestUserPermissionAdmin,) def post(self, request, name, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={'request': request} ) if serializer.is_valid(): email_id = serializer.validated_data['email'] try: user = TestUser.objects.filter(email=email_id).first() if user: company = str(user.company) user_id = user.id # Add the random string here random_string = get_random_string(16) request.session["login_state"] = random_string token = signing.dumps({"email": email_id, "login_state": random_string}) qs = urlencode({'token': token}) magic_link = request.build_absolute_uri( location=reverse('api-magiclink'), ) + f"?{qs}" return Response({ 'success': True, 'message': 'magiclink created .', 'data': { 'access_token': magic_link, } }) else: return Response({ 'message': 'User does not exist', }) except TestUser.DoesNotExist: return Response({ 'message': 'Unable to login user' }) else: return Response(serializer.errors) Then tryin to validate this using the following code class PartnerUserMagicLink(CreateAPIView): http_method_names = ['get'] permission_classes = (IsAuthenticatedTestUserPermissionAdmin,) def get(self, request, token, **kwargs): token = request.GET.get("token") if not token: # Go back to main page; alternatively show an error page return redirect("/") # Max age of 15 minutes data = signing.loads(token, max_age=900) email = data.get("email") if not email: return redirect("/") user = TestUser.objects.filter(username=email, is_active=True).first() if not user: # user does not exist … -
Django+PostgreSQL: creating user with UserCreationForm saves it to auth_user table, but not to the table created for the User model
I'm learning Django and now developing a simple food blog app for practice, using Django 4.1 and PostgreSQL. Since I'm not quite good yet at understanding how some concepts work in practice, I started with creating the basic structure (models, views, etc.) as per MDN Django Tutorial, and then went on adding other things based on various Youtube tutorials. I also created some users with Django Admin to see if everything works, and work it did... until I implemented user registration. I successfully registered several users via registration form and could log in as anyone of them, view their profile page, etc., but found out they were not displayed anywhere in the users list. At the same time, I couldn't log in to any of the accounts I created previously with Django Admin. Having searched for errors through the code of my 'recipeblog' app, I finally went to check the database I used. There, I found two different tables with different users: the first one named recipeblog_user, containing users created with Django Admin, and the second one named auth_user, containing users created with registration form. Thus I seem to have found the problem, but it got me stuck, for I … -
Which method to implement Websocket in Django?
I know that there are two ways to implement websocket in Django With Django channels Deploying a separate WebSocket server next to Django project My question is which one is better for scaling and customization ? -
Chain-Model Getting all objects for template
models.py class Sirket(models.Model): isim = models.CharField(max_length=20) def __str__(self): return f"{self.isim}" class Proje(models.Model): ad = models.CharField(max_length=20) total = models.DecimalField(max_digits=20,decimal_places=0) kalan = models.DecimalField(max_digits=20,decimal_places=0) tarih = models.DateField() firma = models.ForeignKey(Sirket, on_delete=models.CASCADE) def __str__(self): return f"{self.ad}" class Santiye(models.Model): isim = models.CharField(max_length=20) kasa = models.DecimalField(max_digits=20, decimal_places=0, default=0) araclar = models.ManyToManyField(Arac) baglanti = models.ForeignKey(Proje, on_delete=models.CASCADE) def __str__(self): return f"{self.isim}" class Personel(models.Model): ad = models.CharField(max_length=50) cinsiyet = models.CharField(max_length=10) yas = models.DecimalField(max_digits=4, decimal_places=0) baslamaTarih = models.DateField() resim = models.FileField(default="static/images/avatar.jpg") birim = models.ForeignKey(Santiye, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.ad}" views.py def firma(request): sirket = Sirket.objects.all().prefetch_related('proje_set').order_by('id') # i have multiple classes with connect each other. # like Proje class connected to Sirket class with many-to-one relationship. # It goes like : Sirket -> Proje -> Santiye -> Personel # I'm trying to access the Personel.ad objects that are linked to the Sirket. template <div class="container"> <div class="row"> {% for sirket in sirket %} <div class="card mb-3"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-9"> <div class="card-body"> <h3 class="card-title"><b>{{ sirket.isim }}</h3></b> <p class="card-text"><b>Şantiyeler:</b></p> <p>{% for araclar in santiye.araclar.all %} <li>{{ araclar }}</li> {% endfor %}</p> <p class="card-text"><b>Çalışan Personeller:</b></p> <p>{% for personel in santiye.personel_set.all %} <li>{{personel.ad}}</li> {% endfor %}</p> **<!-- I try to list santiye personels like above --> ** </div> </div> </div> … -
Terminal unresponsive after running server in Django and Python
I was following a tutorial on Django in python to learn how to build a website. But when I run the command "python manage.py runserver" it executes the command successfully, but after that I cannot type anything into the terminal, I can't even break. Here's a screenshot if it helps you understand my issue I've tried closing everything and rewriting all the code again, and it yields the same results. -
How to solve AttributeError: 'bool' object has no attribute '_committed' in Django
Traceback error: Internal Server Error: /home/absensi_masuk/face_detection Traceback (most recent call last): File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\skripsi\program\new_sisfocvwaero\project_sisfocvwaero\app_sisfocvwaero\views.py", line 332, in face_detection instance.save() File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\base.py", line 1047, in _do_insert return manager._insert( File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\query.py", line 1791, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1659, in execute_sql for sql, params in self.as_sql(): File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1583, in as_sql value_rows = [ File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1584, in [ File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1585, in self.prepare_value(field, self.pre_save_val(field, obj)) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\sql\compiler.py", line 1533, in pre_save_val return field.pre_save(obj, add=True) File "E:\skripsi\program\new_sisfocvwaero\env\lib\site-packages\django\db\models\fields\files.py", line 313, in pre_save if file and not file._committed: AttributeError: 'bool' object has no attribute '_committed' My Views.py : `while True: ret, frame = cap.read() face_cascade = cv2.CascadeClassifier('E:/skripsi/program/new_sisfocvwaero/project_sisfocvwaero/app_sisfocvwaero/face.xml') gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(frame, str("OK"), (x+40, y-10), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 255, 0)) … -
Loading html file using js in django project
I have a django template in which I want to load a html file in a div depending on the value of a select box. This is the target div: <table id="template" class="table"> Where to load tables. </table> I have an tag: <a href="#" onclick='loadHtml("template", "user_table.html")'>dadjias</a> Which when clicked calls the javascript function: function loadHtml(id, filename) { let xhttp; let element = document.getElementById(id); let file = filename; if (file) { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) {element.innerHTML = this.responseText;} if (this.status == 404) {element.innerHTML = "<h1> Page not found.</h1>";} } } xhttp.open("GET", `templates/${file}`, true); xhttp.send(); return; } } However the issue is that for some reason when the function is called, the file cannot be found so the 'Page not found' displays on screen. These are the files in my django project: Files in Django project The html file I am tring to load in the div is at the bottom. Any help would be much appreciated and thank you in advance. -
How to hide stuff in template if Current User isn't on their own profile in Django?
I have a profile page with a button 'edit profile'. however, it shows up for all users when they access the profile. How do I hide/remove it if the profile doesn't belong to the owner?? For example: Alice visits Bob's profile page or vice versa. They can both see 'edit profile' button on each other's page. <a class="btn btn-primary" href="{% url 'editprofile' %}" role="Edit">Edit Profile</a>' my views @login_required # profile page def profile(request): return render(request, 'profile.html') my model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username -
How can I make my Django rest API run along side my react app on a custom domain HTTPS server?
I was wondering if it would be possible to run my Django rest API along side my react app on a custom domain HTTPS server. Currently I have my website on a google cloud VM with a custom domain attached to it via the CloudFlare service. The issue that I am currently facing is that I cannot set the csrftoken cookie on my browser since I would be trying to access my API on port 8000 (Unsafe) while my page is on HTTP or even HTTPS on a different domain. What should I do in this situation? What would be my best option? I have tried setting the CSRF_COOKIE_SAMESITE to None but it requires me to set Secure as well but once I do this I end up with a similar problem where I cannot access the token as my API is not on a secure server. -
Django: NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent
I am trying to integrate stripe into my django application, i have followed the documentation and some articles, but when i hit the checkout button i get this error that says NOT NULL constraint failed: payments_orderdetail.stripe_payment_intent, what could be the issue here because everything seems to be working fine, this is the github repo. views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) product = get_object_or_404(Product, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( # Customer Email is optional, # It is not safe to accept email directly from the client side customer_email = request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'inr', 'product_data': { 'name': product.name, }, 'unit_amount': int(product.price * 100), }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('success') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('failed')), ) # OrderDetail.objects.create( # customer_email=email, # product=product, ...... # ) order = OrderDetail() order.customer_email = request_data['email'] order.product = product order.stripe_payment_intent = checkout_session['payment_intent'] order.amount = int(product.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) models.py class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) product = models.ForeignKey( to=Product, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = models.CharField( max_length=200, null=True, blank=True … -
How to get the detailed page by slug and not id in Django Rest Framework class based views
I am building an API using Django Rest Framework. I have the /api/localities endpoint where all of the objects on my database are displayed. Now I want to create the endpoint for a single page of a particular locality, and I want to make it by slug and not id for example /api/localities/munich. I am using Class based views and right now I can get the single page by id, for example /api/localities/2, but I want to change that to the slug. How can I do this? Here is my code: models.py class Localities(models.Model): id_from_api = models.IntegerField() city = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) postal_code = models.CharField(max_length=20, null=True, blank=True) country_code = models.CharField(max_length=10, null=True, blank=True) lat = models.CharField(max_length=255, null=True, blank=True) lng = models.CharField(max_length=255, null=True, blank=True) google_places_id = models.CharField(max_length=255, null=True, blank=True) search_description = models.CharField(max_length=500, null=True, blank=True) seo_title = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.city serializers.py from rest_framework import serializers from .models import Localities class LocalitiesSerializers(serializers.ModelSerializer): class Meta: model = Localities fields = ( "id", "id_from_api", "city", "slug", "postal_code", "country_code", "lat", "lng", "google_places_id", "search_description", "seo_title", ) views.py from django.shortcuts import render from django.http import HttpResponse from wagtail.core.models import Page from .models import LocalityPage, Localities from django.core.exceptions import ObjectDoesNotExist from … -
trying to link css in html file for a django project
Directories Attached is a photo of my directories. Am am trying to use sudokuStyle.css in sudoku_board.html. However, it does not seem to make the connection in my html file. I am including my head for the HTML. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sudoku Solver</title> <link rel="stylesheet" type="text/css" href="{% static 'css/sudokuStyle.css' %}"> </head> Where could I be going wrong? I have tried a variety of ways to connect but it does not work. -
How to align text or url in Django template? - Python Crash Course, Project "Learning Log"
I am creating "Learning Log" Django web-application using "Python Crash Course, 2nd edition" book. But since I reached 20th chapter of the book, I started having problems. I created a template, that displays all entries of the particular topic. On the page we have entry title, date, a button to edit it, and of course its text. Following the book, I use bootstrap4 to make pages looks more beautiful. But I would like to align the entry date and the "edit entry" url to the right side. I tried style="text-align:right;" , but it doesn't work. I am really new to web development , so I beg you to not judge me strictly :) Page with topic and its entries topic.html {% extends 'learning_logs/base.html' %} {% block page_header %} <h3>{{ topic }}</h3> {% endblock page_header %} {% block content %} <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new entry</a> </p> {% for entry in entries %} <div class="card mb-3"> <h4 class="card-header"> {{ entry.title }} <small style="text-align:right;"> {{ entry.date_added|date:'M d, Y'}} <a style="text-align:right;" href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </small> </h4> <div class ="card-body"> {% if entry.text|length > 500 %} {{ entry.text|linebreaks|truncatechars:500 }} <p><a href="{% url 'learning_logs:entry' entry.id %}">Read more</a></p> {% … -
How to authenticate to Geonode api v2?
Im am creating a geonode-project app and I want to authenticate to the Geonode API v2, but I cannot find an endpoint to authenticate. I listed all endpoint of the api using http://localhost:8000/api/v2/ but I cannot find and endpoint to authenticate. How can I authenticate to the Geonode REST API? -
How to redirect Django button for loop in HTML to specific HTML page for that service?
Im working on a django project but got stuck here. I have a for loop which loops through the data from a model, basically looping in services which are offered and creating buttons for these. I would like to redirect the button to a specific page for only this service. So basically each service offered gets an own button and if clicked gets redirected to a page for this service only. As I add the link in an anchor I don't know how to get it from the for loop in HTML doc. How should I code this to get the desired result? MODEL: class ServiceTypes(models.Model): typ = models.CharField(max_length=255, primary_key=True, blank=False) pris = models.DecimalField(decimal_places=0, max_digits=6, null=False, blank=False) beskrivning = models.CharField(max_length=255, null=True, blank=True) VIEWS: def boka_service(request): services = ServiceTypes.objects.all() return render(request, 'main/boka.html', {'services': list(services)}) THE HTML PART: {% for r in services %} <a href="{% url 'homepage' %}"> <button class="button_x"> <p style="margin-top: -60px; font-size: 15px; font-weight: bold;">{{ r.typ }} {{ r.pris }},- kr</p> <p>{{ r.beskrivning }}</p> </button></a> {% endfor %} -
How to merge two queryset based on common key name in django
Lets say i have 2 QuerySet: <Queryset [a, b, c]> and <Queryset [a, d, e]> How can i merge those two to achieve : <Queryset [a, b, c, d, e]> -
django.db.utils.IntegrityError not solving this part
I need a help regarding django.db.utils.IntegrityError: I read similar questions on stackoverflow before posting a new question, but I could not find the right solution. Basically, I am following a course, let's say copy-pasting the code in models.py, serializers.py views.py And whenever I call python manage.py migrate, I get this error: django.db.utils.IntegrityError: The row in table 'LittleLemonAPI_menuitem' with primary key '1' has an invalid foreign key: LittleLemonAPI_menuitem.category_id contains a value '1' that does not have a corresponding value in LittleLemonAPI_category.id. Anyone can help, how could I fix that error? The strange part is, that I literally follow each step on the course, it isn't even my code, and I can't figure out what's wrong. I tried to delete all migration related files and db.sqlite3, but in that way I lose all the previously entered data. I tried changing the part from on_delete.PROTECT, default=1. into. on_delete.CASCADE and removing default1, but nothing worked. -
Django form start date and date validation
I am trying to validate that the end date is greater than the start date. This is a form editing an entry submitted in a previous form. The startdate field has already been populated. This function was written based on Django documentation: [https://docs.djangoproject.com/en/4.1/ref/forms/validation/] When I submit the form there is no error thrown. Is this function called simply by submitting the form? What am I missing? ` class EditForm(ModelForm): class Meta: model = Cast fields = [ 'enddate', ] def clean(self): cleaned_data = super().clean() start_date = self.cleaned_data.get('startdate') end_date = self.cleaned_data.get('enddate') if end_date < start_date: raise ValidationError("End date must be greater than start date") ` I was expecting to see the error "End date must be greater than start date" In reality, the form submits no problem with an end date that is less than the start date. -
Django relation of models
I have an e-commerce project and I stuck at admin view. I have 2 models, namely Order and OrderItem. They are connected with FK relationship, and when Order is created I create both Order and related OrderItems in my admin page. Orders in admin page: OrderItems in admin page: When I open my OrderItems, I see my OrderItem belongs to which Order. I want to add Order# to my OrderItem# list in my admin page. In other words: I want to express "OrderItem.str" = "existing OrderItem.str" + "Order.str" My desired OrderItem__str__ format is something like: OrderItem#4-Order#2 views.py file: if request.user.is_authenticated: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost, user=request.user) order_id = order.pk for item in cart: order_item = OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user) # Update stock product = Product.objects.get(title=item['product']) product.stock_qty -= int(item['qty']) product.save() models.py file: class Order(models.Model): full_name = models.CharField(max_length=300) email = models.EmailField(max_length=255) shipping_address = models.TextField(max_length=10000) amount_paid = models.DecimalField(max_digits=8, decimal_places=2) date_ordered = models.DateTimeField(auto_now_add=True) # Foreign key (FK) # Authenticated / not authenticated_users user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class Meta: # Update admin view label verbose_name_plural = 'Orders' # Admin list view of order records def __str__(self): return 'Order - #' + str(self.id) class OrderItem(models.Model): # Link Order to Orderitem class # … -
Django forms dont displaying all fields
I have a problem, i need to create form like scheme, i have my models and created forms.py.When i add my forms into the HTML, i have only 2 of all fields in my forms.What it can be? This is my models.py class Post(models.Model): full_name = models.CharField(max_length=60, verbose_name='Full name'), name_scheme = models.CharField(max_length=40, verbose_name='Name of scheme') job = models.CharField(max_length=100, verbose_name='Job'), email = models.EmailField(verbose_name='Email'), domain_name = models.CharField(max_length=100, verbose_name='Domain'), phone_number = PhoneNumberField, company_name = models.CharField(max_length=30, verbose_name='Company name'), text = models.TextField(max_length=255, verbose_name='Text'), age = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(65)]) address = models.CharField(max_length=255, verbose_name='Address'), created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name forms.py class AddSchemeForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py def add_scheme(request): if request.method == 'POST': form = AddSchemeForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = AddSchemeForm() return render(request, 'add_scheme.html', {'form': form}) -
TypeError at /accounts/add_rent_payment/1363902a-c341-4883-84ee-1e12156b0381
I have two model namely Receipt and RentPayment. What I want to achieve is for me to create a Receipt, I want to redirect to a RentPayment form with a initial value of the recently saved receipt in the receipt field. #Models class Receipt(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) receipt_number = models.CharField(max_length=4, null=True, blank=True) property = models.ForeignKey(Property, null=False, blank=False, on_delete=models.CASCADE) month_paid = models.CharField(max_length=15,null=True,blank=True,choices=MONTHS) balance_due = models.DecimalField(max_digits=5, decimal_places=2) total_rent = models.DecimalField(max_digits=7, decimal_places=2, null=True,blank=True) class RentPayment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) receipt = models.ForeignKey(Receipt, null=True, blank=True, on_delete=models.CASCADE) property = models.ForeignKey(Property, null=True, blank=True, on_delete=models.SET_NULL) amount_paid = models.DecimalField(max_digits=7, decimal_places=2) payment_date = models.DateField(auto_now=True) next_payment_due = models.DateField(auto_now=True) #Views def createReceipt(request,pk): property_entity = Property.objects.get(id=pk) form = ReceiptForm(initial={'property' :property_entity}) if request.method == 'POST': form = ReceiptForm(request.POST, initial={'property' :property_entity}) if form.is_valid(): receipt_obj = form.save(commit=False) receipt_obj.property = property_entity receipt_obj.save() return redirect('add_rent_payment', receipt_pk=receipt_obj.id) else: ReceiptForm() context = {'property_entity' :property_entity, 'form' :form } return render(request,"accounting/receipt.html",context) def add_rent_payment(request, pk): receipt = Receipt.objects.get(id=pk) if request.method == 'POST': rent_payment_form = RentPaymentForm(request.POST) if rent_payment_form.is_valid(): rent_payment = rent_payment_form.save(commit=False) rent_payment.receipt = receipt rent_payment.save() return redirect('property_list') else: rent_payment_form = RentPaymentForm() context = { 'receipt': receipt, 'rent_payment_form': rent_payment_form, } return render(request, 'accounting/add_rent_payment.html', context) #urls urlpatterns = [ path('receipt/<str:pk>', views.createReceipt, name="receipt"), path('add_rent_payment/<str:receipt_pk>', views.add_rent_payment, name="add_rent_payment") ] -
Obtaining a refresh token from gapi auth2
I have the following use case: I have a Django REST + Vuejs application in which users log in using Google OAuth 2. Once they've logged in, there are some actions that they might perform which require them to grant my application extra permissions, i.e. more scopes than they originally gave permission for when logging in. These applications are performed on the backend, which will send Google services requests authenticating as the users, so I need to somehow store the access tokens, which have also been granted specific scope permissions, on my backend. In order to implement this flow, I thought about following the guide on incremental auth and do the following: const option = new gapi.auth2.SigninOptionsBuilder(); option.setScope(ADDITIONAL_SCOPES_TO_REQUEST); const googleUser = auth2.currentUser.get(); const res = await googleUser.grant(options) const response = res.getAuthResponse() The response variable will hold an object which, among the other properties, has the access_token returned by Google. After that, I can issue a request to my Django backend to create an instance of some GoogleAccessToken model which will hold the token returned by Google and use it for authenticating server-to-server requests to Google services. The idea is to use it this way: from google.oauth2.credentials import Credentials from .models … -
How to properly create recursive comments in templates django?
I want to create a tree like comment section in my site, but I can't handle to work it as expected. I just ended up with a mess there, but it seems to me that model works perfectly.. Maybe I am wrong, but I assume there is a template logic problems. I've attached a screenshot of how it looks now. As you can see, comments are duplicating each other and do not construct a tree like stuff. Can somebody point me in the right direction? Models.py class Comment(models.Model): user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField(max_length=255) comment_to_reply = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='replies') created_at = models.DateTimeField(auto_now_add=True) comments_template.html {% if post.comments %} {% for comment in post.comments.all %} <a name="comment-{{ comment.id }}"></a> <div class="row" id="{{ comment.id }}"> <div class="shadow-sm mb-3 card border-0 p-3 bg-light"> <div class="panel-heading"> <strong>{{ comment.user.username }}</strong> <a href="#comment-{{ comment.id }}"></a> <small class="text-muted">{{ comment.created_at }}</small> </div> {% if form %} <div class="row"> <div class="col-10">{{ comment.body }}</div> <div class="col text-end"> <a class="btn btn-primary btn-sm" onclick="return show_comments_form({{ comment.id }})">Reply</a> </div> </div> {% else %} <div>{{ comment.body }}</div> {% endif %} </div> </div> {% if comment.replies %} <div class="offset-md-3"> {% for comment in comment.replies.all %} <div class="row"> … -
How display circleMarker data using several colors?
How display circleMarker data using several colors according to magnitude value. For example this map (https://cartonumerique.blogspot.com/2023/02/seismes-en-Turquie-et-Syrie.html)? Here is my map function and my map script. #views.py def data(request): all_evens = Even.objects.all() _data = [[obj.name, obj.date, obj.latitude, obj.longitude, obj.magnitude] for obj in all_evens] return JsonResponse (_data, safe=False) #evenmap.html <!DOCTYPE html> {% load static %} <html lang ="en"> <body> </body> {% block js %} <script> var even = L.layerGroup() $.ajax({ url:"{% url 'even:data' %}", type:"GET" success: function(response){ response.forEach(obj =>{ L.circleMarker([obj[6], obj[7]], { radius: obj[8] * 3, fillColor: "#ff7800", color: "#000", weight: 1, opacity: 1, fillOpacity: 0.6 }).bindPopup('Name: ' + obj[0] + '</br>' + 'Date: ' + obj[1] + '</br>' + 'Latitude: ' + obj[2] + '</br>' + 'Longitude: ' + obj[3] + '</br>' + 'Magnitude: ' + obj[4] ).addTo(even) }); }, error: function(response){ alert(response.statusText); } }); </script> {% end block js %} </html> -
Does anyone used Django-postman for implementing private chat?
Iam newbie to programming as well as in Django framework, recently i am creating a website that user can chat 1 to 1 "private chat" i found lot of tutorials, like creating Django chat with django-channels every on of them are creating with chatroom, i like to implement 1 to 1 chat. is there any tutorial in Django-postman or does anyone created chat with django-postman? if you anyone came across any alternative that would be helpful. Any advice will helpful.