Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to search for the most similar entry
There are many ways I can query for information in a database, mine being PostgreSQL, such as __contains, __icontains, unnaccent__icontains, __unaccent__lower__trigram_similar, and so on. Though these are very handy, none of these helped my really reach the goal I have in mind: searching for the most similar entry. Trigram similarity got pretty close, but it no longer worked for longer strings. Is there any operation that can get the closest value, also working for longer strings? -
Django: How to rewrite raw SQL into queryset
The raw SQL was rewritten because the issue time of the following queryset was very slow. # queryset Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), ).filter( Q(title__contains=value) | Q(tags__name__contains=value), is_public=True, published_at__lte=timezone.now(), ).order_by("-published_at").distinct()[:20] SELECT DISTINCT "videos_video"."id", "videos_video"."title", "videos_video"."thumbnail_url", "videos_video"."preview_url", "videos_video"."embed_url", "videos_video"."duration", "videos_video"."views", "videos_video"."is_public", "videos_video"."published_at", "videos_video"."created_at", "videos_video"."updated_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_wl" FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT OUTER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE ("videos_video"."is_public" AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00' AND ("videos_video"."title" LIKE '%word%' OR "videos_tag"."name" LIKE '%word%')) ORDER BY "videos_video"."published_at" DESC LIMIT 20; I have sped up the above query to look like the query below. But how can I reproduce this in Django's querieset? SELECT DISTINCT "t"."id", "t"."title", "t"."thumbnail_url", "t"."preview_url", "t"."embed_url", "t"."duration", "t"."views", "t"."is_public", "t"."published_at", "t"."created_at", "t"."updated_at", EXISTS (SELECT (1) AS … -
Django Session Is not working with Heroku when changing views (but works locally)
The sessions work perfectly while changing views when working locally, but when deployed to Heroku it is as if the session was refreshed and all the information it contains is deleted upon every view change. I am using Heroku's Postgres Database. I have already taken a look at: Django Session Not Working on Heroku but the problem still persists Here is my current settings file. Any help would be appreciated import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'e488a0185303170daa47fe1de243823fbb3db60f045e6eae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'here goes the heroku host'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '....', '....', ] ASGI_APPLICATION = 'System.asgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'System.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'System.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 8} }, … -
Django Rest Framework - Nested List Inside JSON Response
I'm very new to both Django and the Django Rest Framework, and I'm struggling with building up a particular JSON response. I have two models, like so: class Artist(models.model): artist_id = models.CharField( max_length=256, primary_key=True, ) name = models.CharField( max_length=256, null=False, blank=False, ) birthplace = models.CharField( max_length=256, null=False, blank=False, ) class Album(models.Model): artist = models.ForeignKey( Artist, on_delete=models.DO_NOTHING, db_constraint=False, null=True, ) name = models.CharField( max_length=256, null=False, blank=False, ) label = models.CharField( max_length=256, null=False, blank=False, ) I'm trying to build a JSON response that looks like this, where the albums are nested inside the artist: { "artist_id": "A123", "name": "Bob Dylan", "birtplace": "Duluth, Minnesota", "albums": [ { "id": 123, "name": "Bob Dylan", "label": "Columbia" }, { "id": 123, "name": "The Freewheelin' Bob Dylan", "label": "Columbia" } ] } Is this even possible? I was looking into select_related, but that doesn't seem to work as I feel like I need to 'hit' the Artist table first, and there is no relationship defined in the direction of Artist to Album. Any help would be greatly appreciated. -
I need save info + User.id or username to database in Django
I have some problem with save info about authentificate user with info. I didnt have some id but django have exception. My model.py from django.contrib.auth.models import User from django.db import models from hashlib import md5 from django.conf import settings # Create your models here. class Url(models.Model): long_url = models.CharField(unique=True,max_length=500) short_url = models.CharField(unique=True, max_length=100) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) id = models.BigAutoField(primary_key=False, null=True) @classmethod def create(self, long_url, user, id): tmp = md5(long_url.encode()).hexdigest()[:6] tmp = '127.0.0.1:8000' + '/' + tmp try: obj = self.objects.create(id=id,long_url=long_url, short_url=tmp, user=user) except: obj = self.objects.get(long_url=long_url, user=user) return obj My views.py from django.contrib.auth.models import User from django.shortcuts import render, redirect from .forms import UserRegistration, UserLogIn from .models import Url from django.http import HttpResponse from django.contrib.auth import authenticate, login # Create your views here. def register(request): if request.method == 'POST': user_form = UserRegistration(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request, 'register.html', {'new_user': new_user}) else: user_form = UserRegistration() return render(request, 'register.html', {'user_form': user_form}) def shorter(request): if request.method == 'POST': long_url = request.POST.get('long_url') obj = Url.create(long_url, User) return render(request, 'short.html', { 'short_url': request.get_host() + '/' + obj.short_url[-6:]}) return render(request, 'shorter.html') My forms.py from django.contrib.auth.models import User from django import forms class UserRegistration(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat … -
Django: How do I create separate instances of the same model object?
I have two classes that need to relate to each other. an Item class and an Order class. An Item object has several attributes: name, cost, quantity etc. I want the same item to be able to belong to several different Order objects and white doing so, having different attributes inside that Order object. (Like different orders can have different amounts of the same Item on order) Is this possible? Here's what I've got so far: class Item(models.Model): description = models.CharField(max_length=200) cost = models.FloatField() order_quantity = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.description) @property def line_total(self): return self.cost * self.order_quantity class Order(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('issued', 'Issued'), ('closed', 'Closed'), ) reference = models.AutoField(primary_key=True) location = models.ForeignKey( Location, null=True, blank=True, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) item = models.ManyToManyField(Item, blank=True) class Meta: ordering = ('location',) def __str__(self): return str(self.reference) This setup allows me to have the same item in different orders, which is great, however I can't figure out how to make some Item attributes 'independent', based on which order they belong to. -
Customized Settings in Django
I am creating an electronic reference library for my school, where I have created a custom admin page (not the Django admin page). And in my requirements there needs to be a specific 'settings' page where I can store small information such as How frequently to create reports How frequently users should change their passwords etc. These kinds of custom settings are not available in Django by default. But is there a way I can implement it in my app? And how should I store this information? Should I create another table to store these information? Please let me know how to tackle such a situation. Thanks! -
Django: Annotate distinct foreign ManyToMany relation
Given the following simplified model setup class Tag(models.Model): name = CharField() class Template(models.Model): name = CharField() tags = ManyToManyField(Tag) class Collection(models.Model): name = CharField() templates = ManyToManyField(Template) class GenericViewSet(viewsets.ModelViewSet): def get_queryset(): ... queryset = Collection.objects.all() queryset = queryset.annotate(tags=models.Distinct('templates__tags')) ... Is there a way similar to the last line above to annotate a Collection queryset with a distinct set of tags originating from its templates? Example (Template): name: History 1 tags: [England, France] (Template): name: History 2 tags: [England, United States) (Collection): name: History of England templates: [History 1, History 2] tags: [England, France, United States] Where the collections tags are derived from its templates. -
Unable to Login to Admin Panel in Django using Custom User Model
I have created a custom user model that overrides the default AUTH_MODEL in settings.py. I am unable to login on the admin panel using python manage.py createsuperuser. The message that the admin throws back at me is: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. Below is my code for models.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from django.contrib.auth.hashers import make_password from phonenumber_field.modelfields import PhoneNumberField class UserAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, phone, password=None): if not email: return ValueError("User must have an email address!") if not username: return ValueError("User must have a username!") if not first_name: return ValueError("User must have a first name!") if not last_name: return ValueError("User must have a last name!") if not phone: return ValueError("User must have a phone number!") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, phone=phone, ) hashed_password = make_password(password) user.set_password(hashed_password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, phone, password): user = self.create_user( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, phone=phone, password=password, ) user.is_admin = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): username = models.CharField(null=False, blank=False, max_length=30, unique=True) first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) email = models.EmailField(null=False, blank=False, unique=True) … -
Store JWT tokens in cookies with django-rest-framework-social-oauth2 library
I wanted to securely store my JWT token. Up until now, I have used local storage, but I have read that using local storage is not secure. Hence, I wanted to start using HttpOnly cookies to store my JWT tokens. I was going to use CSRF protection inbuilt into Django to mitigate the security issues with cookies. However, I can't figure out how to use cookies with the Django-rest-framework-social-oauth2 library. There doesn't need to be any other library that has social auth and JWT auth. So my first question, is there a secure storage method that doesn't need cookies. If not, how does use django-rest-framework-social-oauth2 library with cookies? -
How not to skip what follows hashtags in django admin search field?
In Django admin, there is the search bar for list_display page of objects. Lets say there is search_fields = ["name"] for given admin. If there is an object with the name "abc" and the search term is "ab", an object is returned. however, when there is a name "abc#deg" and "ab" is searched for, doesn't return any. Seems like the Django admin search bar perceives # as a special character for setting parameters or something, does anyone know how to avoid this? Any hint would be much appreciated! -
Django/PythonAnywhere -- Getting Error "Something went wrong :-("- Debugging Tips
I am new and learning Full Deployment walkthrough on python Anywhere, But getting the Error. I have tried all possible things which I could do to resolve it but I am stuck here. where supriya25 is my directory name Error is: **Something went wrong :-(** Something went wrong while trying to load this website; please try again later. If it is your site, you should check your logs to determine what the problem is. There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception **Debugging tips** -The first place to look is at your web app page to ensure that there are no errors indicated there. -Next, check your site's server and error logs for any messages — you can view them here: -supriya25.pythonanywhere.com.error.log -supriya25.pythonanywhere.com.server.log -You can find helpful tips on the PythonAnywhere help site: -There's an ImportError in the logs -"403 Forbidden" error or "Connection Refused" error in logs -Database connection errors -There are many more helpful guides on our Help pages If you get completely stuck, then drop us a line at support@pythonanywhere.com, in the forums, or use the "Send feedback" link on the site, with the relevant … -
Is there a best practice for storing data for a database object (model) that will change or be deleted in the future (Django)?
I am building an order management system for an online store and would like to store information about the product being ordered. Now, if I use a Foreign Key relationship to the product, when someone changes the price of the product or deletes it, the order will be affected as well. I want the order management system to be able to display the state of the product when it was ordered even if it is altered or deleted from the database afterwards. I have thought about it long and hard and have come up with ideas such as storing a JSON string representation of the object; creating a duplicate product whose foreign key I then use for the order etc. However, I was wondering if there is a best practice or what other people use to handle this kind of situation in commercial software? -
Revoke celery task queue based on task id
I have two button in Django View in which the first button starts a celery task. I want to stop the queue when i press the second button. Is it possible to stop the queue simply based on the task id? -
Django makemigrations not working, how can i fix the dependencies?
I'm getting the error at the end of the trace back below. When I run 'python manage.py makemigrations'. I Get similar errors when I run it by 'python manage.py makemigrations accounts' and 'python manage.py makemigrations homedb'. If I run the accounts app, it says I'm missing a dependency in the accounts app and if I run the homedb app, it says I'm missing a dependency in the accounts app. In an effort to fix this, I've deleted my migrations, many pycache_ items, and the database to no avail. I also unstalled then reinstalled django. I would be greatful for any help. This is a portion of my traceback: self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/loader.py", line 262, in build_graph self.graph.validate_consistency() File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, Du mmyNode)] File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, Du mmyNode)] File … -
Customize Create funciton in DRF viewset
I want to customize the user viewset i.e. when the user registers the user account was created as well. -
How to require non-admin login before accessing Wagtail admin login
I am working on a Django App that uses Wagtail and django-allauth. I am using a workaround from Allauth docs to take advantage of some Allauth's features which are lacking in vanilla Django Admin login. from django.contrib import admin from django.contrib.auth.decorators import login_required admin.site.login = login_required(admin.site.login) I am trying to do the same for the Wagtail Admin, but am having no luck so far. My difficulty might be because the Wagtail admin views are class-based - I don't think I can use method_decorator in this context. Any help or pointers are highly appreciated. -
How to adjust ChainedManyToManyField to populated field based on another field?
I'm trying to populate district based on the selected city in the admin page. I tried the ChainedManyToManyField, but when selecting a city, there is no districts in the dropdown menu! class District(Timestamps): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=100) class ListingPrice(MinimumListingPriceBase): city = models.ForeignKey("location.City", on_delete=models.CASCADE, null=True) district = ChainedManyToManyField( District, horizontal=True, chained_field="city", chained_model_field="city", auto_choose=True ) How to make it possible to select districts based on selected city in the admin page? -
unsupported operand type(s) for @: 'Q' and 'Q' in Django RestFramework
I am trying to make login api using django rest framework and while doing login api serilization I encounter this error "unsupported operand type(s) for @: 'Q' and 'Q'" inside validate function. I couldn't understand why this error came and help me to solve this This is my model.py file class User(models.Model): first_name=models.CharField(max_length=100, null=True) last_name=models.CharField(max_length=100, null=True) username = models.CharField(max_length=100, null=False,unique =True) email = models.EmailField(max_length=100, null=False, unique =True) # work_email = models.EmailField(max_length=100,unique =True) password = models.CharField(max_length=50, null=False) phone= models.CharField(max_length=100, null=True,unique =True) phone2=models.CharField(max_length=100, null=True,unique =True) is_login = models.BooleanField(null=True, default=False) is_verified=models.BooleanField(null=True) is_active=models.BooleanField(null=True) token = models.CharField(max_length=100, null=True, default="") user_type_id=models.ForeignKey(UserType, on_delete=models.CASCADE,null=True) created_at=models.DateField(null=True) updated_at=models.DateField(null=True) def __str__(self): return "{} -{}".format(self.username, self.email) and here is serializers.py file from django.db.models import Q, fields from django.db.models.base import Model # for queries class UserLoginSerializer(serializers.ModelSerializer): username=serializers.CharField() password=serializers.CharField() token=serializers.CharField(required=False, read_only=True) def validate(self,data): # user,email,password validator username=data.get("username",None) password=data.get("password",None) if not username and password: raise ValidationError('Detail not enter') user=None # if email is passed in username if '@' in username: user= User.objects.filter(Q(email=username) & Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credintials are not correct.") user= User.objects.get(email=username) else: user=User.objects.filter(Q(username=username)@ Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credentials are not correct.") user = User.objects.get(username=username) if user.is_login: raise ValidationError("User already logged in.") user.is_login = True data['token'] = uuid4() user.token = … -
Test Django validator with parameters
I want to test a custom validator for an ImageField that checks that the aspect ratio of the image is between the given parameters. The validator takes a min_aspect_ratio and a max_aspect_ratio parameter, and returns a validator function, which takes the image from the ImageField: def validate_image_aspect_ratio(min_aspect_ratio: int, max_aspect_ratio: int): """Checks that the proportions of an image (width / height) are what we expect.""" def validator(image): if image is None: return aspect_ratio = image.width / image.height error_message = _( 'Image\'s height proportion to its width should be between %(min_aspect_ratio)s and %(max_aspect_ratio)s. ' 'It was %(aspect_ratio)s.' ) % { 'aspect_ratio': "{:.2f}".format(aspect_ratio), 'min_aspect_ratio': min_aspect_ratio, 'max_aspect_ratio': max_aspect_ratio } if aspect_ratio < min_aspect_ratio or aspect_ratio > max_aspect_ratio: raise ValidationError( error_message ) return validator Here's how I am using the validator: image = models.ImageField( _('Image'), help_text=_('A default image will be used if this is not set.'), blank=True, validators=[validate_image_aspect_ratio(1.25, 1.35)] ) Now I want to test this method, for which I will give it two arguments for the aspect-ratio range, but how do I pass the image to it? The problem is not creating a mock image for the test, just how do I pass it to the function, since it is passed to the returned … -
How should I send input array from javascript to django views.py
I am trying to send an array from javascript function to views.py and after some calculations to array i want to display the array on the webpage -
Ajax returns whole HTML page in Django
I'm trying to implement a simple form using the bootstrap modal but whenever I submit the form the response I get is whole HTML page. The request is POST. I have tried almost all answers which are present on the StackOverflow but none of them worked for me. My Modal form code: <div id="alert-box"></div> <form id="ajax-form" autocomplete="off"> {% csrf_token %} {{contact_form|crispy}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> This is my Ajax code: <script type="text/javascript"> const alertBox = document.getElementById('alert-box'); const msgForm = document.getElementById('ajax-form'); const name = document.getElementById('id_name'); const number = document.getElementById('id_phone_number'); const message = document.getElementById('id_message'); const csrf = document.getElementsByName('csrfmiddlewaretoken'); const handleAlerts = (type,text) => { alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } const url = ""; console.log(csrf); msgForm.addEventListener('submit',e => { e.preventDefault(); const fd = new FormData(); fd.append('csrfmiddlewaretoken',csrf[0].value); fd.append('name',name.value); fd.append('number',number.value); fd.append('message',message.value); $.ajax({ type: 'POST', url: url, data: fd, cache: false, contentType: false, processData: false, enctype: 'multipart/form-data', success: function(response) { const sText = `${response.name}`; handleAlerts('success', sText) setTimeout(()=>{ alertBox.innerHTML = ""; name.value = ""; number.value = ""; message.value = ""; }, 5000); }, error: function(error){ handleAlerts('danger', 'oops..something went wrong') } }) }); </script> This the form which I want to submit. -
Django Static Files does not deploy on Google Cloud Bucket
I am deploying an Django App, which runs on google server but it does not load the static files, so that App does not load the css and images. I checked the bucket I created but there is no files in the bucket. Here is settings.py STATIC_URL = '/static/' STATIC_ROOT = "static" PRODUCTION = True if PRODUCTION: # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") print(GS_BUCKET_NAME) STATIC_URL = "/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_DEFAULT_ACL = "publicRead" else: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Here is app.yaml file. runtime: python38 handlers: - url: /static static_dir: static/ - url: /.* script: auto Here is urls.py. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I deploy the app, it was done successfully. but the static files does not deploy into the bucket. As well I run this bellow command. python manage.py collectstatic I followed this tutorial. -
IndentationError: unindent does not match any outer indentation level (views.py, line 20)
enter image description here Tried every damn thing from changing indentation to spaces to writing a new file, this error is determined to not go from django.urls import path from . import views app_name="main" urlpatterns= [ path("",views.homepage,name="homepage"), path("register/", views.register, name="register") ] -
I want to fetch the data using api in flutter
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital …