Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Nginx - 403 on Static Files
I've recently uploaded a django project to an Ubuntu 22.04 DigitalOcean droplet. Nginx, gunicorn, and postgres have all been set up without a hitch, but the static files are all being 403'd. In both development and production, I never used collectstatic. The reason being, I always put all my static files in a static folder in the root of my project, so I figured I didn't have to do it. I'm not sure if collectstatic needs to be done in order for static files to be shown in production, but it seems that other people have still encountered this problem even when they've done collectstatic. My project on the server is called pyapps, and in that folder there are the static and media folders. The static folder is further broken down into css, js, and images folders. The media folder is further broken down into photos, then folder by year, month, then day, all of which correlate to the time the photos were uploaded. Below are my settings.py, urls.py and /etc/nginx/sites-available/ files' code. settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) /etc/nginx/sites-available/Car-terra … -
Test not found in github actions
I am trying to do an automated test. There should be 21 tests, but github-actions can't find them for some reason. https://github.com/duri0214/portfolio/actions/runs/4215160033/jobs/7316095166#step:3:6 manage.py is under mysite directory, so... (Below is when I run it on my local PC) (venv) PS D:\OneDrive\dev\portfolio\mysite> python manage.py test Found 21 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). : self.client.post(reverse('vnm:likes', kwargs={'user_id': 1, 'article_id': 99}), follow=True) AssertionError: ObjectDoesNotExist not raised ====================================================================== FAIL: test_post_click_good_button (vietnam_research.tests.test_views.TestView) ---------------------------------------------------------------------- OK Anyone know a solution? thanks -
Applying multiple validations to a field using Django REST framework
I want to check if a field in an incoming request body contains only a list of predefined integers. for example, given: valid_values=[2, 3, 8] [2, 8] should pass the validation and [4, 8] or ['2', 8] should raise a validation error. First I tried using serializers.ChoiceField() but it didn't raise any validation errors for ['2', 8]. also I have tried chaining validators but apparently it's not supported in Django REST framework. so this raised a TypeError: class MySerializer(serializers.Serializer): valid_rules = [2, 3, 8] tags = serializers.ListField(child=serializers.IntegerField().ChoiceField(valid_rules)) and I didn't found anything on the documentation either. -
Sign up function using django
i hope you are all doing great. I am currently working on a Django project. In views.py i did a function that handles registration. The user is an object from a class that django generated when i connected mysql to my django project. The request method in my form is set to POST but django doesnt execute it. It was working all good but suddenly i am getting a ValueError my function didnt return a HttpResponse. It returned None instead. The method in my html form is set to POST and the action attribute leads to the url ( {% url 'name_in_my_url_file %} -
Restful API Real-time order tracking
I design a api for a restaurant one of the features is that the user can make an order online and the oreder status is pending until the restaurant cashier or restaurant admin staff convert status by accept or refuse so i wanna create a notification or icons appears in client html page if there is pending orders or something that the admin staff or cashier know that there is an pending order created now without need to update or refresh the page , to decide if he accept the order or refuse it , so my question is how i make a html page show pending order without user refresh the page and may the page have some section to make order using restaurant staff or show current orders status i use django rest framework I hear about websocket and Django channels Also i hear about SSE Also i read about client freamwork send requests every n minute to update the page I need to know what the best approach to implement this and if there is another technology and what is best for server if there is a lot of loading or the application used by millions of … -
Django upload and process multiple files failing with libreoffice
I'm working on a Django application that works with excel files. It only works with xlsx files but if you upload an xls or an ods file I convert it previously to xlsx in order to work with that processed file. My application supports multiple file upload in the form. All files uploaded are uploaded successfully and saved into a model in Database with a field status = 'Created'. A post-save model function triggers a new Thread that process files for processing those files in background. After files are processed them are saved as status = 'Error' or status = 'Processed'. I have also added an extra option to reprocess files. The problem comes when I try to upload multiple files which are not xlsx those files need to be converted to xlsx before my own processing stuff. For that purpose I'm using libreoffice --convert-to xlsx filename --headless in a python subprocess. This is working fine with one or two file upload at the same time. But if I upload multiple files at the same time, some are failing and some files are being processed successfully, and there aren't any pattern with the files. All files for testing works properly … -
Unable to deploy Django/Docker/Nginx/Gunicorn/Celery/RabbitMQ/SSL on AWS Lightsail
I have been trying for more than a week few hours daily. Needless to say, I'm beginner in most of these things, but I have tried hundreds of configurations and nothing worked. That's why I am finally coming here for help. I am currently getting 502 Bad Gateway. My suspicion is that either Nginx can't find staticfiles or nginx upstream doesn't know what is web (in config). Nginx error logs are printing this: connect() failed (111: Connection refused) while connecting to upstream...upstream: "https://some-ip-address-here?:443" (this might be that nginx doesn't know about the web) Dockerfile # Pull base image FROM python:3.10.2-slim-bullseye # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Create and set work directory called `app` RUN mkdir -p /app RUN mkdir -p /app/staticfiles WORKDIR /app # Install dependencies COPY requirements.txt /tmp/requirements.txt RUN set -ex && \ pip install --upgrade pip && \ pip install -r /tmp/requirements.txt && \ apt-get -y update && \ apt-get -y upgrade && \ apt-get install -y ffmpeg && \ rm -rf /root/.cache/ # Copy local project COPY . /app/ COPY wait-for-it.sh /wait-for-it.sh RUN chmod +x /wait-for-it.sh docker-compose.yml version: '3.7' services: web: container_name: web build: . restart: always command: ["/wait-for-it.sh", "db:5432", "--", "gunicorn", … -
Django authorization through mobile application request
Is it possible with Django to authenticate users through a mobile app (enter login/password, then connect to the Django server and get some response)? I've tried to do something like that, but I can't figure out what to do next. Views.py def user_login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse(status=200) else: return HttpResponse(status=403) I used the extended User class, my Models.py class DiaUsers(AbstractUser): middle_name = models.CharField(blank=True, max_length=150) birth_date = models.DateField(blank=True, null=True) weight = models.FloatField(blank=True, null=True) height = models.FloatField(blank=True, null=True) attending_doctor = models.CharField(max_length=150, default="Toivo Lehtinen") app_type = models.CharField(max_length=150, default="Dia I") Serializer.py class DiaUsersSerializer(serializers.ModelSerializer): class Meta: model = DiaUsers fields = ['id', 'username', 'email', 'password', 'first_name', 'last_name', 'middle_name', 'birth_date', 'weight', 'height', 'attending_doctor', 'app_type', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined'] Admin.py admin.site.register(DiaUsers, UserAdmin) admin.site.unregister(Group) -
RelatedObjectDoesNotExist at CustomUser has no student
i'm trying to filter logbook report based on the logged in industry supervisor, the supervisor should be able to see the report of students under his supervision views.py class LogbookEntryView(ListAPIView): queryset = LogbookEntry.objects.all() serializer_class = StudentLogbookEntrySerializer def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) request = self.request user = request.user if not user.is_authenticated: LogbookEntry.objects.none() return qs.filter(student_id__industrysupervisor = request.user.student.industry_based_supervisor) models.py LogbookEntry Model class LogbookEntry(models.Model): week = models.ForeignKey("api.WeekDates", verbose_name=_("Week Id"), null=True, on_delete=models.SET_NULL) student = models.ForeignKey("students.Student", verbose_name=_("Student Id"), on_delete=models.CASCADE) entry_date = models.DateTimeField() title = models.CharField(_("Title"), max_length=50) description = models.CharField(_("Description"), max_length=1000) diagram = models.ImageField(_("Diagram"), upload_to=profile_picture_dir) Student Model class Student(models.Model): user = models.OneToOneField(get_user_model(), null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(_("profile picture"), upload_to=profile_picture_dir) department_id = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) phone_no = models.CharField(max_length=11) school_based_supervisor = models.ForeignKey("school_based_supervisor.SchoolSupervisor", verbose_name=_("School Supervisor"), null=True, on_delete=models.SET_NULL) industry_based_supervisor = models.ForeignKey("industry_based_supervisor.IndustrySupervisor", verbose_name=_("Industry Supervisor"), null=True, on_delete=models.SET_NULL) placement_location = models.ForeignKey("industry_based_supervisor.PlacementCentre", verbose_name=_("Placement Location"), null=True, blank=True, on_delete=models.SET_NULL) Industry Supervisor Model class IndustrySupervisor(models.Model): user = models.OneToOneField(get_user_model(), null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(_("profile picture"), upload_to=profile_picture_dir) phone_no = models.CharField(max_length=11) placement_center = models.ForeignKey("industry_based_supervisor.PlacementCentre", verbose_name=_("Placement Centre"), null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.user.username -
How to update multiple instance of a model
I am working on a project whereby user are able to apply to borrow book from a Libray. Whenever a user apply to borrow a book or books, an instance of the model PendingRequest is automatically created using a post_save function in signals.py. What i want to achieve is to be able to filter and update all the instance of the PendingRequest model by user. models.py class PendingRequest(models.Model): book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True) approved = models.BooleanField(default=False) not_approved = models.BooleanField(default=False) approval_date = models.DateTimeField(auto_now=True, null=True) What i want to achieve specifically is to be able to approve the request and if the request isn't approved, not_approved will be True in database. -
how redirect user with stripe react component and django
I would like to redirect my user after he has made a payment (successful or failed) to a page automatically. Currently, the payment is going well, the update is a success on stripe and I manage to retrieve the necessary information with my django view. However, after successful payment, no redirection takes place. There are several documentation but I can't find a way to do it with the react component proposed by stripe themselves. How can I proceed? here is my work Offers.js : ReactComponent by Stripe <stripe-pricing-table pricing-table-id="prctbl_<my_pricing_table_key>" publishable-key="pk_test_<my-stripe-public-key>" // user informations for update subscriptions django model customer-email={`${info_user.info_user.email}`} client-reference-id={`${info_user.info_user.id}`} > </stripe-pricing-table> When I click on the subscribe button, everything is fine. the payment is made on stripe and I retrieve the information in my webhook with django views.py class StripeWebhookView(APIView): permission_classes = [] authentication_classes = [] helpers = AbonnementHelpers updating = UpdateAbonnementHelpers def post(self, request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] endpoint_secret = STRIPE_WEBHOOK_SECRET # webhook try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: return Response(status=status.HTTP_400_BAD_REQUEST) except stripe.error.SignatureVerificationError as e: return Response(status=status.HTTP_400_BAD_REQUEST) # full session data recovery if event['type'] == 'checkout.session.completed': info_event = self.helpers().stripe_event(event) user = UserAccount.objects.get(id=info_event['user_id']) # check if user subscription exist in my … -
Please help me sort the products in the django online store
How to sort the goods in the online store so that you can click on the button and the sorting has changed, for example: price,-price. And to views.py was in class, not in def. views.py class SectionView(View): def get(self, request, *args, **kwargs): sort_form = request.GET.getlist('sort') products = Product.objects.filter(available=True) if sort_form.is_valid(): needed_sort = sort_form.cleaned_data.get("sort_form") if needed_sort == "ДТ": products = products.order_by( "created") # или updated в зависимости от того, что ты вкладываешь в понятие по дате elif needed_sort == "ДЕД": products = products.order_by("price") elif needed_sort == "ДОД": products = products.order_by("-price") return render( request=request, template_name='main/index.html', context={ 'products':products, } ) forms.py class SortForm(forms.Form): sort_form = forms.TypedChoiceField(label='Сортировать:', choices=[('ПУ', 'По умолчанию'), ('ДТ', 'По дате'), ('ДЕД', 'От дешевых к дорогим'), ('ДОД', 'От дорогих к дешевым')]) index.py <form action="{% url 'product_list' %}" method="get" class="sort-form"> {{ sort_form }} <p><input type="submit" name="sort" value="Сортировать"></p> {% csrf_token %} </form> -
Reference comment count on different using Django
I have a BlogPage that references all my blogs with snippets of text. These can be clicked to view the full blog on a ViewBlog page, at the bottom of the view-blog page you can add a comment, and all comments are subsequently shown on this page. I want to be able to reference the amount of comments made on every post some where on the snippet box on the blog page as screenshot below shows (I don't require help with the code for this, only the code to be able to reference it on the BlogPage; MODELS.PY class BlogPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="") text = RichTextUploadingField(null=True, blank=True, default="text") featured_text = models.TextField(max_length=550, null=True, blank=True, default="text") image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") date = models.DateField(auto_now_add=True) published = models.BooleanField(default=False) featured = models.BooleanField(default=False) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class BlogComment(models.Model): post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) name = models.CharField('Name',max_length=100, default="") text = models.TextField('Comment',max_length=1000, default="") date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ("date",) def __str__(self): return '%s -- Name: %s'%(self.post.title, self.name) VIEWS def BlogPage(request): posts = BlogPost.objects.filter(date__lte=timezone.now()).order_by('-date') blog_paginator = Paginator(posts, per_page=4) page_number = request.GET.get('page') page = blog_paginator.get_page(page_number) … -
iexact doesn't work in declaring filterable field in django-filter
I am using django-filter lib with DRF. class OrganizationFilter(FilterSet): class Meta: model = Organization fields = { 'city': ['iexact', 'contains'], 'zipcode': ['exact', 'contains'] } city: CharField I want to filter city field case-insensitive. I can make it work by specifying the following. class OrganizationFilter(FilterSet): city = filters.CharFilter(lookup_expr='iexact') ... Unless If I don't specify the lookup_expr it's not working. I want to know why? -
How to generate 10 digit unique-id in python?
I want to generate 10 digit unique-id in python. I have tried below methods but no-one worked get_random_string(10) -> It generate random string which has probability of collision str(uuid.uuid4())[:10] -> Since I am taking a prefix only, it also has probability of collision Do we have any proper system to generate 10 digit unique-id? -
Reading a file in view vs template in Django - is one more performant over the other?
Let's say I want to read a .txt file in Django. I can do it in two ways: 1. View def index(request): file = open('path/to/file', 'r') return render(request, 'index.html', {"text": file.read()}) And then just use that in the template like so: {{ text }}. 2. Template Or I could do it directly in the template using include, like so: {% include 'path/to/file' %}. Not my question is, is one approach better than the other one? Like is there a performance benefit in doing 2? Thanks for any help. -
How to combine two different tables information together in vuejs and django?
I am trying to build a application where there is on table called party which contains basic customer information and then another table called leads which contains more information about the same customer. But I am not able to get the two different tables information in one ag-grid table to show the information on my Vue.js frontend. Here is the code for the two tables separately: Party table <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Party table</h1> <ag-grid-vue style="width:1310px; height: 650px" class="ag-theme-alpine" :columnDefs="columnDefs" :rowData="rowData" > </ag-grid-vue> </div> </div> </template> <script> import axios from 'axios'; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-alpine.css"; import { AgGridVue } from "ag-grid-vue3"; import 'ag-grid-enterprise'; export default { components: { AgGridVue, }, data() { return { columnDefs: null, rowData: null, } }, mounted(){ this.columnDefs=[ {field:'FIRST_NAME',headerName: 'First name'}, {field:'LAST_NAME',headerName: 'Last name'}, {field:'PARTY_TYPE',headerName: 'Party Type'}, {field:'PRIMARY_NO',headerName: 'Main number'}, {field:'WHATSAPP_NO',headerName: 'Whatsapp number'}, {field:'EMAIL_ID',headerName: 'Email ID'}, {field:'PREFERRED_CONTACT_METHOD',headerName: 'Preferred contact'}, ]; axios.get('http://127.0.0.1:8000/request1') .then(response=>this.rowData=response.data) }, } </script> <style scoped> .ag-theme-alpine { --ag-foreground-color: rgb(2, 1, 2); --ag-background-color: rgb(245, 244, 243); --ag-header-foreground-color: rgb(204, 245, 172); --ag-header-background-color: rgb(64, 103, 209); --ag-odd-row-background-color: rgb(0, 0, 0, 0.03); --ag-header-column-resize-handle-color: rgb(236, 230, 236); --ag-font-size: 17px; --ag-font-family: monospace; } </style> Leads table <template> <div class="tasks_container"> <div class="tasks_content"> <h1>Lead table</h1> <ag-grid-vue style="width: 1330px; height: 850px" class="ag-theme-alpine" … -
AttributeError 'datetime.date' object has no attribute 'utcoffset'
Sorry if Im not making complete sense, but I'm relatively new with Django I have a models.py file with such attributes: from datetime import * from django.db import models def return_date_time(): now = datetime.now() return now + timedelta(days=10) class Job(models.Model): lastDate = models.DateTimeField(default=return_date_time) createdAt = models.DateTimeField(auto_now_add=True) I am able to create new database on /admin, but when editing I get This error AttributeError at /admin/job/job/2/change/ 'datetime.date' object has no attribute 'utcoffset' There was a very similar post here : https://stackoverflow.com/questions/51870088/django-attributeerror-datetime-date-object-has-no-attribute-utcoffset but I was not able to solve the problem The Traceback is as below Environment: Request Method: GET Request URL: http://localhost:8000/admin/job/job/2/change/ Django Version: 4.1.7 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django.contrib.gis', 'django_filters', 'job.apps.JobConfig'] 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'] Template error: In template /Users/daniel/Workspace/Projects/iTokyo_Jobs/.venv/lib/python3.10/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 'datetime.date' object has no attribute 'utcoffset' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors … -
The task in my Django asynchronous view is not executed
Django asynchronous views can respond immediately, while tasks run asynchronously,but in fact the task cannot continue. async def task_async(): print('task begin') await asyncio.sleep(2) print('task run success') async def view_async(request): print('async begin') loop = asyncio.get_event_loop() loop.create_task(task_async()) print('return') return HttpResponse("Non-blocking HTTP request") I expect the task to continue running after the http response returns, but the result is: async begin return task begin Using uvicron is ok, but manage.py is not。 -
Pytest randomly return ConnectionError
I have a Django project with pytest as the unit testing module. Previously, everything ran smoothly but lately when running unit testing, it took a very long time, around 20 minutes (initially it only took 10-12 minutes). In addition, there is a test failure that displays the following message: requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')). Is there any information on how to solve this? I have tried running unit tests for my entire codebase, but I am seeing errors occur in random files. When I try to run tests for a specific file, the errors occur in random functions within that file. I also deleted my virtual environment folder and reinstalled my dependencies, and rebooted my computer. However, I am still encountering the same issues with my unit tests. I have tried searching for solutions online, but I am not finding any helpful results with my search keywords -
Django Rest Framework Password Rest Confirm Email not showing Form and returning as none
In my Django Rest Framework, the users request to reset the password and when the email is received and the link is clicked, the url password-reset-confirm/<uidb64>/<token>/ as comes up requested but the form is not showing and when I added it as {{ form }} is displayed NONE The password reset process is working perfectly fine when I do everytihng on the Django but if I try to reset the password from Django Rest Framework the form does not appear. Here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm',), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('admin/', admin.site.urls), path('api/', include('api.urls'), ), path('users/', include('users.urls'), ), ] Here is the API app urls.py that is related to DRF app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] here is the template password_reset_confirm.html <main class="mt-5" > <div class="container dark-grey-text mt-5"> <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} {{ form }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Reset Password</button> </div> </form> </div> </div> </main> My question is: Why is the form showing as NONE … -
Getting the User from an APIClient() in DRF
Im using a fixture in pytest that returns a client that has been logged in: @pytest.fixture def create_client(create_user) -> APIClient: data = { "email": create_user.email, "password": "TestPassword", } client = APIClient() client.post(path="/user/login/", data=data) return client How might i get the user that has been logged in in the test i understand i might be able to use a get a request from the client and get it that way: def test_get_user(create_client): response = create_client.get(path="/some/random/path/") user = response.user return user but is there a better way to do this? -
Fix for [GET]/ favicon.ico when trying to deploy a chat app on vercel?
This is the error I keep getting while trying to upload the same app as https://www.studybud.dev: [GET] /favicon.ico 06:21:27:53 [ERROR] ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Traceback (most recent call last): File "/var/lang/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/var/task/vc__handler__python.py", line 13, in <module> __vc_spec.loader.exec_module(__vc_module) File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "./studybud/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/var/task/django/contrib/auth/models.py", … -
Filter Backends Django Rest Framework List API View
Excuse me devs, I want to ask about Django generics List API View filter_backends, how can i return none / data not found when the param is wrong or empty? # My Django Views class FilterTablePVPlantByPVOwnerId(filters.FilterSet): id = filters.CharFilter( field_name='id', lookup_expr='exact') class Meta: model = TablePVPlant fields = ['id'] class PlantListByClientView(generics.ListAPIView): queryset = TablePVPlant.objects.all() serializer_class = PlantListSerializer filter_backends = [DjangoFilterBackend] filterset_class = FilterTablePVPlantByPVOwnerId def list(self, request, *args, **kwargs): if self.request.query_params: response = super().list(request, *args, **kwargs) response.data = {'status': 'success', 'data': response.data, 'msg': 'done'} return response -
pythonanywhere back-end to external react native site
Here is the environment I am looking at. I am building my UI layer in DraftBit, which is a low code drag-and-drop platform. I am looking to host my backend on PythonAnywhere. I want to communicate via Rest APIs that I would want to expose to the Draftbit screens. Has anyone done this before and has that worked well? Is it easy to expose your API's to external parties? Any feedback is appreciated. Thanks Uday I have not tried anything yet. I am exploring hosting providers like Hiroku etc but like the fact that PythonAnywhere is a python platform since my backend platform is a Python/Django.