Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URLs management between React and Django
I have a Django application with following URLs patterns: urlpatterns = [ path('', include('tsangom.urls')), path('admin/', admin.site.urls), path(API_ROOT, include('tsangod.urls')), path('app/', include('tsangof.urls')), path('accounts/', include('django.contrib.auth.urls')), ] The /app path is served by a React app with URLs managed by a React Router. When I navigate inside the React app, i.e. by clicking on menus, everything is fine. I stay in the React App. However, if I enter a URL in the browser like /app/view, then Django is taking over URLs management and not able to route to the appropriate URL in React Router... this is normal. However, my question is what would be your recommendation to overcome this issue? How can I define the URLs in Django to handshake with the React App at the requested URL? Should I also modify the React App for that? I would prefer avoiding to define again the URLs of the React Router inside Django. -
dry_yasg example on request_body
So I use dry_yasg library to produce swagger schema. Is any way to give request_body with example json? It will make anyone can copy-paste example request body with minimal edit. My code right now: @swagger_auto_schema(operation_summary='Onboarding', operation_description='Onboarding new merchant', security=[{'Bearer': []}], request_body=serializers.OnboardingSerializer, responses={201: openapi.Response( schema=serializers.OnboardingResponseSuccessSerializer, description='Created', examples=swagger_example('hedwig_proxy/v2', '201_created')), 403: openapi.Response( schema=serializers.OnboardingResponseErrorSerializer, description='Forbidden', examples=swagger_example('hedwig_proxy/v2', '403_forbidden')), 409: openapi.Response( schema=serializers.OnboardingResponseErrorSerializer, description='Conflict', examples=swagger_example('hedwig_proxy/v2', '409_conflict')), 422: openapi.Response( schema=serializers.OnboardingResponseErrorSerializer, description='Unprocessable Entity', examples=swagger_example('hedwig_proxy/v2', '422_validation')), 500: openapi.Response( schema=serializers.OnboardingResponseErrorSerializer, description='Internal Server Error', examples=swagger_example('hedwig_proxy/v2', '500_internal_server')) }) -
Django autocomplete_fields for multiple fields in same form
This are my models: class Person(models.Model): first_name = models.CharField('Name', max_length=200) family_name = models.ForeignKey(Family, on_delete=models.PROTECT) gender_is_male = models.BooleanField(default=True) class Child(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True) father = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='father_of', limit_choices_to={'gender_is_male': True}) mother = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='mother_of', limit_choices_to={'gender_is_male': False}) In my admin I have the following: class ChildForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChildForm, self).__init__(*args, **kwargs) self.fields['person'].queryset = Person.objects.filter( Q(child__isnull=True) | Q(child=self.instance) ) self.fields['father'].queryset = Person.objects.filter(husband_of__isnull=False).distinct() self.fields['mother'].queryset = Person.objects.filter(wife_of__isnull=False).distinct() class ChildAdmin(admin.ModelAdmin): form = ChildForm list_per_page=50 search_fields=('person__first_name','person__family_name__family_name') Separate querysets looking up the same Person table provide the option lists for the ChildForm in Django Admin. When the querysets got bigger, I tried to use the 'autocomplete_fields' option: In PersonAdmin I added: search_fields=('first_name','family_name__family_name') In ChildAdmin I added: autocomplete_fields = ['person', 'father', 'mother'] The autocomplete function is working OK, but now, the option lists for all the three autocomplete fields are the same, and has all Persons. This appears to run contrary to my motive of having the autocompletes, viz. to limit the queryset sizes. For eg. why should the options for person contain those who are already children? How can the lists be limited for each of the fields according to the querysets in ChildForm? -
No images on heroku after deployment (django) (using AWS)
I deployed my app on heroku and instead of letting collect images from my system folder, I used AWS's S3 bucket. None of the images are displayed nor the background image. Even the django admin page is displayed with only username and password fields only like a normal form with no effects. I guess there is some problem with path setting in settings.py What are changes I need to do make it work. You can have look at the current website at https://market-shaurya.herokuapp.com/ settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'gm1zyhprh9=9+4@vu*^8g30(pg*xq6e@0z1)h81hc2evd7n*^v' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['market-shaurya.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'store.apps.StoreConfig', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerce.wsgi.application' # … -
Django backend configuration to Stripe, React frontend
I have created React frontend for Stripe payment, how can I configure Django Rest Framework server ? REACT COMPONENT import React, { Fragment } from "react"; import StripeCheckout from "react-stripe-checkout"; import axios from "axios"; const StripeBtn = () => { const publishableKey = "pk_test_some key"; const onToken = token => { const body = { amount: 999, token: token }; axios .post("http://localhost:8000/payment", body) .then(response => { console.log(response); alert("Payment Success"); }) .catch(error => { console.log("Payment Error: ", error); alert("Payment Error"); }); }; return ( <StripeCheckout label="Go Premium" //Component button text name="Business LLC" //Modal Header description="Upgrade to a premium account today." panelLabel="Go Premium" //Submit button in modal amount={999} //Amount in cents $9.99 token={onToken} stripeKey={publishableKey} image="" //Pop-in header image billingAddress={false} /> ); }; export default StripeBtn; Regular Django views def charge(request): # new if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) return render(request, 'payments/charge.html') I have installed Stripe in Django and added key's in settings.py and above view is regular Django function to receive Stripe payments. I was following a tutorial but they were using express.js as backend https://medium.com/hackernoon/stripe-api-reactjs-and-express-bc446bf08301 -
No moduke name opal
When I run command opal startproject xyz it give error --- from opal.core import application ModuleNotFoundError: No module named 'opal' Failed to run: python aarm\manage.py makemigrations aarm --traceback -
Combination of Django with urllib
I have a Django Application. Now, in a particular scenario I make a POST request(/doSomeWork) from template and come to the view. Inside the view, I open an url using urllib.request.urlopen() and work on it's response. Then, finally I return back to the template. So, my view function somewhat look like, def doSomeWork(request): ------ Some Tasks Performed ------ response = urllib.request.urlopen("http://xx.yy.com/XYZ") content = response.read() ------ Do Some More Tasks -------- return HttpResponse(***) Now, the problem it creates is that, it is automatically making multiple calls to the /doSomeWork. So, the function doSomeWork(request) is being called several times. As per my idea this urlopen is somehow messing with the normal Django flow. Can anyone have any idea regarding the problem or possible wayouts ? -
Django custom view stopped working after updating to 2.2 from 1.1
Backstory: I took over a website from two guys who wanted to abandon it due to financial reasons, but their only client didn't want to change their system, so I took on the job to maintain it. I updated to Django 2.2 from 1.1 and it seemed to work flawlessly, but a specific view stopped working and returns Internal Server Error (500). I have troubleshooted for hours and found the core issue is in the ScheduleView. If I change the view to a Django premade view, it works. What do I miss? ScheduleView class class ScheduleView(TherapistRequiredMixin, SuccessMessageMixin, FormView): form_class = ScheduleForm template_name = "schedule.html" success_message = "Nya bokningstillfällen är skapade" def get_success_url(self): return reverse('schedule') def form_valid(self, form): ret = form.save() if ret: messages.error(self.request, ret) # return super(ScheduleView, self).form_invalid(form) return super().form_invalid(form) else: # return super(ScheduleView, self).form_valid(form) return super().form_valid(form) -
How does gmail android app loads external images in a mail?
I am creating a mailtracker service in python which generates a transparent pixel which the user can copy to his email and send it. Actually due to google image proxy the image is not refetched from original server every time,So I came up with a workaround where i am returning an invalid response whenever the pixel is requested from my server making gmail to refetch it everytime. Everything is working fine on gmail web app but gmail app for android shows some weird behaviour. Whenever an other email which is just above or below the email having the transparent pixel is opened my server gets a request even though the email having the pixel is not opened. I am unable to figure out why is this happening. -
Django queryset union from different models and OnetoOne keys
This is my model.py: class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return "%s %s" % (self.first_name, self.surname) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', null=True, blank=True) first_nameUnregistered = models.CharField(max_length=200, null=True, blank=True, default=None) surnameUnregistered = models.CharField(max_length=200, null=True, blank=True, default=None) # The following is important: the Profile could be linked to a user (in this case it sources the name from there) or not (in this case it sources the name from its own 'unregistered' fields.) def __str__(self): if self.user_id != None: return f"{self.user.first_name} {self.user.surname}" else: return f"{self.first_nameUnregistered} {self.surnameUnregistered}" class Ensemble(models.Model): ensemble_name = models.CharField(max_length=200) def __str__(self): return self.ensemble_name class Event(models.Model): solo_performer = models.ManyToManyField(Profile) ensemble_performer = models.ManyToManyField(Ensemble) class performanceOfWork(models.Model): solo_performer = models.ManyToManyField(Profile) ensemble_performer = models.ManyToManyField(Ensemble) I would like to output the performers (both solo and ensemble, ideally in the same table-cell) all together, coming from both Event and performanceOfWork. This is what I did so far: views.py: performances = performanceOfWork.objects.values_list('solo_performer', 'ensemble_performer') events = Event.objects.values_list('solo_performer', 'ensemble_performer') all_performances = performances.union(in_event) This works relatively well, although it outputs only the ID of the solo_performer and of the ensemble. How can I output the name linked to the def __str__(self): method? Moreover, as you can see, a Profile (solo_performer) can … -
Django:register different users to different groups
I have two types of clients to register in my system(regular and prime) and an admin to oversee all operations. How do i assign each user differently , on the registration template page ,differently into these three groups.I only want to deal with the group method for roles and authentication. Here is my theory,please help: My decorators.py def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request,*args,**kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request,*args,**kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request,*args,**kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'client': return redirect('user-page') if group == 'prime': return redirect('user-page') if group == 'admin': return view_func(request,*args,**kwargs) return wrapper_function signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Client,Prime def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') post_save.connect(client_profile, sender=User) def prime_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='prime') instance.groups.add(group) Prime.objects.create( user=instance, name=instance.username, ) print('Profile created IN PRIME!') post_save.connect(prime_profile, sender=User) views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username … -
django.core.exceptions.ImproperlyConfigured. Even though I have tried all methods of configuration I receive the same error
I am getting the error even though I have configured DJANGO_SETTINGS_MODULES accordingly. Error:django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here is my views.py: import requests from bs4 import BeautifulSoup from django.shortcuts import redirect, render from django.shortcuts import render from django.http import HttpResponse import os from models import * requests.packages.urllib3.disable_warnings() def index(request): session=request.Session() session.headers={"User-Agent":"Googlebot/2.1 (+http://www.google.com/bot.html)"} url="https://weather.com/en-IN/weather/today/l/9d531fc505eb4a93a90a7e8303ccaa22a142c9370b68391129de5019ee7adf5b" content=session.get(url,verify=False).content soup=BeautifulSoup(content,"html.parser") for hit in soup.findAll(attrs={'class':'today_nowcard-temp'}): head=hit.text summ=(hit.next_sibling.text) weather=News() weather.header=head weather.summary=summ print(head) print(summ) weather.save() return redirect("../") def news_list(request): weathers=News.objects.all() context={ 'object_list': weathers, } return render(request,'index.html',context) This is settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'th9v0%i9^#4a30t3bn*0w_1qm9ci&(8q%xd*q+&*h1amyr77j9' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'news.apps.NewsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Learn.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Learn.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'News', 'USER':'postgres', 'PASSWORD':'gateexam', 'HOST':'localhost' } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' … -
user get notification when new data insert in record
i have four model shop(user), products,customer and order customer Shop = models.ManyToManyField(Shop) name = models.CharField(max_length=100, serialize=True) Phone = models.FloatField() order Shop = models.ManyToManyField(Shop) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ManyToManyField(Products) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=1000, null=True) i want set notification where the shop , get notification of new order shop get the customer name in notification and text customer(name) have order -
Wagtail KeyError 4 at /admin/
I'm getting this error after creating a new model on a new app recently installed. This is not the first time I'm getting this error and I haven't been able to identify the problem. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.0.6 Python Version: 3.7.4 Installed Applications: ['home', 'search', 'flex', 'streams', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\wagtail\admin\urls\__init__.py", line 109, in wrapper return view_func(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\wagtail\admin\auth.py", line 188, in decorated_view return view_func(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\wagtail\admin\views\home.py", line 116, in home RecentEditsPanel(request), File "C:\ProgramData\Anaconda3\lib\site-packages\wagtail\admin\views\home.py", line 98, in __init__ pages = Page.objects.specific().in_bulk(page_keys) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\query.py", line 698, in in_bulk return {getattr(obj, field_name): obj for obj in qs} File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\ProgramData\Anaconda3\lib\site-packages\wagtail\core\query.py", line 403, … -
Django custom user passwords not being hashed
I created custom user models as so: class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email manager: class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have unique email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user I have called the user.set_password(password) in the manager, yet it is not hashing it. For this, I can't login! Here is the view that I used for the signup process: class SignupView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): data = self.request.data name = data['name'] email = data['email'] password = data['password'] password2 = data['password2'] if password == password2: if User.objects.filter(email=email).exists(): return Response({'error': 'Email already exists'}) if len(password) < 6: return Response({'error': 'Password must be more than 6 characters in length'}) user = User.objects.create(email=email, password=password, name=name) user.save() return Response({'success': 'User created successfully'}) return Response({'error': 'Passwords do not match'}) I have seen other solutions but they were related to serializers. … -
getting an MultiValueDictKeyError in making a otp varification in django
This is not my whole code. This a part of my code. It is for otp varification. Although i should use random.radient() for generating a random value. But it is for testing. Views.py if otp == 1234: user = User.objects.create_user(first_name=first_name, last_name=last_name, username=username,email=email, password=password1) user.save() messages.success(request, 'User Created') return redirect('register') print("User Created") else: messages.error(request, 'Otp does not matched') return redirect('register') register.html <input type="text" class="form-control" name="otp" placeholder="Enter OTP" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button><br> It's give MultiValueDictKeyError error. How i resolve this error ? error is in this line otp = request.POST['otp']. I think. HOW I RESOLVE THIS ? FULL TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 3.0.6 Python Version: 3.6.8 Installed Applications: ['accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Ujjwal Kar\Python\env\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('otp'), another exception occurred: File "C:\Users\Ujjwal Kar\Python\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ujjwal Kar\Python\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ujjwal Kar\Python\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ujjwal Kar\Python\Project\Doctormirror\accounts\views.py", line 43, in register otp = request.POST['otp'] … -
Search javascript in Django
I have the following javascript code to do a search (search with a button in the bar) on a page in Django 2.2, it works but it highlights it for less than 1 second, that is, it finds the word highlights it and no longer highlights it anymore As I said it does less than 1 second and the idea is that it is checked and if possible that it continues showing other coincidences like CTRL + F does in browsers. Can someone help me with a code that does work well? Thank you. <script type="text/javascript"> function FindNext () { var str = document.getElementById ("findInput").value; if (str == "") { alert ("Por favor, introduzca un texto para buscar!"); return; } if (window.find) { // Firefox, Google Chrome, Safari var found = window.find (str); if (!found) { alert ("No se encontró el siguiente texto:\n" + str); } } else { alert ("Su navegador no es compatible!"); } } </script> -
Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the reqested resource
I am trying to make a simple GET request from my angular front-end to the django back-end and I am getting the following error I have tried clearing the cache, adding trailing slash in the url as mentioned in other similar threads but nothing seems to be working. Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Angular code export class UserServiceService { private url = 'http://127.0.0.1:8000/api/v1' constructor(private httpClient: HttpClient) { } getUsers(){ return this.httpClient.get(this.url) } } showUser(){ this.userService.getUsers().subscribe(response => { console.log(response) , err=> console.log(err) }); } In the django backend I have added 'corsheaders', in installed apps ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware' ] added in the middle ware and set CORS_ORIGIN_ALLOW_ALL=True -
Django compressor and Cloudfront
I use AWS S3 to store my Django static files (using django-storages). And alternate cloudfront domain name to serve these files. I am unable to finish Django compressor via python manage.py compress. This is the error I see: CommandError: An error occurred during rendering /home/ubuntu/foldername/templates/home/xxx.html: 'https://xxx.domainname.com/static/plugins/xxx-xxx/xxx.js' isn't accessible via COMPRESS_URL ('https://s3bucket-static.s3.amazonaws.com/') and can't be compressed So I tried using the default cloudfront address, alternate domain name and S3 bucket for COMPRESS_URL: https://s3bucket-static.s3.amazonaws.com/ https://s3bucket-static.s3.amazonaws.com/static/ https://d1231232131241123.cloudfront.net/ https://d1231232131241123.cloudfront.net/static/ https://xxx.domainname.com/ https://xxx.domainname.com/static/ Only https://domainname.com/static/ don't have error. What happen is that after compress is done, the CACHE folder appear inside the local instance staticfiles folder. Which is wrong since I wanted the CACHE folder to be inside the S3 bucket. Here are my settings for django compressor: # django-compressor STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_ENABLED = True COMPRESS_OFFLINE = True if not DEBUG: COMPRESS_URL = env('COMPRESS_URL') Here are my django-storages settings: if not DEBUG: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_CLOUDFRONT_DOMAIN_NAME = env('AWS_CLOUDFRONT_DOMAIN_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_CLOUDFRONT_DOMAIN_NAME}.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' -
Django: BooleanField return 'on' instead of true?
I have a BooleanField (ran_bug) in my Randomisation models that is displayed as a checkbox. Click on the checkbox sould show 2 other fields that are not mandatory (ran_dem_nom and ran_dem_dat). My problem is that, when I 'check' the checkbox, it return 'on' instead of true. Moreover, it display the 2 fields hide at pageload but if I 'uncheck' it doesn't hide the 2 fields... And I got an error when I try to registered data: django.core.exceptions.ValidationError: ["'on' value must be either True, False, or None."] models.py class Randomisation(models.Model): ran_ide = models.AutoField(primary_key=True) pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True) ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True) bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True) ran_act = models.IntegerField("Activated line", null=True, blank=True) pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True) ran_nai = models.IntegerField("Patient birthdate (year)", blank=True) ran_sex = models.IntegerField("Sex", null=True, blank=True) ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) ran_bug = models.BooleanField("Use of alternative randomization procedure?", null=True, blank=True) ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True) # hide at pageload ran_dem_dat = models.DateField("Date of demand", null=True, blank=True) # hide at pageload ran_log = models.CharField("User", max_length=12, null=True, blank=True) … -
How to skip waiting for response from db part when saving data in Django?
The challenge is that I need to recompute all the data I have in db, after saving a new instance. The computation takes not more than 2 mins, which is fine for my problem. I have custom save method and all I need to do is to go through all items and item.save(), but as I said It takes more than 30 sec, so I have issues with 'request timeout'(using Heroku btw). Any ideas on how to deal with this? -
React JS + Stripe + Django Rest Framework
My website calculate money deductible from users in React JS frontend. I wish to integrate Stripe with React JS. I have been going through tutorials but could not figure it out. Most tutorials leads into React + Node/Express JS environments and none to Django Rest Framework. I was able to integrate successful stripe payment with pure Django template, but I wont be able to get price calculated by React frontend in doing so. I have stored Stripe key's in Django Rest Framework settings.py and installed stripe. Can anybody lead me from a beginner perspective ? I can provide below values in React 1.Value_chargable 2.Stripe publishable key 3.Link_to_secrete key -
Django model calculated field to get number of days subtracting given date with system date
Am trying to generate a column value dynamically i.e calculate "number of days a demand is open from the day demand is requested", am trying to subtract requested date from system date to get the days directly in django model but not getting output below is the django model code any help please from django.db import models from datetime import datetime Demand_Id = models.CharField(max_length=10, default='BLANK')`enter code here` Requested_Date = models.DateField(default=datetime.now) Days_Open = models.IntegerField(default=0) @property def get_Days(self): date_format = "%Y-%m-%d" sysdate = datetime.strptime(str(datetime.now().date()), date_format) odays = (sysdate - datetime.strptime((self.Requested_Date), date_format)).days return self.odays @property def save(self, *args, **kwargs): self.Days_Open = self.get_Days() super(Demand_Master, self).save(*args, **kwargs) def __str__(self): return self.Demand_Id -
Django how to set layout in the form helper
I'm trying to set the layout of my crispy form. I want to reduce the font-size of the input form. I have tried to set in my ModelForm the layout from crispy_forms.layout but in my template the result does not change. Here my forms: from ricavi.models import Ricavi from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field class RicaviForm(forms.ModelForm): class Meta: model = Ricavi fields = "__all__" def __init__(self, *args, **kwargs): super(RicaviForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( Field('__all__', css_class="form-control form-control-sm",)) Where is the error? -
error in Doctype html while adding copied html folder
When I added {% load staticfiles%} there is an error in I did exactly with what was told to do with a static folder but it still shows an error. I created a static folder in my project by Udemy and downloaded the code which was provided by the trainer and followed the instruction. and copied the main files and addedenter image description here to the enter image description herestatic folder and changed the addresses as said of images etc using Windows 10, python 3.8, and IDE is pycharm m working on ... !!