Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
css and js is not working in blog detail page wagtail
enter image description here CSS and JS is not working in blog detail page -
Django to heroku deployment issue
While attempting to deploy my django project, I am running into a strange error: There is a dependency that I didn't use, and uninstalled, that is still trying to load with requirements.txt during the build. I have since uninstalled all of the dependencies, removed it from requirements.txt, run makemigrations and migrate, and yet it still tries to load it, which crashes the deployment. PyGObject is the dependency. workflow: Procfile - web: gunicorn solarsystem.wsgi ran - pip3 freeze > requirements.txt the dependency is no longer showing after uninstalling it. however during build: Collecting PyGObject remote: Downloading PyGObject-3.42.0.tar.gz (716 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing wheel metadata: started remote: Preparing wheel metadata: finished with status 'done' ... ERROR: Failed building wheel for PyGObject ... ERROR: Could not build wheels for PyGObject which use PEP 517 and cannot be installed directly and here is my requirements.txt: asgiref==3.3.4 autopep8==1.5.7 boto3==1.17.108 botocore==1.20.108 click==8.0.1 cm-rgb==0.3.6 cycler==0.10.0 dj-database-url==0.5.0 Django==3.2.3 django-appconf==1.0.4 django-compressor==2.2 django-heroku==0.3.1 django-libsass==0.9 django-material==1.9.0 django-materializecss-form==1.1.17 django-on-heroku==1.1.2 django-sass-processor==1.0.1 gunicorn==20.1.0 hidapi==0.10.1 Jinja2==3.0.1 jmespath==0.10.0 kiwisolver==1.3.1 libsass==0.21.0 MarkupSafe==2.0.1 matplotlib==3.4.3 mpld3==0.5.5 numpy==1.21.2 Pillow==8.3.1 psutil==5.8.0 psycopg2==2.9.1 … -
How to add event for checked row
I'm using django and it's printing a table. Currently, using the latest jquery script, clicking the Transfer Selected Rows button moves the selected rows to the second table. But I'm managing a server and I want the second table to be saved and visible to users. Should I create another class model to store the second table? Alternatively, when moving to the second table for the checked row, I would like to change the select column to name column and add the user name currently logged in in bulk. Another method I thought of is to apply a different color to each checked row and save it to the server. That is, I have 2 teachers and I want to assign them to students. Help.. <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">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><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Transfer Selected … -
Unable to save in different database in django?
I am trying to save data into different database but its not saving and not giving any errors. settings.py I have two database mypage and ringi. mypage is set to default. DATABASE_ROUTERS = ['app_kanri.router.myrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } models.py class Approvallog(models.Model): # id = models.IntegerField(primary_key=True) cat_name = models.CharField(max_length=100,default=None,blank=True) cat_id = models.IntegerField(default=None,blank=True) cat_subid = models.IntegerField(default=None,blank=True) status = models.IntegerField(default=None,blank=True) user = models.CharField(max_length=100,default=None,blank=True) app_root = models.IntegerField(default=None,blank=True) app_step = models.IntegerField(default=None,blank=True) comment = models.TextField(default=None,blank=True) created = models.DateTimeField(default=None,blank=True) modified = models.DateTimeField(default=None,blank=True) class Meta: app_label = 'ringi' db_table = "approvallogs" router.py class myrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ringi' or \ obj2._meta.app_label == 'ringi': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ringi': return db == 'ringi_db' return None This is how I am saving Appr_log = Approvallog() Appr_log.cat_name=str(data2['cat_name']) Appr_log.cat_id=data2['cat_id'] Appr_log.cat_subid=data2['cat_subid'] Appr_log.status=data2['status'] Appr_log.user=data2['user'] Appr_log.save(using="ringi_db") I tried to print(Appr_log.save(using="ringi_db")) and … -
I'm doing a get request with fetch in a django app, it works in development but not in production and cannot get the problem
The application is deployed on heroku. When I run the program on my machine it works fine, but in production I get different errors. In Google Chrome in the console I get the following error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 In Firefox the error in the console is as follows Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data I received the following report from Sentry: Exception gaierror: [Errno 11001] getaddrinfo failed File "urllib3\connection.py", line 169, in _new_conn conn = connection.create_connection( File "urllib3\util\connection.py", line 73, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "socket.py", line 953, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed File "urllib3\connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "urllib3\connection.py", line 353, in connect conn = self._new_conn() File "urllib3\connection.py", line 181, in _new_conn raise NewConnectionError( MaxRetryError: HTTPSConnectionPool(host='www.wordreference.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno … -
How can i make a custom user model in django without using username field?
I am working on building a project and for this, i need to create a custom user model, since the one that Django comes with isn't suitable for my situation, so whenever i use the AbstractBaseUser, I am forced to use the username field, which i really don't need in my case. how can I create a custom user model without using the username field and thank you -
Upload file from Django app to IBM Cloud Object Storage
I'm trying to connect a django app to IBM COS and having trouble. I'm capturing user video and want to save the file to IBM COS and the user info to Postgres also hosted on IBM. I'm able to connect from both the terminal and my app to IBM COS and move files around, but am having trouble getting the default storage configured properly. I'm using django-storages, trying to adapt the AWS configurations for IBM but I must be missing something. This code will save the file to IBM COS, but makes no entries in the DB. The problem may be in the configuration? Also, I am not able to manually upload a file form the django admin panel - I get a similar traceback. Thanks in advance for any help. settings.py # IBM STORAGE CONFIG IBM_API_KEY_ID = 'IBM_API_KEY_ID' IAM_SERVICE_ID = 'IAM_SERVICE_ID' ENDPOINT = 'https://s3.us-east.cloud-object-storage.appdomain.cloud' IBM_AUTH_ENDPOINT = 'https://iam.bluemix.net/oidc/token' SERVICE_INSTANCE_ID = 'SERVICE_INSTANCE_ID' IBM_STORAGE_BUCKET_NAME = 'cloud-object-storage-3u-cos-standard-77w' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' models.py class Video(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) videofilename=models.CharField(max_length=500) videofile=models.FileField(upload_to="video/", null=True, verbose_name="") def __str__(self): return str(self.videofile) views.py class upload_to_ibm_auto(LoginRequiredMixin, CreateView): model = Video context_object_name = 'Videos' form_class = VideoForm template_name = 'app_video/upload_to_ibm_auto.html' success_url …