Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CORS Missing Allow Origin Error even with corsheaders middleware
Hi I'm building a SPA with Django + Vue.js and struggling with CORS Missing Allow Origin error. It occurs when Vue.js frontend call some API and Django backend returns redirect to external URL. From Django backend, this API returns something as below. return redirect('https://api.external.service.com/sso/authorize?param1=xxx&param2=yyy>') And then Vue.js frontend tries to redirect to the URI but it fails. Since console tells "CORS Missing Allow Origin", I'm using corsheaders with the following configuration, but it doesn't solve the issue. What's wrong with what I'm doing?? settings.py DJANGO_DEBUG = True ALLOWED_HOSTS = ('localhost', 'api.external.service.com',) CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ('https://localhost:8000', 'https://0.0.0.0:8000', 'https://api.external.service.com',) ... INSTALLED_APPS = [ ... 'django_extensions', 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] For debug, I tried the follows but it also failed with the same error... settings.py DJANGO_DEBUG = True ALLOWED_HOSTS = ('*',) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ('https://localhost:8000', 'https://0.0.0.0:8000', 'https://api.external.service.com',) ... INSTALLED_APPS = [ ... 'django_extensions', 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Otherwise am I misunderstanding "CORS", and perhaps I should register my app domain to the external service to allow access from my app to it?? -
Django Signals: Creating instance of different models when one is created based on a boolean field on the sender model
I have three models ProductOrService, Product and Service. I have a BooleanField named is_product in the ProductOrService model which says that an item is a product if it is true and it is a service if it is false. I want to automatically create a Product instance if the is_product field is True or automatically create a Service instance if the is_product field is False. The code given below creates a Product instance when a ProductOrService instance is created with is_product set to True. But it does not create a Service instance when a new ProductOrService instance is created with is_product set to False. models.py: class ProductOrService(models.Model): web_id = models.CharField(max_length=50, unique=True, verbose_name=_("product web id"), help_text=_("format: required, unique")) slug = models.SlugField(max_length=255, null=False, blank=False, verbose_name=_("product/service url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("product/service name"), help_text=_("format: required, max_length=250")) seller = models.ForeignKey(User, related_name="product_or_service", on_delete=models.PROTECT) description = models.TextField(verbose_name=_("product description"), help_text=_("format: required")) category = TreeManyToManyField(Category) is_visible = models.BooleanField(default=True, verbose_name=_("product/service visibility"), help_text=_("format: true->product is visiible")) is_blocked = models.BooleanField(default=False, verbose_name=_("product/service blocked"), help_text=_("format: true->product is blocked")) created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_("date product/service created"), help_text=_("format: Y-m-d H:M:S")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("date product/service last updated"), help_text=_("format: Y-m-d H:M:S")) is_product = models.BooleanField(default=True, verbose_name=_("Is this product?"), help_text=_("format: … -
AJAX-based refresh without data duplication
I am confused about AJAX requests. I am using the load() function to refresh specific elements on the page. Unwanted duplication does not occur when there is only one matched element on the page. {% for example in examples %} <div class="refresh" id="single{{ example.id }}"> <div class="container"> <p> Different content </p> </div> </div> {% endfor %} Assuming the above example, I would like to refresh the contents of a container with different contents in multiple elements on the page. In this case, if the 'examples' elements are four, there will be 8 after the refresh. I've tried everything I can find, but so far the data is duplicated. -
Django 4 seems to be caching my query. How can I turn it off?
Some context I have a model with 20+ attributes. This is for a property-listing site (like Airbnb). So there are things like size, bedrooms, city, state, etc. There needs to be an auto-complete functionality on the textboxes when I am editing these properties. So for example, State is a text field in my form. When I am adding a 2nd house to my website, the State textbox should suggest values from the previous houses that I have in my system. (Basically when I type C, it should show California if I have any houses with California already in the DB) UpdateView I am using an Update View to show my Property-Edit (House-Edit) page. I need to pass in all these auto-complete fields inside this Update View so that I can add them to my text boxes. The code looks like this: class PropertyUpdateView(LoginRequiredMixin, UpdateView): context_object_name = 'property' model = models.Property form_class = forms.PropertyForm template_name = 'desertland/admin/property_update.html' extra_context = get_autocomplete_fields() def get_success_url(self): messages.success(self.request, 'The property was updated successfully.') return reverse('property_update', kwargs={'pk': self.object.id}) The extra_content is where I am passing my autocomplete fields. The get_autocomplete_fields() method is like so: def get_autocomplete_fields(): ac_keys = ['state', 'city', 'county', 'zip_code', 'zoning', 'power', 'water_district', 'water', 'access', … -
127.0.0.1:8080/data/ping should return pong json response (something like {‘data’:‘pong’}
I am using Redis in my project for caching, now I need to return pong in the browser when i point to the /data/ping and also other Redis CLI operations if possible, I did some research and found something in js but I need to implement this in pure Django or DRF -
I am getting the error disallowed host with python anywhere
I am trying to deploy my blog to python anywhere but I keep getting this error DisallowedHost at /. The error log says this Invalid HTTP_HOST header: 'codewizblog.pythonanywhere.com'. You may need to add 'codewizblog.pythonanywhere.com' to ALLOWED_HOSTS. I do not know why it is asking me to add something I have already added to my sittings file. if anyone knows how to fix this any help would be appreciated. Also if anyone can give me tips on security for my site that would also be appriceated. setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['codewizblog.pythonanywhere.com',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } … -
Django - get message from websocket
I would like to be able to receive a message from the user POST /createEvent and immediately give it to all other users via websocket /wsEvens But it's not clear to me how to make interaction between these interfaces in Django I use Django + DRF -
Problems configuring site on PythonAnywhere
I am trying deploy a test web app on PythonAnywhere by pulling my code from my Github repo using a helper tool by PythonAnywhere. I used this command: $ pa_autoconfigure_django.py --python=3.8 https://github.com/<your-github-username>/repository.git Then after a prompt for my username and password ( had to use a token because it is required) and putting them in I got this error: remote: Write access to repository not granted. fatal: unable to access 'https://github.com/Username/Myrepo.git/': The requested URL returned error: 403 Traceback (most recent call last): File "/home/Username/.local/bin/pa_autoconfigure_django.py", line 49, in <module> main( File "/home/Username/.local/bin/pa_autoconfigure_django.py", line 31, in main project.download_repo(repo_url, nuke=nuke), File "/home/Username/.local/lib/python3.8/site-packages/pythonanywhere/django_project.py", line 20, in download_repo subprocess.check_call(['git', 'clone', repo, str(self.project_path)]) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['git', 'clone', 'https://github.com/username/repo.git', '/home/username/username.pythonanywhere.com']' returned non-zero exit status 128 Can someone tell me what im doing wrong? -
How deep can "django-nested-admin" have nested inlines?
django-nested-admin shows the code example which has 3 levels "TableOfContentsAdmin", "TocSectionInline" and "TocArticleInline" as shown below: # An example admin.py for a Table of Contents app from django.contrib import admin import nested_admin from .models import TableOfContents, TocArticle, TocSection class TocArticleInline(nested_admin.NestedStackedInline): # 3rd Level model = TocArticle sortable_field_name = "position" class TocSectionInline(nested_admin.NestedStackedInline): # 2nd Level model = TocSection sortable_field_name = "position" inlines = [TocArticleInline] class TableOfContentsAdmin(nested_admin.NestedModelAdmin): # 1st Level inlines = [TocSectionInline] admin.site.register(TableOfContents, TableOfContentsAdmin) Now, how deep can django-nested-admin have nested inlines? Only 3 levels? -
I don't want drf ValidationError response string boolean
raise ValidationError(detail={"something": True}) Response: { "something": "True" } Looging for: { "something": true } -
The view main.views.home didn't return an HttpResponse object. It returned None instead
Okay so I looked through a few different slack posts on this ValueError, but it seemed most of them had to do with not returning render which it seems like I am doing that correct..? I am sure it has to do with my if statements, just not sure what exactly or how to set the code up correctly so I can check the form request to the browser. views.py: from http.client import responses from django.shortcuts import render from .forms import SearchUser from .search import search def home(request): if request.method == "POST": form = SearchUser(request.POST) if form.is_valid(): form.cleaned_data["name"] else: return render(request, "main/home.html", { 'form': SearchUser(), # Reference to form 'userid': search(request), # 'mmr':NA, }) search.py: import requests def search(request): data = requests.get( f"https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/{name}/NA1?api_key=RGAPI-d1224a2c-9130-45ff-8c05-0656d56d105f") return data.json()['puuid'] urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.home, name=""), #path("", views.search, name=""), ] home.html: {% extends 'main/base.html'%} {% block content %} <h2>Valorant Ranked Checker</h2> <form method="post" action=""> {% csrf_token %} {{form}} <button type="submit" name="search"> Get rank </button> </form> <p><strong>{{userid}} - {{mmr}}</strong></p> {% endblock %} -
Django & React implementation using Google OAuth2 does not work with csrftoken
I have implemented Django backend for Google OAuth2 signin/signup process for user authorization. The mechanism is triggered from React UI. The user can successfully signup using Django backend and I can see the associated users are created in Django Admin. However, when I try to use the same user information through React UI, "me" API call cannot access to the Django user that has signed in. But direct Django call through browser and curl command works fine. The following command works fine with backend call : curl -X GET --header "Cookie: csrftoken=M1kFFNataWZcbckfdrqUEiXuRRsSRwYKKCH4XvENUyWnLE9xnSMHe7DiaUcDBRU6; sessionid=p156z2d5gy9cwamojxvmxbopg84p99v6" http://localhost:8000/registration/me/ Below is Django settings for Cors and CSRF : CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_ALL_ORIGINS=True CORS_ALLOW_CREDENTIALS = False CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ] CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_HTTPONLY = False CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_AGE = None CSRF_COOKIE_DOMAIN = 'localhost' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True Below is rest framework settings : REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } The API call from Django for "me" : @api_view(['GET']) def current_user(request): from rest_framework.permissions import IsAuthenticated permission_classes = [IsAuthenticated] user = request.user if user.is_authenticated: return Response({ 'username' : user.username, … -
is there anyway to add multiple class to cart in django?
I'm creating a e-commerce website in django i want to add product class and variation class to my cart is there anyway to do this? I checked the similar questions but i couldn't find any solution I Tried to Models.py class Product(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name='Kategori') name = models.CharField(max_length=200,null=True,verbose_name='Başlık') class MainVariation(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name='Kategori',blank=True,null=True) gender = models.ManyToManyField(Gender,verbose_name='Cinsiyet',blank=True,null=True) mainvar = models.ForeignKey(Product,on_delete=models.CASCADE,verbose_name='Ana Ürün') name = models.CharField(max_length=200,null=True,verbose_name='Başlık') Cart.py from django.conf import settings from Products.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): for p in self.cart.keys(): self.cart[str(p)]['product'] = Product.objects.get(pk=p) for item in self.cart.values(): item['total_prices'] = int(item['product'].price * item['quantity']) yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def add(self, product_id, quantity=1, update_quantity=False): product_id = str(product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 1, 'id': product_id} if product_id in self.cart: self.cart[product_id]['quantity'] += int(quantity) if self.cart[product_id]['quantity'] == 0: self.remove(product_id) self.save() def remove(self, product_id): if product_id in self.cart: del self.cart[product_id] self.save() def get_total_cost(self): for p in self.cart.keys(): self.cart[str(p)]['product'] = Product.objects.get(pk=p) return int(sum(item['product'].price * item['quantity'] for item in self.cart.values())) def get_item(self, product_id): if str(product_id) in self.cart: return self.cart[str(product_id)] else: return … -
ValueError: the field was declared with a lazy reference but app doesn't provide model
I know there are several similar questions. But I don't understand where I need to change my dependencies. And I'm very afraid to change it, because I don't understand it. I have a lot problems when I created local database. I solved all isues. Then I go to production database. And have problems again. I solved it. And then I returned to development. And again I had issues. I think my problem is changing event.Team for production, when in development I have Team (from mission.models import Team). When I solved issues in production, I went to development database and I had: ValueError: The field accounts.Member.id_team was declared with a lazy reference to 'event.team', but app 'event' doesn't provide model 'team'. class Member(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True) id_team = models.ForeignKey("event.Team", null=True, blank=True, on_delete=models.SET_NULL) this is my showmigration files: [X] 0052_alter_member_id_user [ ] 0053_alter_member_id_user [ ] 0054_remove_member_id_team [ ] 0055_remove_member_id_user [ ] 0056_remove_goal_id_member [ ] 0057_member_id_user [ ] 0058_remove_member_id_user [ ] 0059_member_id_team_member_id_user [ ] 0060_remove_member_id_user [ ] 0061_delete_member [ ] 0062_member [ ] 0063_delete_member [ ] 0064_member [ ] 0065_member_id_team_member_id_user [ ] 0066_remove_member_id_team [ ] 0067_member_id_team Can you please advice. In what migration files I need to write some … -
Django Permissions traversal across multiple foreign keys
I have 4 core entity models: User Can be an Owner or Participant on a Collection Collection Recipe A recipe has a foreign key to a collection Steps A step has a foreign key to a recipe In order to enable the above, I think I need a model for each of them as well as a model (let's call it CollectionContributor) with the following fields: contributor - this would be a foreign key to the user model collection - this would be a foreign key to the collection On the Collection then, I'd add a many to many field that looks like this: class Collection(models.Model): ... contributors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='CollectionContributor') Now, let's say I want to provide a page that lists all "step" across all recipes. If I want to limit that view to those steps that are part of recipes that are part of collections that the user has access to, how would I do that. Essentially, how can I manage permissions that require traversal of multiple foreign keys? I assumed it might be something like the following. But it seems terribly inefficient, and could lead to performance issues if entities go several layers deep. Is this the … -
Get json data from from django-rest-api with react frontend into a variable
I am new to react and javascript. I am trying to get some data INTO A VARIABLE in react from django-rest API. I am using this variable in another function using react-beautiful-dnd. I have the API set up and CORS also set up. This is the output in http://127.0.0.1:8000/api/column_names/ I am trying to get this as a json object in react frontend. const getData = async () => { let response = await fetch("http://127.0.0.1:8000/api/column_names/"); let data = await response.json(); console.log(data); // line 29 return data; }; let columnFromBackend = getData(); console.log(columnFromBackend); // line 34 This is the output Is there any way to get this data into the variable columnFromBackend I am trying to get the equivalent of this value. let columnFromBackend = { idone: { name: "In progress", items: [{ id: "hjnmkjnh", content: "first" }], }, idtwo: { name: "Todod", items: [], }, }; If I declare the variable directly like this, then this is the output that I am getting and what I am trying to get from the api. -
Why I have this error message, and How can correct it?
cart.js:19 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) updateUserOrder @ cart.js:19 (anonymous) @ cart.js:12 VM2104:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 function updateUserOrder(productId, action){ console.log('User is logged in, sending data....') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body: JSON.stringify({'productId':productId,'action:':action}), }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) }); } -
Prevent Django from appending postgress timestamptz to query when importing data
I have a managment command for django, to import data from a csv file into an app. This management command works mostly fine, except that a date field in my model which has a default value for 'now' can't seemingly be overridden. This is the code for my 'load_data' management command: from django.db import connection import csv from django.core.management import BaseCommand from myapp.models import myitem class Command(BaseCommand): help = 'Load a csv file into the database' def add_arguments(self, parser): parser.add_argument('--path', type=str) def handle(self, *args, **kwargs): path = kwargs['path'] with open(path, 'rt', errors='ignore') as f: reader = csv.reader(f, dialect='excel') for row in reader: print ("\n22: "+row[0]+"\n") print("\nQuery: "+connection.queries) print ("\n\n24: "+row[1]+"\n") print ("\n24: "+row[2]+"\n\n") MyItem.objects.create( itemProp1=row[0], itemProp2=row[1], itemDate=row[2], ) The code mostly works, except trying to import the itemDate field, instead of being assigned via the value in the row being imported, django wants to set the time to now. The following error is generated, which is: django.db.utils.DataError: value too long for type character varying(20) The connection query being used when trying to import sample data, obtained via my printing it out above, is: INSERT INTO "myapp_myitem" ("itemProp1", "itemProp2", "itemDate") VALUES (\'heavy\', \'green\', '\'2022-06-23T00:00:00+00:00\'::timestamptz) The associated model I am trying to … -
Django views - Using requests
If I have a views.py function like this one right here: #imports env = environ.Env() environ.Env.read_env() def stocks(request): input_ticker = request.POST['ticker'] response = requests.get(f"https://cloud.iexapis.com/v1/stock/" + input_ticker + "/quote?displayPercent=true&token=" + env('API_IEX')) parsed = response.json() return render(request, 'result_api.html', {'api': parsed}) How can I scale up the flexibility and efficienty of my code if I want to add like 10-15 similar requests? (...) response2 = requests.get(f"https://cloud.iexapis.com/anything/anything/" + input_ticker + "/anything=true&token=" + env('API_IEX')) response3 = requests.get(f"https://cloud.iexapis.com/anything/anything2/" + input_ticker + "/anything2=true&token=" + env('API_IEX')) (...) parsed2 = response2.json() parsed3 = response2.json() (...) return render(request, 'result_api.html', {'api': parsed, 'api2': parsed2, 'api3': parsed3 , }) It would be pretty munch repeated, so I think there need to be a better way to solve this here. PS: I am more into Django than Python atm. Probably I miss something obvious out here :D -
how to mock the response from a library api in pytest
Writing an pytest for a function that is making api call using an installed package. How do you mock the response from the api response? This is how the function looks like import hubspot from pprint import pprint from hubspot. import ApiException def get_clicked_events(): client = hubspot.Client.create(api_key="YOUR_HUBSPOT_API_KEY") try: api_response = client.events_api.get_page(limit=100, event_type="clicked") pprint(api_response) return api_response except ApiException as e: print("Exception when calling events_api->get_page: %s\n" % e) -
Worker isns't populating some apps on Django
The worker from my django project isn't detecting some apps but other yes. All of them are in INSTALLED_APPS. And thats makeing it restarting endless. What could be it? here is the directory structure: -project -worker -pycache -init.py -celery.py -tasks.py The traceback below is getting error on bootstrapform, if I take off that from installed apps, the next module go to the traceback which is crispy_forms and so on. here is the traceback: Checking for celery... OK Starting worker using broker at redis://broker Checking for celery... OK Starting worker using broker at redis://broker self.django_setup() File "/usr/local/lib/python3.9/dist-packages/celery/fixups/django.py", line 118, in django_setup django.setup() File "/usr/local/lib/python3.9/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrapform' Postgres is up - executing command wait-for-it.sh: waiting for broker:6379 without a timeout wait-for-it.sh: broker:6379 is available after 0 seconds wait-for-it.sh: waiting for webapp:8000 without a timeout wait-for-it.sh: webapp:8000 is available after 0 seconds Traceback (most recent call … -
Django REST how to not apply default permission for get request
I don't want to apply my permission_classes for get request. I tried @permission_classes(AllowAny) but didn't work. Here is my my code: class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] @permission_classes(AllowAny) def list(self, request): if request.method == "GET": blog = Blog.objects.all().order_by("id") serializer = BlogSerializer(blog, many=True) return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) -
Django multi-table inheritance - make sure only one child exists (CheckConstraint)
How can I make sure that a parent object has only one child/type? class Property(...): class Meta: abstract = False class Flat(Property): pass class House(Property): pass class Land(Property): pass I want every property object to have none or at most one child. It can be either flat, house or land (or null). Is it possible to create a DB constraint for this? My idea was to create a constraint that checks: class Meta: constraints = [ models.CheckConstraint(check=Q(Q(flat__isnull=True) & Q(house__isnull=True)) | Q(Q(flat__isnull=True) & Q(land__isnull=True)) | Q(Q(house__isnull=True) & Q(land__isnull=True)), name="constraint")] But apparently, there are no such fields on a DB level (you can get flat by property.flat getter in Django but not in DB) EDIT: properties.Property: (models.E012) 'constraints' refers to the nonexistent field 'flat'. -
sitemaps returns NoReverseMatch at /sitemap.xml
I'm trying to add sitemaps in my application, but when i add a url that has slug, it throws me an error in http://127.0.0.1:8000/sitemap.xml Reverse for 'view-Question' with no arguments not found. 1 pattern(s) tried: ['questions/(?P[-a-zA-Z0-9_]+)/\Z'] i follow this Tutorial my urls: sitemaps = { 'static': StaticViewSitemap, } path('', views.Home, name='Home'), path('login', views.login, name='login'), path('register/', views.register, name='register'), path('Terms', views.rules, name='Rules'), path('questions/<slug:slug>/', views.viewQuestion, name='view-Question'), path('feedback/', views.PostFeedBack.as_view(), name='FeedBack'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), my sitemaps.py file: from django.contrib import sitemaps from django.urls import reverse class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'daily' def items(self): return ['Home', 'login', 'register', 'Rules', 'FeedBack', 'view-Question'] def location(self, item): return reverse(item) Thanks. -
Can django-nested-admin sort the top level items in select-to-change list in addition to inline items?
I could sort inline items with django-nested-admin as shown below: But, I couldn't sort the top level items in select-to-change list as shown below: This is the code in "models.py" as shown below: # "models.py" from django.db import models class Country(models.Model): name = models.CharField(max_length=100) position = models.PositiveSmallIntegerField("Position", null=True, blank=True) class Meta: ordering = ('position',) def __str__(self): return self.name class Province(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField("Position", null=True) class Meta: ordering = ('position',) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=100) province = models.ForeignKey(Province, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField("Position", null=True) class Meta: ordering = ('position',) def __str__(self): return self.name And, this is the code in "admin.py" as shown below: # "admin.py" from nested_admin import SortableHiddenMixin, NestedTabularInline, NestedModelAdmin from .models import Country, Province, City class CityInline(SortableHiddenMixin, NestedTabularInline): model = City sortable_field_name = "position" class ProvinceInline(SortableHiddenMixin, NestedTabularInline): model = Province sortable_field_name = "position" inlines = (CityInline,) @admin.register(Country) class CountryInlineAdmin(SortableHiddenMixin, NestedModelAdmin): sortable_field_name = "position" inlines = (ProvinceInline,) Are there any ways to sort the top level items in select-to-change list? Or, is it impossible to sort the top level items with django-nested-admin?