Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install and point to Python GDAL library on App Engine (Standard)?
Django is firing this error locally: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Here's an example of how the path should look in settings: GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300' Now this is an easy, well documented fix locally, but we're quite far along with App Engine Standard on GCP (Python 3). There's a GDAL package that seems to be installable by pip but it also seems there's also native extensions/headers required. How can I: how do I install GDAL in a specific directory in app engine? where do I know where App Engine will put it/put it somewhere myself? Note: Willing to do any kind of workaround like host it remotely (probably not allowed) or even try a different library for lat-long distance filtering. Though for the latter it must accept and return a queryset via queryset.filter() in Django so I doubt there are other Django options. Perhaps running PSQL query directly on a dataset? The only solution I found and examined were vendor packages and lib. But it looks like this is no longer an option (https://cloud.google.com/appengine/docs/legacy/standard/python/tools/using-libraries-python-27#vendoring) for … -
Groupby and count number of children where each child has more than a specific number of children itself
I have three models, Business, Employee, and Client, where each business can have many employees and each employee can have many clients: class Business(models.Model): name = models.CharField(max_length=128) menu = models.CharField(max_length=128, default="") slogan = models.CharField(max_length=128, default="") slug = models.CharField(max_length=128, default="") class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) business = models.ForeignKey( Business, related_name="employees", on_delete=models.CASCADE ) class Client(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) employee = models.ForeignKey( Employee, related_name="clients", on_delete=models.CASCADE ) A sample data: Business.objects.create(name="first company") Business.objects.create(name="second company") Business.objects.create(name="third company") Employee.objects.create(first_name="f1", last_name="l1", business_id=1) Employee.objects.create(first_name="f2", last_name="l2", business_id=1) Employee.objects.create(first_name="f3", last_name="l3", business_id=2) Employee.objects.create(first_name="f4", last_name="l4", business_id=3) Employee.objects.create(first_name="f5", last_name="l5", business_id=3) Employee.objects.create(first_name="f6", last_name="l6", business_id=3) Client.objects.create(first_name="cf1", last_name="cl1", employee_id=1) Client.objects.create(first_name="cf2", last_name="cl2", employee_id=1) Client.objects.create(first_name="cf3", last_name="cl3", employee_id=2) Client.objects.create(first_name="cf4", last_name="cl4", employee_id=2) Client.objects.create(first_name="cf5", last_name="cl5", employee_id=3) Client.objects.create(first_name="cf6", last_name="cl6", employee_id=3) Client.objects.create(first_name="cf7", last_name="cl7", employee_id=4) Client.objects.create(first_name="cf8", last_name="cl8", employee_id=5) Client.objects.create(first_name="cf9", last_name="cl9", employee_id=6) If I wanted to see how many employees each business has, I could run a query like this: Business.objects.annotate( employee_count=Count("employees") ).values( "name", "employee_count" ).order_by("-employee_count") <QuerySet [ {'name': 'third company', 'employee_count': 3}, {'name': 'first company', 'employee_count': 2}, {'name': 'second company', 'employee_count': 1} ]> Similarly, if I wanted to see how many clients each employee has, I could run a query like this: Employee.objects.annotate( client_count=Count("clients") ).values( "first_name", "client_count" ).order_by("-client_count") <QuerySet [ {'first_name': 'f1', 'client_count': 2}, {'first_name': 'f2', 'client_count': 2}, … -
autocomplete form in django
i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table views.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def get_employee(request): if is_ajax(request=request): q = request.GET.get('term', '') places = InfoTrabajadores.objects.filter(documento__icontains=q) results = [] for pl in places: place_json = {} place_json['label'] = pl.state results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) and the jquery $(document).ready(function() { async function getCities(event, ui) { let url = '{% url ' / api / get_employees / ' %}'; let url = 'http://127.0.0.1:8000/api/get_employees/'; let results = await fetch(url); let data = await results.json(); return data; }; async function AutoCompleteSelectHandler(event, ui) { let zipCode = await getCities(); $('#nombre').val(nombre[ui.item.value]); $('#num_emergencia').val(num_emergencia[ui.item.value]); $('#prov_salud').val(prov_salud[ui.item.value]); $('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]); $('#rh').val(rh[ui.item.value]); }; $("#autoSuggest").autocomplete({ source: "{% url 'invitados' %}", select: function(event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); -
How to define and render Django formset for registeting hours spent on a project each day during a month?
I building a Django site where users can register their time spent working on a particular project (Time Report). In the future Time reports will be subject to approval process and possibly sources for calculating invoices to clients, but right now I struggle in setting it up in Django. I want Time Reports to hold multiple project lines and each project line should have as many input fields as many days is in a particular month . This will allow user to register number of hours spent each day on all projects they work on. In addition each project can be presented in more than line (so user can register different tasks within the project separately, e.g. hours spent on project planning vs time spent on development). Projects are defined separately (separate model). I believe that I need following models to support the requirements: from django.db import models class TimeReport(models.Model): employee = models.ForeignKey('employees.Employee', on_delete=models.CASCADE) start_date = models.DateField() #to calculate Time Report month status = models.CharField(max_length=20, default='draft') class ProjectLine(models.Model): time_report = models.ForeignKey('TimeReport', on_delete=models.CASCADE) project = models.ForeignKey('projects.Project', on_delete=models.CASCADE) comment = models.TextField(blank=True, null=True) class ProjectLineDay(models.Model): project_line = models.ForeignKey(ProjectLine, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField(max_digits=2, decimal_places=0) I want to achieve something like this … -
NOT NULL constraint failed: store_customer.first_name
NOT NULL constraint failed: store_customer.first_name Request Method: GET Request URL: http://127.0.0.1:8000/signup/ Django Version: 4.1.4 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: store_customer.first_name models.py class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=50) email = models.EmailField(max_length=100) password = models.CharField(max_length=500) def register(self): self.save() def __str__(self): return self.first_name views.py def signup(request): if request == 'GET': return render(request, 'signup.html') else: first_name = request.POST.get('firstname') last_name = request.POST.get('lastname') phone = request.POST.get('phone') email = request.POST.get('email') password = request.POST.get('password') customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password) customer.register() # return HttpResponse( 'signup successful' ) return render(request, 'signup.html') -
How to query model list from one app to another django?
I am facing an issue in django. I have two apps in my project booking and Home, in the booking I have a model called Clinics that has data related to clinics in the home app I am creating a template that shows clinics list I used {% if clinics_list%} to query the data into the model but nothing shows up notes: 1.clinics list has data 2.I imported the clinics model into home app in models.py 3.no issues were detected when running check Tried to create new model(test) in home app that inherit the data from clinics and used {% if test_list %} -
SessionId inside the cookie header slows down request (Django)
I'm learning how to use django sessions and caching. I noticed that once I login, a sessionId is included in the cookie header. I'm using the "@authentication_classes" and "@permission_classes" decorators to validate the session. I'm also using Redis to cache the session, since I dont want to hit the DB everytime. I followed the docs for the django and redis server setup. Once the user log in, the session is written in the cache. The problem is that, even tho the session is inside the cache, the database is hit with each request and it slows down the response time to around 300ms. This is the api I'm using for testing. It does nothing, but it takes 300 ms and it does hit the DB each time I call it. I'm using "never_cache" because I dont want the entire response to be cached. @api_view(["GET"]) @authentication_classes ([SessionAuthentication]) @permission_classes([IsAuthenticated]) @never_cache def test(request, username): return JsonResponse("", safe=False) this is the request I'm making: request If I remove the session autentication decorators, a SessionId is not required anymore to access the api, but the DB is still hit and the response still takes 300ms (there is still the sessionID token inside the cookie header). … -
How to deploy a Django backend in a self-hosted PC?
I have a Django Back-end and I would like to deploy in "production" in a local PC and to be accessible for everyone on the same network. PS: the network has a proxy. How can I achieve this in a way that the server is fast and reliable, also I have some async functionality so I was reading of this integraton with uvicorn, where I was deploying in local server to test the functional views. Any suggestions are welcome, I just need a general overview of the path I should go for accomplish this :) -
OSError: /opt/anaconda3/lib/libgdal.dylib: cannot open shared object file: No such file or directory
I am using windows and installed geodjango in my pc but not too confirm how can i add the path to my django application i.e = GDAL_PATH = ?? not to confirm i have try the folder in which my gdal is installed that path but it didn't work -
How to convert a string to a datetime?
I'm trying to run a row query with objects. I have a tran_date field which is look like: '2022062519:14:47' I think because of that I'm getting this error: django.db.utils.DataError: date/time field value out of range: "2022062519:22:54" LINE 1: ...HERE merch_id = '510000022048730' and tran_date = '202206251... Here is my code: medium_prob = ProcessTransaction.objects.raw('SELECT * ' 'FROM bvb_generaltransaction ' 'WHERE merch_id = %s and tran_date = %s::DATE ' 'and probabilty >= 0.8 and alerted= false', [str(merchant.merch_id), str(merchant.tran_date)]) How can I solve that? -
how to display error messages in django in front of each textbox django
I am having an issue that i wanted to display error messages below each text-box but. Below is my code i am having an issue that how to display each message below textboxes e.g username taken in front of username. -
Django Channels equivalent code for javax.websocket
I am new to Django Channels. I am trying to replicate what is being done in this Java code using Django Channels. But I cannot figure out how to send the message JSON to the Angular frontend. The frontend has a table that will get updated throught the websocket implementation. But the recieve method doesn't seem to replicate what the onMessage method was doing. Django Channels performs a successful handshake. But that's all that happens. Java Code @ServerEndpoint("/socket/order") @ApplicationScoped public class OrderSocket { Set<Session> sessions = new HashSet<>(); @OnOpen public void onOpen(Session session) { LOG.debug("onOpen " + session.getId()); sessions.add(session); } @OnClose public void onClose(Session session) { LOG.debug("onClose " + session.getId()); sessions.remove(session); } @OnError public void onError(Session session, Throwable throwable) { LOG.debug("onError " + session.getId() + " left on error: " + throwable); sessions.remove(session); } @OnMessage public void onMessage(String message) { LOG.debug("onMessage " + message); broadcast(message); } public void broadcast(OrderDto orderDto) { Jsonb jsonb = JsonbBuilder.create(); String jsonString = jsonb.toJson(orderDto); broadcast(jsonString); } private void broadcast(String message) { sessions.forEach(s -> { LOG.debug("Message broadcasted: " + message); s.getAsyncRemote().sendObject(message, result -> { if (result.getException() != null) { LOG.error("Unable to send message: " + result.getException()); } }); }); } } Python Code consumer.py class OrderConsumer(WebsocketConsumer): … -
Images loss every time on server when run "docker-compose up --build" + Django
I had a setup docker on Django project, images are stored on server but whenever I upload changes on server and then run "docker-compose up --build" then it loss every images that I uploaded, path showing images there but I am not able to view it. I don't know want happened there. if anyone have idea what to do for that ? How to resolved this issue ? is there any things need to add in docker-compose file ? Below is my docker compose file. version: '3' volumes: web-django: web-static: services: redis: image: "redis:alpine" web: build: . image: project_web command: python manage.py runserver 0.0.0.0:8000 restart: always volumes: - web-django:/usr/src/app - web-static:/usr/src/app/mediafiles ports: - "8000:8000" depends_on: - redis celery: image: project_web command: celery -A project_name worker -l info restart: always depends_on: - web - redis celery-beat: image: citc_web command: celery -A project_name beat -l info restart: always depends_on: - web - redis I want solution of it, what i missing on above file and want to resolve it. -
How To Solve Django ValueError: :Comment.post" must be a "Software" instance
I'm getting an error over and over again when I'm displaying comments for a program. Please what is the problem I made here? I made many attempts using get , filter but the error remains the same. Other errors may appear when changing the view of comments. Please help. def download(request,slug): app = get_object_or_404 (Software,slug = slug) comments= app.comments.filter(active=True).order_by("-created") try : app = Software.objects.filter(slug = slug) except : raise Http404 new_comment = None if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post= app <<<--------------------------->>> here my error new_comment.save() else: comment_form = CommentForm() context ={ 'app' :app, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, } return render( request,'download.html',context) that's my models: class Software (models.Model): class Meta : verbose_name_plural = 'software' ordering = ['created_at'] category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="mac") category = models.CharField(max_length=150 , null=True,blank=True) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) title = models.CharField(max_length=50 , null=True) requirements = models.CharField(max_length=100 , null=True) version = models.CharField(max_length=100 , null=True) picture = models.ImageField(upload_to='img_pro' , null=True) size = models.CharField(max_length=20 , null=True) created_at = models.DateField(auto_now_add=True) auther = models.CharField(max_length=100 , null=True) download = models.URLField(null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('download', args=(self.slug,)) class Comment(models.Model): post = models.ForeignKey(Software , on_delete=models.CASCADE ,null=True, related_name='comments') name = models.CharField(max_length=80 , null=True) email = models.EmailField(max_length=200, blank=True … -
ValueError: Related model 'users.customuser' cannot be resolved
Can't figure out what to do to solve this problem. I am trying to create a custom user model but when i try to migrate it throws this error. Here is managers.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email or Phone numvber must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) Here is models.py: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.CharField(_('email or phone number'), max_length=175, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
Dynamic template rendering in Angular
Can we render template dynamically from DB? in this template, I'm going to use angular event, string interpolation and directive. Do we have any other option instead of Angular compiler?? Currently we have old process or code... -
Django. One project. Separate auth systems and templates for different apps
I have a project with the following structure: main_app accounts_app (stores CustomUser model) my_app1 users_app (inside my_app1) my_app2 users_app (inside my_app2) The reason behind separate users_app is that I want to reuse my_app1 and my_app2 in other projects. So I want them to be as separate as possible. I want to have a separate auth system (custom user model, registration, templates, login/logout redirect, etc) for each app. So for example, let's say I have my-app1 at url localhost:8000/my-app1/. This means that registration will be at /my-app1/signup/, login at /my-app1/login/ and login redirect goes to /my-app1/ I also want to use allauth on some or all apps. Questions: Does this project structure even make sense? (yes/no) Is it possible to have separate signup/sigin/etc templates for each app using allauth? (yes/no - link to doc?) I couldn't find the answer to this. How do I avoid DB conflicts with migrations when creating custom user for each app? Right now I'm inheriting from AbstractUser in each app's model.py, like so: class MainCustomUser(AbstractUser), class AppOneUser(AbstractUser), class AppTwoUser(AbstractUser) But that doesn't seem to work. Answers to these questions will serve me as guidance in the right direction, right now I sort of confused myself a … -
Send email based on form boolean value
I am trying to send email based on the form boolean value. If the Trigger_Email is True then send the mail Below is the models.py class New_Shipment(models.Model): Status_CHOICES = ( ("1", "Open"), ("2", "Close"), ) alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.') Courier_or_Freight_details = models.CharField(max_length=200, validators=[alphanumeric]) Quantity = models.IntegerField() Action_On = models.CharField(max_length=200, validators=[alphanumeric]) Status = models.CharField(max_length=300, validators=[alphanumeric], choices=Status_CHOICES) Trigger_Email = models.BooleanField(default=False) Below is my views.py def my_form1(request, new_shipment=New_Shipment): if request.method == "POST": form1 = MyForm1(request.POST) if form1.is_valid(): new_shipment = get_object_or_404(New_Shipment) elif new_shipment.Trigger_Email: subject = "New Shipment Details" message = "Hello \n New Shipment details added to the EPC\n\n Regards,\nIsmail" from_email = settings.EMAIL_HOST_USER to_list = ['toemail@gmail.com'] send_mail(subject, message, from_email, to_list, fail_silently=True) form1.save() return HttpResponse('Submitted successfully') # return redirect('/home_page/') else: form1 = MyForm1() return render(request, "authentication/New_shipment.html", {'form1': form1}) Any Kind of help will be appreciated. Thanks in advance -
django returning duplicates even though distinct() is used
I'm using django=4.1, python=3.8 & sqlite. What I want to do filter our the top five player points and unique players in a given month and present it in a template, there shouldn't be any duplicates. This is the PlayerPoint model: class PlayerPoint(models.Model): OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN')) points = models.IntegerField(null=False, default=0) operation = models.CharField( max_length=3, null=False, choices=OPERATION_CHOICES, default=OPERATION_CHOICES[2][0] ) operation_amount = models.IntegerField(null=False) operation_reason = models.CharField(null=False, max_length=1500) player = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="player_points" ) points_ts = models.DateTimeField(auto_now_add=True, null=False) And this is the player model: class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, help_text="Please ensure +251 is included" ) first_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) father_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) grandfather_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) email = models.EmailField( unique=True, help_text="please ensure that the email is correct" ) age = models.CharField(max_length=3) profile_pic = models.ImageField(upload_to='profile_pix', default='profile_pix/placeholder.jpg') joined_ts = models.DateTimeField(auto_now_add=True, null=False) username = None When I run the below query it gives me the top 5 Player Points but it's not distinct, the player_ids are duplicates. It keeps repeating the same Player. q = PlayerPoint.objects.filter(points_ts__year=2023, points_ts__month=1, points__gte=2000) x = q.order_by('-points') … -
Restricting website access by client geolocation
I need to restrict access to a website because of countries regulations. I know that Hosting providers or CDNs/Webservers like Cloudflare or NGINX can do that for me and is probably the best approach (?) but I think only if the website needs to scale and since it has small expected traffic I'd like to just implement it myself for the start. This question is not about how to get the users IP or how to use geolocation APIs with that IP. It is about how to design the backend to deny or grant access to the website for the clients. Do I need to do it on every request to the server ? If yes should I just write middleware that rejects the request if it is a blocked coutry or put that logic somewhere else ? Or can I do it once and then just "remember" it somehow for that client (how reliable would that be/ could that be abused ?). I just dont want to build a super stupid design where I affect the performance of the backend just for a simple task like that. Thank you in advance. -
How can i access current session data outside django view function?
I am using SessionStore object to store session data, how can i get current session data from Session table without using pk as we dont know pk of record stored in table. Here is the code ldap.py from django.contrib.sessions.backends.db import SessionStore s = SessionStore() class LDAPPBackend(ModelBackend): def authenticate(self, *args, **kwargs): **s['memberOf']** = "Star Group" #**setting session** s.create() serializer.py from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from django.contrib.sessions.models import Session **s = Session.objects.get(pk="")** #**how can i know current logged in user session pk???** class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer): def validate(self, attrs): data['attr'] = attrs **data['memberOf'] = s** # **How can i get current session data here??** return data How can i achieve this??? -
How to serve thumbnail image instead of full image on the articles listing page in Django?
I made a django powered website here it is https://www.endustri.io When you look the frontpage i serve the blog post feautered image in original size. And it causes the increase loading time. So i wanna serve 300x180 pixels the featured images of the posts. How can i make automatically 300x180 pixels images from my original images and how can i serve these images on the frontpage. When i looked the media file, i wanna see two images, one of is original and other image is 300x180 pixels. Here is my codes... views.py def frontpage(request): posts = Post.objects.order_by('-id') most = Post.objects.order_by('-num_reads')[:10] kat = Category.objects.all() f = Firma.objects.all().order_by('-id')[:15] p = Paginator(posts, 10) page = request.GET.get('page') sayfalar = p.get_page(page) context = { 'posts': posts, 'most': most, 'kat': kat, 'sayfalar': sayfalar, 'f': f, } return render(request, 'blog/frontpage.html', context) models.py class Post(models.Model): category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) intro = models.TextField() body = tinymce_models.HTMLField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/") date_added = models.DateTimeField(auto_now_add=True) num_reads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) and frontpage.html {% for post in sayfalar %} <div class="card mb-3" style="max-width: 75%px;"> <div class="row g-0"> <div class="col-md-4"> <img … -
How to apply permissions on perform_create in ViewSet DRF
This is my View Set: class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if self.request.user.is_superuser: return self.serializer_class return serializers.MyUserSerializer def perform_create(self, serializer): employee = models.Employee.objects.get(user=self.request.user) serializer.save(employee=employee) I want to apply permission before perform_create, this perform_create() should only be called if a currently logged in user is not a super user. If a currently logged in user is a superuser, default perform_create function should be called. How to do that? -
Refused to apply style from '<URL>' because its MIME type ('text/html') pythonanywhere
Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. i dont have any problem in vscode but when i hosted into pythonanywhere i cant even login into admin panel and the css from admin panel is not working -
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django. I have tried to Integrate the subscription-based button as per the PayPal guidlines. Screenshot is attached for same. But after clicking on either button screen is blank, and nothing happens, screenshot is attached for the same. Here is my code for button integration. <div id="paypal-button-container-P-789654"></div> <script src="https://www.paypal.com/sdk/js?client-id=123456&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-789654' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-789654'); // Renders the PayPal button </script>