Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure webpack to generate SuiteScript compatibile modules?
I am trying to use webpack to bundle a few libraries into my typescript suitelet. Netsuite expects suitescripts to follow amd modules pattern. If I use tsc tocompile my suitelet, I get correct syntax that looks this fragment: /** * * @NApiVersion 2.x * @NScriptType Suitelet */ define(["require", "exports", "N", "N/file"], function (require, exports, N_1, file_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.onRequest = void 0; var onRequest = function (context) { //my actual code here }; exports.onRequest = onRequest; }); The poblem is that the dependencies from node_modules are not bundled. So I have tried to use webpack for this, and webpack output differs: /** * * @NApiVersion 2.x * @NScriptType Suitelet */ define(["N", "N/file"], (__WEBPACK_EXTERNAL_MODULE__N, __WEBPACK_EXTERNAL_MODULE__Nfile) => { return (() => { //... some webpack internals goes here var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "onRequest": () => (/* binding */ onRequest) // harmony imports goes here, cut for readability }); var onRequest = function onRequest(context) { //my actual code here }; … -
How to Update and Create at the same time?
I would like to create an object and once that is created I want to update an different object, not sure how to do that ? My View: class CreateUserClassQuestionRecord(UpdateAPIView, CreateAPIView): queryset = UserClassQuestionsRecord.objects.all() serializer_class = User_Class_Question_RecordSerializer permission_classes = [IsAuthenticated] def update(self, request, *args, **kwargs): user_inf =UserClassQuestionsRecord.objects.filter(user=self.request.user, question__singleclass_id =self.kwargs.get('pk')).all() for c in user_inf: if c : ClassAttempt.objects.filter(user=self.request.user, related_class_id=self.kwargs.get('pk')).update(is_first_time=False) else: pass My json : { "is_correct": "True", "xp_collected": 10, "user": 1, "question": 1, "selected_answer": 13 } The url : http://127.0.0.1:8000/api/class-record/new/13/ My Error message: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` -
How to avoid fields that has null values automatically when rendering html
I want to not to display the null value fields in template.So How can i achieve this in django?Is there any functions available to do this. -
Post form redirect not retrieving resource django
I am sending a POST request to one of my views via fetch upon clicking a form's button in javascript. The POST request resolves and reaches a redirect, but the redirect does not render the corresponding view, rather the page remains on the same view. I have configured the urls with the views, name-spaced the application and I am overall unsure where I went wrong here, particularly because the resource is indeed returned from the redirect, but just not rendered. Here is my urls.py file: from email import policy from django.urls import path,re_path from . import views app_name = 'partyupapp' urlpatterns = [ path('', views.index, name='home'), #add create_event paths path('create_event/', views.create_event, name='create_event'), path('choose_venue/', views.choose_venue, name='choose_venue'), ] Here is my views.py file: def create_event(request): if request.method == 'POST': # Create form with request data in it form = PartyEventInfoForm(request.POST) # Check all validation criteria, is_valid implemented by default via UserCreationForm if form.is_valid(): # Process data return redirect('partyupapp:choose_venue') return render(request, 'PartyUpApp/create_event.html', {'form': form}) else: form = PartyEventInfoForm() return render(request, 'PartyUpApp/create_event.html', {'form': form}) def choose_venue(request): if request.method == 'POST': own_form = ChooseOwnVenueForm(json.load(request)['data']) # Check all validation criteria, is_valid implemented by default via UserCreationForm if own_form.is_valid(): # Process data return render(request,'PartyUpApp/hire_vendors.html') return render(request,'PartyUpApp/choose_venue.html', {'own_form': … -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead. How to solve this error
shows the same error again and again...Can u please help me to solve this error url path("add-to-cart/<uid>/",add_to_cart,name="add_to_cart") html code <a href="{% url 'add_to_cart' product.uid %}?variant={{selected_size}}" class="btn btn-outline-primary"> <span class="text">Add to cart</span> <i class="fas fa-shopping-cart"></i> </a> def add_to_cart(request,uid): variant=request.GET.get('variant') product=Product.objects.get(uid=uid) user=request.user cart=Cart.objects.get_or_create(user=user, is_paid=False) cart_item=CartItems.objects.create(cart=cart,product=product) if variant: variant=request.GET.get('variant') size_variant=SizeVariant.objects.get(size_name=variant) cart_item.size_variant=size_variant cart_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFFER')) else: return HttpResponseRedirect(request.META.get('HTTP_REFFER')) shows the same error again and again...Can u please help me to solve this error -
Heroku & AWS - Error while running '$ python manage.py collectstatic --noinput'
Trying to push my code from github to Heroku after setting up S3 for statics. I am using Django. I tried different solutions I found on here, but no success. Here are the different things I did. Removed whitenoise which apparently is incompatible with django-storages; I also tested the following combowhich returned no error. python manage.py collectstatic python manage.py test I did manage to push the code to heroku with $ heroku config:set DISABLE_COLLECTSTATIC=1 but obviousy statics are not there. Finally, a post suggested to run heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput', but this only results in an error message for me C:\Program' is not recognized as an internal or external command,operable program or batch file. Code wise, I have a file called Settings, in which I have base.py, prod.py and dev.py. base.py import os from pathlib import Path import django_heroku import dj_database_url from decouple import config from dotenv import load_dotenv, find_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'django_extensions', 'storages', 'import_export', 'django.contrib.sites', 'fontawesomefree', ] 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', ] … -
Issue with Paypal in AWS lightsail deployment
I have an PayPal standard check-out implemented in my Django template. Everything work fine on my local server. When I have deployed into a AWS lightsail instance (still using sandbox account) it doesn't work anymore. Paypal pop-up, shows but doesn't load. In my lighstail instance I use nginx and gunicorn. I would appreciate any hints. my nginx code is std default server { listen 80; listen [::]:80; listen 443; listen [::]:443; server_name 13.50.59.xx; location / { include proxy_params; proxy_pass http://127.0.0.1:8000/; } location /static/ { autoindex on; alias /home/ubuntu/NewBench/staticfiles/; } } -
Ajax post data don't arrive to Django
I am developing a Django application. I am trying using jquery and ajax for a POST request but I am not able to find the error. I am basically struggling to send the data from the frontend with ajax to the server. views.py def add_new_question_feedback(request, pk): if request.headers.get('x-requested-with') == 'XMLHttpRequest': question = Question.objects.get(id=pk) feedback = QuestionFeedback( question=question, user=request.user, text=request.POST.get('feedback'), feedback_choice=request.POST.get('feedback_choice')) feedback.save() feedback = serializers.serialize('json', [feedback]) return HttpResponse(feedback, content_type='application/json') models.py class QuestionFeedback(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) text = models.TextField() feedback_choice = models.CharField( max_length=200) is_closed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) template <div class="modal-header"> <h5 class="modal-title">${gettext( "Question Feedback" )} n° ${res[0].pk}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback Type" )}</label> <select name="feedback_choice" id="feedback_choice" class="form-control" required=""> <option value="" selected="" disabled>${gettext( "Select Topic" )}</option> <option value="Wrong Question">${gettext( "Wrong Question" )}</option> <option value="Wrong Answer">${gettext( "Wrong Answer" )}</option> <option value="Other">${gettext( "Other" )}</option> </select> </div> <div class="form-group mt-3"> <label class="form-label">${gettext( "Feedback" )}</label> <textarea name="feedback" id="feedback" rows="10" class="form-control"></textarea> </div> <button type="button" class="btn btn-success mt-3" id="addFeedback"> ${gettext( "Add New Feedback" )} </button> <button type="button" class="btn btn-danger mt-3 ms-3" data-bs-dismiss="modal">${gettext( "Close" )}</button> </div> `; ajax function $("#addFeedback").on("click", function () { $.ajax({ type: "POST", url: "/quiz/add_new_question_feedback/" + questionBtnId, … -
Django IntegrityError : null value in column violates not-null constraint but there is a value in the request
I have a form that tries to add a record in a database using django. When trying to save into the database, i get the error IntegrityError: null value in column "aid" violates not-null constraint, but when I look at the request, I can clearly see a non-null value for the column 'aid' aid '10' uid '2' rid '13' action '' time '' table '' When I print the request.data inside views.py I can see all the values from the request: <QueryDict: {'aid': ['10'], 'uid': ['2'], 'rid': ['13'], 'action': [''], 'time': [''], 'table': ['']}> My question is why django cannot find the PK column> -
Current user does not show up in form from ModelForm whilst relationship has been established in Django
I have two models defined, a Test model and a User model. The Test model relates to the User model with a ForeignKey. The Test model has many different aspects to it, so I have truncated it, but I make a form of it with ModelForm. Then I call the form, and indeed all the entries show up, including a cell for User, however it shows no options or pre-selection for current user. What am I doing wrong? #User as rendered in form in browser: <select name="researcher" id="id_researcher"> <option value="" selected>---------</option> models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class User(AbstractBaseUser): is_active = models.BooleanField(default=True) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, self.last_name) return full_name.strip() @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin class Test(models.Model): researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="researcher") views.py from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views.generic.edit import CreateView, UpdateView, DeleteView from database.forms import TestForm from database.models import User, Test # Create your … -
Django Many To Many Ordering
I have two tables Subjectlist and Day. Subject list is m2m in Day. So my problem is I'm creating school timetable. So for each days different subjects to be shown, when i add subjects on each days the order of subject is same. #Models.py class SubjectList(models.Model): subject_name = models.CharField(max_length=25) def __str__(self): return self.subject_name class Day(models.Model): day_name = models.CharField(max_length=15) subject_name = models.ManyToManyField(SubjectList) class_number = models.ForeignKey(AddClass, on_delete=models.CASCADE, null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) def __str__(self): return self.class_number.class_number #Views.py class TimeTableView(APIView): def get(self, request, id): class_number = AddClass.objects.get(id=id) day = Day.objects.filter(class_number=class_number.id) print(day) serializer = DaySerializer(day, many=True) return Response(serializer.data) I want to do like this Monday - English, maths, science, Social Science Tuesady - Maths, Social Science, Englih, Math's but i get like this Monday - English, maths, science, Social Science Tuesday- English, maths, science, Social Science both are in same order even if add subjects in different order. -
Save data from Oracle to sql server using django webpage or python script
I need a short and fast method to copy oracle table to sql server because tables are too large. I have only one model of mssql. models.py class ReceiveMt_sql(models.Model): rcv_no = models.CharField(db_column='RCV_NO', max_length=30, blank=True, null=True) rcv_date = models.CharField(db_column='RCV_DATE', max_length=100, blank=True, null=True) vendor_code = models.CharField(db_column='VENDOR_CODE', max_length=12, blank=True, null=True) rcv_invoice = models.CharField(db_column='RCV_INVOICE', max_length=30, blank=True, null=True) rcv_type = models.CharField(db_column='RCV_TYPE', max_length=1, blank=True, null=True) paid_unpaid = models.CharField(db_column='PAID_UNPAID', max_length=1, blank=True, null=True) print_status = models.CharField(db_column='PRINT_STATUS', max_length=1, blank=True, null=True) user_name = models.CharField(db_column='USER_NAME', max_length=10, blank=True, null=True) u_id = models.CharField(db_column='U_ID', max_length=15, blank=True, null=True) mod_date = models.CharField(db_column='MOD_DATE', max_length=100, blank=True, null=True) width = models.CharField(db_column='WIDTH', max_length=20, blank=True, null=True) length1 = models.CharField(db_column='LENGTH1', max_length=20, blank=True, null=True) remarks = models.CharField(db_column='REMARKS', max_length=300, blank=True, null=True) chtype = models.CharField(db_column='CHTYPE', max_length=50, blank=True, null=True) general_type = models.CharField(db_column='GENERAL_TYPE', max_length=30, blank=True, null=True) action = models.CharField(db_column='ACTION', max_length=1, blank=True, null=True) gate_no = models.CharField(db_column='GATE_NO', max_length=30, blank=True, null=True) save_date = models.CharField(db_column='SAVE_DATE', max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'RECEIVE_MT' views.py class RcvMr(View): def get(self, request): cursor = connections['ORACLE'].cursor() sql = "SELECT * FROM receive_mt WHERE rcv_date>='01-SEP-22'" stmt = cursor.execute(sql) rows = [dict((cursor.description[i][0], value) for i, value in enumerate(row)) for row in cursor.fetchall()] for row in rows: #get data from row and save it to the model print(row) return render(request, 'service.html') -
Please, how do I write a try and except code for a password validation; such that each validation returns its own message to the user?
views.py The issue I have is on the signup function view. What do I write inside the except block to show an error message to the user according to the validationError given. for example: if the error is "Common Password" it should only display common password message to the user and if it is other errors, it should do the same for their independent messages to the user. Thank you in advance. from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout #from django.contrib.auth.models import User from django.core.mail import send_mail from .models import User from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator # Create your views here. def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if password: try: new = validate_password(password,password_validators=None) except: messages.error(request, ) return redirect('home') #if User.objects.filter(email=email): #messages.error(request, "E-mail already exist!") #return redirect('home') #if len(username) > 15: #messages.error(request, "Length of username too long!") #return redirect('home') #if password != password2: #messages.error(request, "Passwords do not match!") #return redirect('home') #if not password.isalnum(): #messages.error(request, "Password must be alphanumeric!") #return redirect('home') user = User.objects.create_user(username=username,first_name=fname,last_name=lname,email=email,password=password) # Welcome E-mail #subject = 'Welcome to ADi meals mobile!' #message = 'Hello {fname}, welcome to … -
Why csrf token must be put in body for POST requests and not in headers in Django Rest Framework?
I would like to know the reason why we must put the csrf token in the body for POST requests (key csrfmiddlewaretoken) and in the headers for the others (key X-CSRFToken)? -
Exclude is not working on djnago queryset
usr_all_friends_shw = Friend.objects.filter(profile_id__in = request.user.profile.friends.all()) uzr_al_cnfr_frn = FriendRequestSave.objects.filter(receiver_request=request.user.profile) sugges= Friend.objects.exclude(profile_id__in=usr_all_friends_shw).exclude(profile_id=request.user.pk) for i in uzr_al_cnfr_frn: bdhc63=Friend.objects.filter(profile_id=i.sender_request.pk) print(bdhc63) sugestion_aftr=sugges.exclude(profile_id__in=bdhc63) It does not show any error but still not excluding elements -
how to use a model field as the default for another field Django?
I want to use a field in a model as the default for a field in a different model. I try to reference the field but when I try to make migrations I'm getting a can't serialize error. Any help would be really appreciated. models.py(look at current bid under Bids) class Auctions(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=200) startingBid = models.IntegerField(max_length=6) currentBid = models.ForeignKey('Bids', on_delete = models.CASCADE, blank=True, null=True) images = models.ImageField(upload_to='images') catagory = models.CharField(max_length=50) closed = models.BooleanField(default=False) sellor = models.ForeignKey(User, models.CASCADE) class Bids(models.Model): auction = models.ForeignKey(Auctions, on_delete = models.CASCADE) currentBid = models.IntegerField(blank=True, null=True, default=Auctions.startingBid) user = models.ForeignKey(User, on_delete = models.CASCADE) error ValueError: Cannot serialize: <django.db.models.query_utils.DeferredAttribute object at 0x7fed612c7250> -
Django function view rewriting to Class View ListView problem with Tag
Im trying to rewrite my whole app from function views to class views. Right now Im struggle with Tag. This how its looks before views.py def tagged(request, slug): tag = get_object_or_404(Tag, slug=slug) articles = Article.objects.filter(tag=tag) paginator = Paginator(articles, 5) page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { "tag": tag, "page_obj": page_obj, } return render(request, "web/home.html", context) And right now Im trying rewrite it to Class View but I dont know how to use get_object_or_404 in class and then filter my model Article by tag class Tagged(ListView): model = Article paginate_by = 5 model.py class Article(models.Model): headline = models.CharField(max_length=100) article_content = models.CharField(max_length=10000) article_author = models.ForeignKey(User, on_delete=models.CASCADE) article_photos = models.URLField(blank=True, max_length=300) yt_links = models.URLField(blank=True, max_length=300) article_image_upload = models.ImageField(blank=True, upload_to="images/") slug = models.SlugField(null=True, unique=True, max_length=100) tag = TaggableManager(blank=True) likes = models.ManyToManyField(User, related_name="article_likes") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "headline": self.headline, "article_content": self.article_content, "article_author": self.article_author, "article_image_upload": self.article_image_upload, "tag": self.tag, "yt_links": self.yt_links, "likes": self.likes, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } -
Django imagefield isn't showing any photo in the template
I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work. settings.py(in main project): MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' in urls.py (main project): from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("book.urls")), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in models.py(the book app): class books(models.Model): cover = models.ImageField(upload_to='cover/co', blank=True) When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me. when I try to click on the photo in the database in admin this is shown to me: enter image description here These are the paths of the app, project and static: enter image description here I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, … -
HTML is not rendering properly in Django
I am Naive in Django and HTML and trying to build an App using django. I got to know about the website getbootstrap.com . And I was trying to render the dropdown button from there in my index.html file. The code for the Dropdown button is as follows. <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown button </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </div> And I am expecting a button like below: But I am getting the The button as follows: I want to know where I am going wrong? -
how to solve django.db.utils.NotSupportedError in django
I got an error while running the project in Django. the thing is that unfortunately i upgraded my pip , MySQL client and Django versions this is the error while running python manage.py run server in check_database_version_supported raise NotSupportedError( django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 10.1.19). -
show images that are related to django model in admin
I have a Book Model and BookImages model. Book is not related to Images directly ,instead BookImages has Book as foreign key and a Book can have many images. I want to show Book details along with images related to book in admin panel but here Book doesnt have any relation to BookImages. Instead BookImages points to Book Model. How can i show admin view with Book details and all Book Images. Below is exact model code. class Book(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length = 5000) class BookImage(models.Model): book = models.ForeignKey('Book', on_delete=models.CASCADE) image = models.ImageField(upload_to=settings.MEDIA_RELATIVE_ROOT + "/bookimages") Python version is 3.7.12 and django version is 3.2.14 -
List of arrivals, per year
I have these three models (I've summarize them): class Tourist(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Etablissement(models.Model): name = models.CharField(max_length=30) class Arrival(models.Model): tourist = models.ForeignKey(Tourist, on_delete=models.CASCADE) place = models.ForeignKey(Etablissement, on_delete=models.CASCADE) I want, for a Tourist, to have all his arrivals, per year. I've tried this: def detailTourist(request, id): touriste = Tourist.objects.get(id=id) datas = Arrival.objects.annotate(year=TruncYear('arrival_date')).values('year').annotate(total=Arrival.objects.filter(tourist=touriste)).order_by() but it give me an error: sub-select returns 19 columns - expected 1 (the arrival model has 19 field so i guest that's why it says 19. So finnaly, how can I do it please ? -
How to restrict ManyToManyField in ModelViewSet for no super users?
I have 2 models linked by a ManyToManyField relationship. class Site(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Device(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True, null=True) users = models.ManyToManyField(User, related_name='devices', blank=True) site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='devices') class Meta: verbose_name = "Device" verbose_name_plural = "Devices" ordering = ['name'] def __str__(self): return self.name My Viewset: class SiteViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SiteSerializer def get_queryset(self): if self.request.user.is_superuser: return Site.objects.all().prefetch_related("devices") else: return Site.objects.filter( devices__users=self.request.user ).prefetch_related("devices").distinct() My Serializers: class SiteDeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ('id', 'name', ) class SiteSerializer(serializers.ModelSerializer): devices = SiteDeviceSerializer(many=True, read_only=True) class Meta: model = Site fields = "__all__" If I access my view with a superuser, it works well I have all the results. Example: "results": [ { "id": 1, "devices": [ { "id": 1, "name": "test 1" }, { "id": 2, "name": "test 2" } ], "name": "Site test 1" }, { "id": 2, "devices": [ { "id": 3, "name": "Test 3" } ], "name": "Site test 2" } ] I have created another user user1 who is not a super user. I also added this user in the users of the device test 1. When I access the view with this user I … -
raise InvalidSchema(f"No connection adapters were found for {url!r}") in Django API call
I am trying to call an API in Django and I have the following code: @csrf_exempt def intasend_webhook_view(request): if request.method == "POST": payload = request.body response = requests.get(payload) intasend_body = json.loads(response) api_ref = intasend_body.get("api_ref") state = intasend_body.get("state") order = Order.objects.get(pk=api_ref) if state == "FAILED": order.payment_status == "Unpaid" order.save() elif state == "COMPLETED": order.payment_status == "Paid" order.save() return JsonResponse('success', safe=False) What I am basically doing is that I want to change the order status to "Paid" once the payment collection event is called and returns "COMPLETED" status. When I try to perform a test transaction, I get the following error in my shell: raise InvalidSchema(f"No connection adapters were found for {url!r}") requests.exceptions.InvalidSchema: No connection adapters were found for '{"invoice_id": "VYBP5OQ", "state": "FAILED", "provider": "CARD-PAYMENT", "charges": "0.00", "net_amount": "84.00", "currency": "USD", "value": "84.00", "account": "email@outlook.com", "api_ref": "2", "mpesa_reference": null, "host": "http://127.0.0.1:8000", "failed_reason": null, "failed_code": null, "failed_code_link": "https://intasend.com/troubleshooting", "created_at": "2022-10-28T11:55:40.755353+03:00", "updated_at": "2022-10-28T11:55:54.504547+03:00", "challenge": "123"}' [28/Oct/2022 11:55:54] "POST /webhooks/intasend/ HTTP/1.1" 500 97938 I am one year into django programming and I don't know much about APIs. For example, the response above needs to indicate the order is "Unpaid" because the "state" of the transaction is "FAILED" Anyone who can help me to proceed from … -
my previously working projects no longer work
I was writing a project with django, but my projects are not opening, not a single project, almost all projects are on a pc, I don't know why, django installed python installed, all projects were working without any problems before, the error is one by one line errors as below, but I would be glad if you could help in all projects like this I was save my projects on cloud I download them and still doesn't work