Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How django-filter called inside class based view?
I am just trying to work with django-filters. Below are the details : filters.py import django_filters from .models import work_allocation class WorkFilter(django_filters.FilterSet): class Meta: model = work_allocation fields = '__all__' views.py from .filters import WorkFilter class get_task_list(ListView): model = work_allocation myFilter = WorkFilter() work.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>List of Tasks</h2> <form method="GET"> {{myFilter.form}} </form> </body> </html> But I do not see any changes on my web page. Is that the right way I am calling filter? Please suggest -
How do I run a functon right after posting a model DRF
I have an api that has two models Company (which requires company name) and Info (which i want to be filled automatically based on the Company name) So what I'm doing there is asking for a company name at "localhost:8000/company/" then I want to get this name, add it to the link then get the information from finance.yahoo.com with get request as csv, run through it and fill my Info model with the information. The problem is when I'm calling Company.objects.last() it gets me the information about previous company For example: I post ZUO, it gets me nothing, then i post PD and I get info about ZUO Here is my models.py class Company(models.Model): company = models.CharField(max_length=10) class Info(models.Model): Date = models.CharField(max_length=64) Open = models.CharField(max_length=64) High = models.CharField(max_length=64) Low = models.CharField(max_length=64) Close = models.CharField(max_length=64) AdjClose = models.CharField(max_length=64) Volume = models.CharField(max_length=64) Here is my view.py def get_download_url(): comp = Company.objects.last() downloadUrl = ('https://query1.finance.yahoo.com/v7/finance/download/' + comp.company.upper() + '?period1=0&period2=5000000000&interval=1d&events=history&includeAdjustedClose=true') return downloadUrl def get_information(): downloadUrl = get_download_url() headers = {'User-Agent': 'user-agent'} response = requests.get(downloadUrl, headers=headers) info = [string.split(',') for string in response.text.split('\n')[1::]] return info class CompanyViewSet(viewsets.ModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.none() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) Info.objects.all().delete() info = … -
AttributeError 'list' object has no attribute '_committed'
I have created a page where the staff will upload their image and description, but when i click on the submit button, I got this error: AttributeError 'list' object has no attribute '_committed' as shown in the picture below. How do I fix this error? What die I do wrong in my code? AttributeError 'list' object has no attribute '_committed' traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/add/ Django Version: 2.2.20 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "E:\Role_based_login_system-master\account\views.py" in addPhoto 422. photo = Photo.objects.create( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py" in create 422. obj.save(force_insert=True, using=self.db) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save 743. self.save_base(using=using, force_insert=force_insert, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in save_base 780. updated = self._save_table( File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _save_table 873. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py" in _do_insert 910. return manager._insert([self], fields=fields, return_id=update_pk, File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to add values for checked rows
The code below prints the list of students in Django as a table. I would like to add the name of the currently logged in account to the teacher column in the checked row when the 'Add Teacher' button is clicked. And I want the added data to be reflected in the DB. <table id="student-list" class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Sex</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.register_date|date:'Y-m-d' }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td>{{ student.teacher}}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Teacher" class="addteacher"> </table> <script> $(function() { $(document).on("click", ".addteacher", function() { var getselectedvalues=$(".maintable input:checked").appendTo($(".maintable tbody").add(getselectedvalues)); }) }); </script> -
Ger all form data as a list, iterate over it and dilplay them in a table on template
I am working on a simple school project where students and teachers are registered as users. class monitors get a student list of their class and monitors have to submit and send a report to class teacher that all the students in the class are present for a certain lesson. So I have created a student model where parent class is the admission number. Then I have filtered a certain class (ex: Grade-6) and render them in to a template (grade-6 dashboard) and gave access to grade 6 class monitor. So the monitor can see all the student with their admission number on monitor dashboard. Then I have insert a select option with each student to select yes or no to say he or she is present or not. Then submit. After submitting in my view.py I get all the data as request.POST. But after saving the form (form.save()) I get last student details only. But all the details are in request.POST but I cannot get them to render in to a template. I dont know how. So I tried getting them as a list or a dict but couldnt. Please help me on getting this done. My form in … -
Static files are not found (gunicors)
I know this question was already asked frequently. But the supposed solutions seem not to help me. Here is my Nginx definition for the static files location /static/ { alias /data/atsi_webapp/ATSi_WebApp/static; } Here my Django settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I did run already python manage.py collectstatic However, I get Not Found: /static/js/xxxx.js -
using custom function inside ModelViewset in Django rest framework
I always used APIView for writing all the CRUD operations in a single api view as because APIView already recognises which actions to be performed on the basis of http methods that comes from the request from the frontend. Recently I came across some code that is written using ModelViewset. Here a custom function is defined instead of list, create, destroy. For example a function named **"get_all_students_questions"** . Here is the snippet below: class QandaApiViewSet(viewsets.ModelViewSet, PusherMixin): """ Viewset that returns the paginated Qanda Details. """ queryset = Qanda.objects.all().order_by("-created_at") serializer_class = QandaModelSerializers def get_pusher_settings(self): setting = Setting.objects.filter(slug="pusher").first() if setting: return setting.settings return None def create(self, request): """ The method that accepts the form data to save the data as Qanda instance. """ serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): validated_data = serializer.validated_data image_content = validated_data.get("content") subject = validated_data.get("subject") """ cms_content contains the cms data in which base64 image are converted to aws url image and content_Writing contains the image_url to those aws url image. """ cms_content, content_writing = parse_image_from_editor(image_content) new_data = { "content": cms_content, "content_writing": content_writing, "subject": subject, "student": request.user, } qanda = Qanda(**new_data) qanda.save() data = {"data": cms_content, "response": "Submitted Successfully"} """ Sending notification to admin side """ try: # getting pusher … -
How to add extra fields outside the list of items in modelView ? (like count for pagination)
I'm looking for the best way to add additional fields to the get list return of a ModelView. I have the following model: class Sale(models.Model): total = models.FloatField(_("Total")) name = models.CharField(_("Name")) [...] When I do a get list on this model, I get the following json: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "results": [ { "id": 0, "name": "example", "total": 0, [...] } ] } I would like to add 2 fields min_total and max_total to the result (at the same level as "count"). Example: { "count": 0, "next": "http://example.com", "previous": "http://example.com", "min_total": 0, "max_total": 100, "results": [ { "id": 0, "name": "example", "total": 100, [...] } ] } My View: class SaleViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for listing or retrieving sales. """ permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filter_fields = ['client', 'machine', 'date_time', 'total'] ordering_fields = '__all__' def get_serializer_class(self): if hasattr(self, 'action') and self.action == 'list': return SaleListSerializer if hasattr(self, 'action') and self.action == 'retrieve': return SaleRetrieveSerializer return SaleSerializer def get_queryset(self): queryset = Sale.objects.all().select_related('client') user = self.request.user if user.is_staff: cache_key = 'list_sale_sales' else: queryset = queryset.filter(client=user.profil.client) cache_key = f'list_sale_sales_client_{user.profil.client.pk}' return cache.get_or_set(cache_key, queryset, 60) To get these 2 values I just have to make these 2 requests: Sale.objects.all().aggregate(min=Min("total")) … -
how to save images in to particular path when image is give from link or url, in python
I'm trying to save images that are given from link, such a way that, image save in the given path and image file_name is created with uuid like below: my profile model is: class Profile(DataTimeModel): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) email_address = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) address = models.CharField(max_length = 255, null=True, blank=True) citizenship_no = models.CharField(max_length = 25, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) Now when the profile is enrolled I will send multiple image link or single, from these link I need to download the image and save to the file path like below: root_dir = MEDIA_ROOT+'/profile/' new_dir = str(profile.id) file_name = str(uuid.uuid4())+'.jpeg' path = os.path.join(root_dir, new_dir) os.makedirs(path) Now, I need to save the image that comes from the URL into the path folder with image name file_name with extension. How can I do that? I try by using urllib.request.urlretrieve(url, file_name) this but it saves into base directory but I need to save in given path. Image link is given from this interface: -
forms.py creaing forms with ForeignKey model. A store should only be able to add products to its own store. (Django)
A store should only be able to create a product for himself, not for other stores. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from django.dispatch import receiver class Store(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) class Product(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=False, blank=False) name = models.CharField(max_length=200) price = models.FloatField() image = models.ImageField(null=True, blank=True) forms.py from .models import Store, Product from django import forms class AddProductForm(forms.ModelForm): store = forms.ModelChoiceField(queryset=Store.objects.all()) class Meta: model = Product fields = ('store', 'name', 'price', 'image',) widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name of your product'}), 'price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Price of your product'}), 'image': forms.FileInput(attrs={'class': 'form-control'}), } In my views.py file, I have tried different stuff, but nothing worked, so I keep it there so you know what I have tried. views.py from django.shortcuts import render, redirect from django.urls.base import reverse from django.contrib.auth.models import User, Group from django.contrib.auth import authenticate, login from .models import Product, Store from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView class AddProductView(CreateView): model = Product form_class = AddProductForm template_name = 'app1/add-product.html' # def get_initial(self): # if Store.objects.filter(owner=self.request.user).exists(): # initial = super(AddProductView, self).get_initial() # initial['store'] = … -
How to get parent fields in a self related model in django?
I created a self-related model called Category like this: class Category(models.Model): name = models.CharField(max_length=250) parent = models.ForeignKey('self', verbose_name=_('parent'), related_name='childs', null=True, blank=True, on_delete=models.CASCADE) and I have a Post model that has a many-to-many relation with this model. I want to get all categories for a post that are parent categories, not child categories that mean something like this: post_one = Post.objects.get(id=1) parent_categories = post_one.category.filter(parent__isnull=True) But it doesn't work for me and always returns an empty result. How I can do this? -
FormMixin on DetailView Django
I wanted to have a comment section in the same page as in my DetailView so I decided to use the FormMixin as a way to be able to add comments. It's not raising any errors but the submitted comments seem to be going nowhere and it's not showing up in the admin site also. models.py from django.db import models from django.utils import timezone from django.urls import reverse from embed_video.fields import EmbedVideoField from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() video = EmbedVideoField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class PostComment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete = models.CASCADE) author = models.ForeignKey(User, on_delete = models.CASCADE) date_posted = models.DateTimeField(default = timezone.now) body = models.TextField() def __str__(self): return f'{self.post} - {self.author}' forms.py from django import forms from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Fieldset, Button, Layout, Div, ButtonHolder, Field, Reset from .models import Post, PostComment from crispy_forms.bootstrap import FormActions from django.urls import reverse class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.fields['body'].required = True self.fields['body'].label = False self.helper.layout = Layout( Field('body', … -
While proceeding to pay , the invalid amount popup appears in razorpay
Below I've attached an image which occurs when I click on Proceed To Pay. When the order is being created, it successfully creates razorpay_order_id and also prints the order_amount, but it doesn't pushes that amount to the gateway. If no razorpay_order_id has been newly created then it will create a razorpay_order_id and print the values of order(i.e. username), order_id, x and order_amount, else it only prints the value of order and execute the else block. But after executing any of the blocks, the order_amount is not been pushed to the razorpay payment process. Below are the python code for the Razorpay Integration: Views.py- @login_required def payment(request): add = Address.objects.filter(default=True) order = Order.objects.filter(user=request.user).first() print(order) client = razorpay.Client(auth=("ABC", "XYZ")) # Creating a Razorpay order if no order_id has been created if order.razorpay_order_id is None: order_id = order.order_id print(order_id) #prints the order_id x = order.get_total() print(x) #prints the total amount order_amount = int(x * 100) print(order_amount) #prints the total amount in paise order_currency = 'INR' order_receipt = 'Rcpt' notes = {'Shipping address': 'LMN, OPQ'} # OPTIONAL # data = {"amount": order_amount, "currency": order_currency, "receipt": order_receipt, "payment_capture": '1', "notes": notes} # razorpay_order = client.order.create(data) razorpay_order = client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, payment_capture=1, notes=notes) # Razorpay order … -
ModuleNotFoundError: No module named 'django.shortcuts'
I am creating a bookstore website using Django framework and this error can't be resolved after various stackoverflow previous solutions. enter image description here Apart from this I also have 2 venv config files in env directory. what to do about them. should one needs to be deleted? enter image description here -
python bcp insert without knowing order of columns
I'm using Django and bcp to insert huge amounts of data into my database. As of now, I have a dataframe which I convert to a CSV using to_csv() which my BCP command then reads and uploads to DB. However, for it to upload correctly, I have to have the file in the exact order as columns in DB and as of now I'm doing it manually like this: data = data[['id', 'data_date', 'data', 'created_at', 'modified_at', 'signal_id']] I tried using the following command to get the order of columns from the table as I learned from this answer but it didn't seem to return anything. Process just got stuck bcp_string_get_col_names = "bcp \"DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name from {}.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='{}'; select @colnames;\" queryout HeadersOnly.csv -S {} -U {} -P {}".format(database, table, host, user, password) status = subprocess.run(bcp_string_get_col_names, stdout=subprocess.PIPE) The command which uploads my data to database looks like this: bcp_string_upload = 'bcp {} in {} -S {} -d {} -U {} -P {} -t "{}" -c -F {} -b 20000'.format(table, file, host, database, user, password, sep, row_start) status = subprocess.run(bcp_string_upload, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) I would really appreciate if either you could tell me how … -
Add twilio webhooks dynamically from a multi-tenant django application with subdomains for twiml
I have tested twilio's twiML api for sending and receiving text messages in application and it worked well. However I had to ngrok the specific test sub-domain I was testing from as the receiving Webhook on Twilio panel. In real use case, because it's a multi-tenant application, this needs to be dynamic, not just a single Webhook endpoint e.g www.first.mysite.com/sms-chat-bot, www.second.mysite.com/sms-chat-bot etc etc. The question is, how do I achieve this either via twiml or twilio rest api (couldn't find a single documentation on this, as everything seems to favour Webhooks). -
Get reverse relation in Django Serializer
Models: class MaterialRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') linked = models.CharField(max_length=50, default="-", blank=True, null=True) flows = models.ManyToManyField(MaterialRequestFlow) is_allocated = models.BooleanField(default=False) delivery_required_on = models.DateTimeField(default=datetime.now) raised_by = models.CharField(max_length=1000, default="__________", blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE) is_delivered = models.BooleanField(default=False) document_available = models.BooleanField(default=False) Now to show my Material Request table I am doing something like this: class MREmpTableAPIView(APIView): permission_classes = (permissions.IsAuthenticated, MRViewPermission) def get(self, request, *args, **kwargs): items = MaterialRequest.objects.all().order_by('-id') serializer = EMaterialRequestTableListSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) Where I get all the detaila of Material Requests but I also want to show the transaction_no of the linked Allotment in Material Request Table. How do I do that? -
Pass ImageURL as an argument to call a function in Django rest framework
want to pass the image url as an argument to a function (image.py), when I upload an image as a POST Method. My api/models.py from os import name from django.db import models from numpy import mod # Create your models here. # Create your models here. class ImageA(models.Model): name = models.CharField(max_length=255) image = models.ImageField() My api/serializers.py: from django.db.models import fields from rest_framework import serializers from .models import ImageA class ImageASerializer(serializers.ModelSerializer): class Meta: model = ImageA fields = ('id','name', 'image') My Response after I upload the Image(POST Method): HTTP 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 19, "name": "qqqqqqq", "image": "http://127.0.0.1:8000/media/pan2.png" } I want to pass "image": "http://127.0.0.1:8000/media/pan2.png", so that image(image_path_here) is called. My current views.py: class ImageAView(generics.ListCreateAPIView): queryset = ImageA.objects.all() serializer_class = ImageASerializer class ImageADetails(generics.RetrieveUpdateDestroyAPIView): queryset = ImageA.objects.all() serializer_class = ImageASerializer -
How to handle token in dajngo rest when user close the browser?
I'm new to the Django rest framework and I'm tyring token auth of Django rest but I have no idea how to handle token when user directly close the browser without logout, In such a case what will be the standard way? Also, I want to implement if a user is already logged in then redirect to the dashboard how to implement this? My views are as follow. class LoginTemplateClass(TemplateView): template_name = 'index.html' class LoginAPI(viewsets.ModelViewSet): serializer_class = LoginSerializer def post(self,request): try: serializer = self.serializer_class(data=request.data,context={'request': request}) if serializer.is_valid(): user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response(token.key,status = 200) return Response(serializer.errors,status = 400) except Exception as e: return Response({},status = 500) -
How to make post call if I have JSON in django
I am working on django project where I have JSON data for Post call request to trigger the post function. here's my view def jiranewsprint(request): default_node = list(Lookup.objects.values('Name').filter(Type = 'JENKINS_NODES', default_node = 'Default').values())[0].get('Name') print('default_node',default_node) jextract= request.body print(jextract) jextract = json.loads(jextract) jiraSprint = jextract["issue"]["fields"]["customfield_10200"] print('jiraSprint',jiraSprint) sandboxcall= { "id": 18, "robot": "Sandbox_Creation_Bot", "param": [ { "node": default_node, "Username": "hello", "Password": "hello@21", "WebsiteURL": "https//:google.com", "SandboxName": jiraSprint+'_sandbox', "Publishable": "Yes", "Description": "testing", "Tools": "Application Composer" } ] } print(sandboxcall) return HttpResponse(status=200) Need help that how make post call with the json request I have ? -
Have example or data about GAN Model web publishing?
i wonder GAN Model Web Publishing. to be more specific, I want to distribute the model I learned from Tensorflow to web. Afterwards, when the user gives the input image, it is desired to derive the output image through the model. so i search Github, google but I couldn't find a satisfactory result. Most example about image classification.. Just in case, have example or data about my question...? -
Passing variable values from one route to another in a token authenticated flask application
I have a flask token authenticated application implemented by flask jwt extended. Code import random import os from flask import Flask, jsonify, request, session from flask_cors import CORS from flask_jwt_extended import create_access_token from flask_jwt_extended import JWTManager import json app = Flask(__name__) app.config["JWT_SECRET_KEY"] = "some secret key" jwt = JWTManager(app) CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' secret_email = "xxxx@gmail.com" secret_pass = "password" @app.route("/") def home(): return jsonify({"msg":"Hello, World!"}) @app.route("/login", methods=["POST"]) def login(): email = request.json.get("email", None) password = request.json.get("password", None) if email != secret_email or password != secret_pass: return jsonify({"msg": "Bad username or password"}), 401 access_token = create_access_token(identity=email) return jsonify(access_token=access_token) @app.route("/configs") def configs(): a = random.randint(10,30) b = random.randint(1,5) summ = a+b return jsonify({"a":a,"b":b}) @app.route("/sumcollect") def sumcollect(): return jsonify({"sum is":summ}) if __name__ == "__main__": app.run(debug=False) The summ variable in route /configs needs to be accessed in route /sumcollect . I tried with session variables. But the token authentication and session variables are not working together. Is there any way to pass the variables in this case. Note: Just added django tag for this in case for them to look at to have a solution. -
Convert string to html in django
I have a Django project but I need to convert a string in Django to HTML I try BeautifulSoup but I fail. How can I convert it? Here is the code of views.py and HTML f= markdown2.markdown(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "fileContent": f }) HTML: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} {{ description | safe }} {{fileContent}} {% endblock %} -
I don't understand how to use the django 3rd party library djangorestframework-api-key
I'm trying to set up an authentication that requires a user to send an API key and secret in the header of a request before being able to create the data. I'm using djangorestframework-api-key found here: https://florimondmanca.github.io/djangorestframework-api-key/guide/. However, I'm struggling with how to use it properly. My models.py looks something like this: class UserTier(Base): key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) api_key = models.CharField(max_length=1000, null=True, blank=True) tiers = models.ManyToManyField(Tier) start_date = models.DateTimeField() end_date = models.DateTimeField() def save(self, *args, **kwargs): api_key, self.api_key = APIKey.objects.create_key(name=self.user.key) super(UserTier, self).save(*args, **kwargs) Here is an example API endpoint view that I have made: class MLBTeams(ListAPIView): serializer_class = MLBTeamSerializer queryset = Team.objects.all() permission_classes = [HasAPIKey] I ran this to get the API Key and passed it through the header in postman: print(APIKey.objects.get_from_key('V9Js7vY7.s1xiK0pWtzbp1ZQA3e2NrT95qhUk1kRV')) #key stored in the UserTier object However, I'm still getting the following error: { "detail": "Authentication credentials were not provided." } Does anybody know how to use this library properly? -
Gitlab CD Django app on DigitalOcean droplet return permission denied for SSH
I'm trying to implement CD for my containerized(Docker, nginx) Django app using gitlab on DigitalOcean droplet. I have created a pair of SSH keys and add the public key to DigitalOcean platform. I can login to my droplet using that SSH key. Now, I have added the private key as the environment variable at gitlab as: $PRIVATE_KEY , so now when I run the deployment it return the permission denied error. Here's my : .gitlab-ci.yml: image: name: docker/compose:1.29.2 entrypoint: [""] services: - docker:dind stages: - build - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/web:web - export NGINX_IMAGE=$IMAGE/nginx:nginx - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker pull $IMAGE/web:web || true - docker pull $IMAGE/nginx:nginx || true - docker-compose -f docker-compose.prod.yml build - docker push $IMAGE/web:web - docker push $IMAGE/nginx:nginx deploy: stage: deploy script: - mkdir -p ~/.ssh - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 - cat ~/.ssh/id_ed25519 - chmod 700 ~/.ssh/id_ed25519 - eval "$(ssh-agent -s)" - ssh-add ~/.ssh/id_ed25519 - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts - chmod +x ./deploy.sh - scp -o StrictHostKeyChecking=no -r ./.env …