Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass json data as queryset object to django template?
I have this json data in views.py [ { "id": 6, "first_name": "Star", "last_initial": "W", "phone": "+918893972142", "email": "star@gmail.com", "date_created": "2020-10-12T17:17:17.629123Z", "orders": [] }, { "id": 4, "first_name": "Sam", "last_initial": "0", "phone": "+918766897214", "email": "sam@gmail.com", "date_created": "2020-10-12T17:13:33.435065Z", "orders": [] }, { "id": 3, "first_name": "Gaara", "last_initial": "W", "phone": "+918668972789", "email": "gaara@gmail.com", "date_created": "2020-10-12T17:08:44.906809Z", "orders": [ { "order_id": "9", "customer_id": "3", "customer_name": "Gaara W", "product_id": "3", "product_name": "Jet", "date_created": "2020-10-12T17:18:18.823289Z", "status": "Delivered" } ] } ] I want to pass this data as a context object to the template from views using render function. so I can display this data using {% for %} loop in my template. -
Signal in Model of Django
I ask you this question that I cannot find a solution. I am entering records in the Django Admin, so I enter the functions in the model. In my Sample class I add several fields, but the one I have problems with is the "number" field (sample number). In this each time I add a new sample, it adds 1 to the last number, and if the year changes, it returns to zero. So I have this code for the Sample Class: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.utils import timezone class Sample(models.Model): PREST = ( ('APS', 'APS'), ('Convenio', 'Convenio'), ('Arancelado', 'Arancelado'), ) DPTO = ( ('LAB', 'LAB'), ('DB', 'DB'), ('DSB', 'DSB'), ('DSO', 'DSO'), ) dpto = models.CharField(max_length=45, choices=DPTO) number = models.PositiveIntegerField() matrix = models.ForeignKey('Matrix', models.DO_NOTHING) kindsample = models.ForeignKey('Kindsample', models.DO_NOTHING) sample = models.CharField(max_length=255) identification = models.CharField(max_length=255, blank=True, null=True) date = models.DateField(blank=True) city = models.ForeignKey('City', models.DO_NOTHING) address = models.CharField(max_length=255, blank=True, null=True) assays = models.ManyToManyField('Assay') def __str__(self): return f"{self.number} - {self.sample}" The function for the signal is this: def save_add(sender, instance, **kwargs): if Sample.objects.all().exists(): now = timezone.now() year_sample = Sample.objects.all().last().date.year last = Sample.objects.all().last().number if year_sample == now.year: next = last + 1 else: next = … -
Django Cannot resolve keyword 'AuctionListing' into field. Choices are: auctionitem, auctionitem_id, currentbid, id, usernameb, usernameb_id
This are my models: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class AuctionListing(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") title = models.CharField(max_length=64) description = models.CharField(max_length=1000) startingbid = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField(max_length=64, blank=True) imgurl = models.URLField(max_length=300, blank=True) status = models.BooleanField(default=True) class Bid(models.Model): usernameb = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userb") auctionitem = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name="item_bided", default=1) currentbid = models.DecimalField(max_digits=6, decimal_places=2, default=0) This is my view: def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) alfa_list = Bid.objects.filter(AuctionListing__status=True) return render(request, "auctions/index.html", { "alfa_list":alfa_list }) ... When I run login_view I get the error "Cannot resolve keyword 'AuctionListing' into field. Choices are: auctionitem, auctionitem_id, currentbid, id, usernameb, usernameb_id" Any ideas why? is it the Models? is it the code from the view to generate the alfa_list? I'm running out of ideas... This is the traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 3.1.1 Python Version: 3.8.5 Installed Applications: ['auctions', '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\LINA\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in … -
curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused
I'm trying to make a Chat application using Django and Vue.js. For this initially I started to create a Django project where I installed Django rest framework and djoser using pip and added corresponding url's in urls.py. But when I'm trying to create user using [curl -X POST http://127.0.0.1:8000/auth/users/create/ --data] I'm getting as "curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused". Following are the required scripts. urls.py : """chatire URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), ] settings.py: """ Django settings for chatire project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ … -
Validate before creating objects and create multiple models data through one serializer
I created multiple models related to an applicant class Applicant(models.Model): app_no = models.CharField(max_length=20, unique=True) class ApplicantBasicDetails(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) f_name = models.CharField(max_length=255, blank=True, null=True) m_name = models.CharField(max_length=255, blank=True, null=True) l_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=15, blank=True, null=True) class AppplcantFamilyDetails(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) relation = models.CharField(max_length=255, blank=True, null=True) f_name = models.CharField(max_length=255, blank=True, null=True) m_name = models.CharField(max_length=255, blank=True, null=True) l_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=15, blank=True, null=True) Now developing an API where someone will POST below body { "app_no": "123456", "applicant_basic_details": { "f_name": "", "m_name": "", "l_name": "", "gender": "" }, "applicant_family_datails": [ { "relation": "", "f_name": "", "m_name": "", "l_name": "", "gender": "" }, { "relation": "", "f_name": "", "m_name": "", "l_name": "", "gender": "" } ] } I don't have much idea how to validate multiple models data first before creating objects I wrote one serializer. class AllInOneSer(serializers.Serializer): def create(self, validated_data): app_no = validated_data.pop("app_no") app_ser = ApplicantSer(data={"app_no": app_no}) if app_ser.is_valid(): pass else: return "error", app_ser.errors How can I pass these multiple models data through one serializer, to validate and create objects? -
Django | Static Files not loading in Production even after executing Collect static
I have a django app on Linode and the static files are not loading. I have executed the collectstatic command and defined STATIC_ROOT as well. I have used {%load static%} in my html file and using the following command to link the css <link rel="stylesheet" href="{% static 'mystyle.css' %}"> settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Here is the photo of my file structure. -
Value error when trying to insert data into Django Database Table
So I've created multiple .csv files to upload data into my tables. Everything seems to be going well except for the part where I try to add data into a table which is has a foreign key attribute. I've seen a question that's similar but it's weird for my case since I've already added data for the primary key table. <QuerySet [{'ISBN': '9780815345244', 'bookName': 'Molecular Biology of the Cell', 'bookVersion': '6', 'bookAuthor': 'Bruce Alberts', 'bookPublisher': 'W. W. Norton & Company'}, i get this error: ValueError: Cannot assign "'9780815345244'": "retailer_book.ISBN" must be a "books" instance. which is weird since it is an instance. This is my models.py code: class books (models.Model): ISBN = models.CharField(max_length=255, primary_key=True) bookName = models.CharField(max_length=255) bookVersion = models.CharField(max_length=255) bookAuthor = models.CharField(max_length=255) bookPublisher = models.CharField(max_length=255, default= 'NULL') class retailer(models.Model): sellerID = models.CharField(max_length=255, primary_key=True) retailer = models.CharField(max_length=255) class retailer_book(models.Model): ISBN = models.ForeignKey(books, on_delete = models.CASCADE) sellerID = models.ForeignKey(retailer, on_delete = models.CASCADE) condition = models.CharField(max_length=255) price = models.FloatField() reviews= models.CharField(max_length=255) ID = models.CharField(max_length=255, primary_key=True) bookType = models.CharField(max_length=255) Thank You! -
use model field name for urlconf in DeleteView django
I want my DeleteView to get url with value of field name. urls.py app_name = 'myapp' urlpatterns += [ path('member/<str:number>/update/', views.member_update, name='update') # this works with function based view. I want my CBV to work as this. path('member/<str:number>/delete/', views.MemberDelete.as_view(), name='delete') ] views.py MemberDelete(LoginRequiredMixin,DeleteView): model = Employee def get_success_url(self): return reverse_lazy('myapp:member') models.py class MyModel(models.Model): myfield = models.CharField(max_length=100, unique=True) # should I change it into SlugField? I tried puttting slug_field and slug_url_kwargs in MemberDelete in no vain. Any advice would be so grateful. Thanks in advance. -
djnago-pytest not able to create test database
I am integrating django-pytest and written first test-case for it, but when running pytest it starts creating test DB and throws error 'Cannot add foreign key constraint' after creating just 5 tables. Below is the stacktrace query = b'ALTER TABLE `tracking_invoiceview` ADD CONSTRAINT `tracking_invoiceview_invoice_id_95b70617_fk_backend_invoices_id` FOREIGN KEY (`invoice_id`) REFERENCES `backend_invoices` (`id`)' def query(self, query): # Since _mysql releases GIL while querying, we need immutable buffer. if isinstance(query, bytearray): query = bytes(query) if self.waiter is not None: self.send_query(query) self.waiter(self.fileno()) self.read_query_result() else: > _mysql.connection.query(self, query) E _mysql_exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint') cheetah_env/lib/python3.6/site-packages/MySQLdb/connections.py:276: IntegrityError The above exception was the direct cause of the following exception: request = <SubRequest '_django_db_marker' for <Function test_login>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, reset_sequences = validate_django_db(marker) if reset_sequences: request.getfixturevalue("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: > request.getfixturevalue("db") cheetah_env/lib/python3.6/site-packages/pytest_django/plugin.py:513: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cheetah_env/lib/python3.6/site-packages/pytest_django/fixtures.py:108: in django_db_setup **setup_databases_args … -
How to get pytest-django's test database connection?
I have a Django project for Postgres with a database set up through URI: DATABASES = {"default": "postgres://user:pw@host:5432/db"} When running through tests, I was to be able to see the changes to DATABASES for the new test database that pytest-django sets up. But when I try to connect to it manually with psycopg2, it's not working: psycopg2.connect("postgres://user:pw@host:5432/test_db") It's shows a different test database? I'm not sure what's going on. When I use the regular Model.objects.get(), that works fine with the test database. It's my supplied uri that's connecting to something else... -
how can i run python management command script infinite time
here is my management command script but the problem is, every time run this script through command like python manage.py scriptname.py, how can i run this script infinite time... i'm using time schedule but its not work... from django.core.management.base import BaseCommand, CommandError from datetime import datetime, timedelta from Skoapp.models import Post class Command(BaseCommand): help = 'Delete Post older than 3 minutes' def handle(self, *args, **options): planss = 5 if Post.objects.filter(plan__exact=planss): Post.objects.filter(list_date__lte=datetime.now() - timedelta(minutes=3)).delete() self.stdout.write('Deleted objects older than 3 minutes successfully') else: self.stdout.write('Post Not Detected') -
How to format export fields with numeric values in django-import-export
Using django-import-export to export data from django admin in excel xlsx format. However, numeric fields export as text in excel. I'd like to export correctly as numeric fields. Documentation has a sample syntax for BooleanWidget, but it's not working, it replaces the value with the object __str__ value, instead of converting the value to a number. -
django except matching query does not exist
I'm trying to use try and except in django; everything work perfect if the user exist but if the user doesn't exist instead of returning NULL; my function keep returning: Userprofile matching query does not exist. I know the user is not exist in table; I just want to not return anything instead of showing error page. def userAlbumFunction(id): try: albums = Album.objects.filter(user_id = id) except Album.DoesNotExist: albums = None return {'albums' : albums} -
Is it possible to upload xlsx file to aws S3 storage on coding in django?
Here is my code (I am writing some data to existing xlsx file) wb = load_workbook(EXCEL_FILE) # it is a directory to my excel file sheets = wb.sheetnames Sheet1 = wb[sheets[0]] Sheet1.cell(row = 4, column = 5).value = user_surname Sheet1.cell(row = 5, column = 5).value = user_name Sheet1.cell(row = 6, column = 5).value = address Sheet1.cell(row = 7, column = 5).value = city_and_country Sheet1.cell(row = 8, column = 5).value = phone_number Sheet1.cell(row = 9, column = 5).value = passport length = len(products) rows = [x for x in range(1,length+1)] sum_list = [] for (row,product,count,price,attr_name,attr_value) in zip(rows,products,product_count,product_price,attr_names,attr_values): length = len(attr_name) additional_info = [] for name,value in zip(attr_name,attr_value): name_and_value = name + ': ' + value additional_info.append(name_and_value) print(additional_info) Sheet1.cell(row = 3+row, column = 7).value = product + "--" +"-".join(additional_info) Sheet1.cell(row = 3+row, column = 9).value = count Sheet1.cell(row = 3+row, column = 10).value = price real_price = price[0:-2] total_one_product = int(real_price) * count sum_list.append(total_one_product) currency = Currency.objects.last() uzs = currency.UZS if currency else 10300 total_price_usd = sum(sum_list)/uzs Sheet1.cell(row = 10, column = 14) .value = round(total_price_usd,2) wb.save("demo.xlsx") # file is being saved to the directory inside of Project and sent to courier as an attachement Now i want to save it to … -
Using iframes with bootstrap carousal
I am working on a django application. In the application, I want to display a few youtube videos in the landing page. For adding and displaying the videos, I am using django-embed-video. Right now when I add videos to the webpage, they are displayed one after the other. I would like to display these videos in the bootstrap carousal. But adding them to the bootstrap carousal does not seem to work. This is my code so far <div id="carouselVideoControls" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselVideoControls" data-slide-to="0" class="active"></li> <li data-target="#carouselVideoControls" data-slide-to="1"></li> <li data-target="#carouselVideoControls" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for i in videos %} <div class="carousel-item active"> {% video i.video 'medium' %} </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselVideoControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselVideoControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> When this code is run, the carousal breaks. The next and previous buttons in the carousal do not work and only the first video is displayed indefinitely. FYI: The carousal and the video themselves work separately. If I were to use images in the bootstrap carousals instead of videos from django-embed-videos, the carousal works. It is only when, I add the … -
Unable to redirect to new page Django
I am new to Django. I am building a multiple page website via Django. on the main page I am using an onclick event and passing the data to views.py via AJAX. the issue is that in the command prompt everything is running smoothly. the function to which Ajax call was made is being called. the data is being fetched but the URL is not changing. If we copy the URL from new URL from cmd and paste it in browser window, it is working the way it is suppose to work. Can someone tell me what might the issue. -
where the Filed class import from in the serializers.py of restframework
The source code of rest_framework/serializers.py is class BaseSerializer(Field): But It does not declare where the Field import in this file. -
Django compare two queryset and append custom object
I have two models class Position(models.Model): ... job_seekers = models.ManyToManyField(settings.AUTH_USER_MODEL) class Applicants(models.Model): position = models.ForeignKey(Position, on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) I am trying to append a custom variable "selected" to my queryset to track users who appear in both the job_seekers ManytoMany field and the Applicants model using the following code. views.py position = get_object_or_404(Position, pk=self.object.pk) applicants = Applicant.objects.filter(position=position) result_list = position.job_seekers.annotate(selected=F(applicant__user)) so I can highlight selected users in my templates with something like {% if applicant.pk == applicant.selected %} How can I do this without having to change the database structure? Thanks -
Why my Django admin is not loading with css?
I have developed a web app in Djnago and deployed it then I found out that admin page is not loading with CSS. I was gettting the admin page with css in local server but not when I deployed it. [django-admin pic][1] [1]: https://i.stack.imgur.com/alHIF.png Even after using python manage.py collectstatic It's not loading with css. Here is my settings.py code from pathlib import Path import os BASE_DIR = Path(__file__).resolve(strict=True).parent.parent Here is the static files linkage part: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'first_app/media') I am not able to figure out why it's not linking the css part even after the above code Django version: 3.1 Python version : 3.8.3 Please could anyone help me out in this Thank you -
Different input and output serializers for django class-based views
I'm currently writing views to list the objects that I have. But I want to have some custom query parameters so that I can filter the querysets in the get_queryset() function. So I created a serializer for the query parameters like this: class IceCreamFilterSerializer(serializers.Serializer): start = serializers.DateField() end = seralizers.DateField() Then for the views I used method_decorator to add the query parameters to my views like this: @method_decorator(name='list', decorator=swagger_auto_schema( manual_parameters=[ openapi.Parameter('start', openapi.IN_QUERY, type=openapi.TYPE_STRING), openapi.Parameter('end', openapi.IN_QUERY, type=openapi.TYPE_STRING) ] )) class IceCream(ListModelMixin, GenericViewSet): serializer_class = IceCreamSerializer def get_queryset(self): filter_data = IceCreamFilterSerializer(data=self.request.query_params) start = filter_data['start'] end = filter_data['end'] qs = IceCream.objects.filter(created__range=[start, end]) return qs So I have two different serializers for the query parameters and for the output data. I need to differentiate the input and output serializers, but I have multiple views with this functionality. So I want to create a Mixin that manages the serializers so I can inherit it in my views. However I'm not sure what to write in the Mixin. Do I override the get_serializer_class? I have read this SO thread but I don't think this is what I want. Can you guys point me to the right direction? I'm kinda new to this Mixin thing. Any help … -
Django - Datatables ajax error with rest framework
I'm trying to use rest in conjunction with Datatables to display a large list with server-side processing. On the datatable html template i get an empty table with an error "DataTables warning: table id=bib - Ajax error. For more information about this error, please see http://datatables.net/tn/7"" urls.py from . import views as v from rest_framework import routers router = routers.DefaultRouter() router.register(r'Bibrest51', v.BibViewSet) urlpatterns = [ path('home/', include(router.urls)), path('home/', v.home, name='home'), path('', v.home, name='home'), views.py class Get_bib(viewsets.ModelViewSet): queryset = Bibrest51.objects.all() serializer_class = BibSerializer home.html <table id="bib" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/home/Bibrest51/?format=datatables"> <thead> <tr> <th data-data="autor" class ="text-center all">Autor</th> <th data-data="ano" class ="text-center all">Ano</th> <th>Título</th> <th data-data="tipo" class ="text-center not-mobile">Tipo</th> <th data-data="tema" class ="text-center not-mobile">Tema</th> </tr> </thead> <tbody> </tbody> </table> JS: <script> $(document).ready(function() { $('#bib').DataTable(); }); </script> models.py class Bibrest51(models.Model): cadastro_id = models.AutoField(primary_key=True) autor = models.CharField(db_column='Autor', max_length=255) ano = models.CharField(db_column='Ano', max_length=255) titulo = models.CharField(db_column='Titulo', max_length=255) referencia = models.CharField(db_column='Referencia', max_length=255) serializers.py from rest_framework import serializers from .models import Bibrest51 class BibSerializer(serializers.ModelSerializer): class Meta: model = Bibrest51 fields = ['autor', 'ano','tipo','tema'] -
Sending large dictionary via API call breaks development server
I am running a django app with a postgreSQL database and I am trying to send a very large dictionary (consisting of time-series data) to the database. My goal is to write my data into the DB as fast as possible. I am using the library requests to send the data via an API-call (built with django REST): My API-view is simple: @api_view(["POST"]) def CreateDummy(request): for elem, ts in request.data['time_series'] : TimeSeries.objects.create(data_json=ts) msg = {"detail": "Created successfully"} return Response(msg, status=status.HTTP_201_CREATED) request.data['time_series'] is a huge dictionary structured like this: {Building1: {1:123, 2: 345, 4:567 .... 31536000: 2345}, .... Building30: {..... }} That means I am having 30 keys with 30 values, whereas the values are each a dict with 31536000 elements. My API request looks like this (where data is my dictionary described above): payload = { "time_series": data, } requests.request( "post", url=endpoint, json=payload ) The code saves the time-series data to a jsonb-field in the backend. Now that works if I only loop over the first 4 elements of the dictionary. I can get that data in in about 1minute. But when I loop over the whole dict, my development server shuts down. I guess it's because the memory is … -
The current path, imageupload, didn't match any of these, Page not Found Django
I am new to Django and I am trying to build an image classifier app, I just tried building the app but I am getting this error, how may I resolve it? Page not found (404) Request Method: GET Request URL: http://localhost:8000/imageupload Using the URLconf defined in imageclassifier.urls, Django tried these URL patterns, in this order: imageupload ^$ [name='home'] admin/ The current path, imageupload, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. These are all changes I made in my app: This is the views.py file in imgUpload app from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html') This is the urls.py file in imageUpload app from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('^$', views.home, name ='home'), ] And this is the urls.py in the Imageclassifier folder: """imageclassifier URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') … -
Error on deploying django app to Heroku -- TypeError: argument of type 'PosixPath' is not iterable
This is my first django project and I get this error when trying to deploy. It would be really appreciated if someone could help me with this. TypeError: argument of type 'PosixPath' is not iterable Error while running '$ python manage.py collectstatic --noinput'. $ python manage.py collectstatic --noinput remote: 122 static files copied to '/tmp/build_92e98a8b/staticfiles'. remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 329, in run_from_argv remote: connections.close_all() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all remote: connection.close() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 190, in close remote: if not self.is_in_memory_db(): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 280, in is_in_memory_db remote: return self.creation.is_in_memory_db(self.settings_dict['NAME']) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db remote: return database_name == ':memory:' or 'mode=memory' in database_name remote: TypeError: argument of type 'PosixPath' is not iterable remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: … -
Using social-auth-app-django for Azure Active Directory authentication and DRF
It could be my approach is just entirely wrong and if so, being corrected would be greatly appreciated. Basically, I need to authenticate company users of the /admin portal in development against the company's Azure Active Directory. They are the only ones who should be able to access it. There are two approaches, as it was explained to me: OAuth for Servers: usually used when the app needs to access user data when they are not logged in. OAuth for Browser Apps: usually used when the app needs to access user data while they are logged in. Based on this, I went with 1, and decided to give python-social-auth, social-auth-app-django and the Microsoft Azure Active Directory a try. The examples are pretty old and it seems like I'm just missing something in the documentation to get it working. I'm using DRF, and aside from /api/admin (the Django Admin Portal), no static assets are being served by Django at all. The ReactJS FE is an entirely separate service. So an oversimplification of what should happen is: User navigates to https://example.com/ ReactJS automatically sends request to https://example.com/api/users/auth/aad/login User is presented with Microsoft login screen This is all I have so far: # …