Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error on forms when running makemigrations
I'm getting the following error when trying to make migrations for my models. This is against a clean DB so it is trying to generate the initial migrations. File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/urls.py", line 20, in <module> from . import views File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/views.py", line 7, in <module> from .forms import AppUserForm, IncomeSourceForm, AccountForm, SpouseForm, DependentForm File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/forms.py", line 32, in <module> class AccountForm(forms.ModelForm): File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 312, in __new__ fields = fields_for_model( ^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/forms/models.py", line 237, in fields_for_model formfield = f.formfield(**kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/ProjectEnv/lib/python3.11/site-packages/django/db/models/fields/related.py", line 1165, in formfield "queryset": self.remote_field.model._default_manager.using(using), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'using' This is the form in my forms.py: class AccountForm(forms.ModelForm): class Meta: model = Account fields = ['account_name','owner','account_provider','balance'] labels = {'account_name': 'Name','account_provider': 'Account Provider','balance': 'Balance','owner': 'Owner'} And here are the relevant Models in models.py: class Projectable(models.Model): class Meta: abstract = True def project_annual_values(self, years): raise NotImplementedError("Subclasses should implement this method.") def project_monthly_values(self, months): raise NotImplementedError("Subclasses should implement this method.") class AccountProvider(models.Model): name = models.CharField(max_length=64) web_url = models.CharField(max_length=256) login_url = models.CharField(max_length=256) logo_file= models.CharField(max_length=64) def __str__(self): return f"{self.name}" class Account(Projectable): account_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=15, decimal_places=2) owner = models.ForeignKey(Agent, on_delete=models.CASCADE) account_provider = models.ForeignKey(AccountProvider, on_delete=models.SET_NULL) def get_balance(self): return self.balance def get_account_type(self): … -
order_by combined column in django
I have two models who inherit from another model. Example: class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID") class A(Parent): name = models.CharField(max_length=255, verbose_name="Name") class BProxy(Parent): target = models.OneToOneField('B', on_delete=models.CASCADE) class B(models.Model): name = models.CharField(max_length=255, verbose_name="Name") My query currently looks like this: Parent.objects.all() In my serializer, I check which subclass the parent object is (hasattr(obj, 'a')) and then use either name = obj.a.name or name = obj.b.target.name for the serialized data. But now I would like to sort the queryset for the output. Normally I would use Parent.objects.all().order_by('name') here. But the name is in the subclasses. Would it be possible to combine the “name” columns of the two subclasses and then sort by them? Or is there another solution? -
Django s3 bucket upload with out admin static css and js
Is it possible to upload the files into s3 buckets in Django without uploading default django admin css, js files? all files are getting uploaded; but i need only uploaded files in S3 buckets. Is there any work around for this? Any changes to settings file that will help to achieve this ? -
How do I create Stripe-like DB ID's for Django models?
Core problem I'm trying to solve: I want to have ID's on my database models that are similar to Stripe's (i.e. of the form aaa_ABCD1234 where the ABCD1234 part is a ULID and the aaa_ part is effectively the table name (or a shortened version of it)). This feature has saved me a ton of time in debugging Stripe integrations and I'd love for users of my systems to be able to have those same benefits. However, I know taking the nieve approach and just a string as a primary key on a table is terrible for performance (mostly indexes and consequently joins as I understand it) so I want to take advantage of the built in UUID datatype in the DB to store only the ABCD1234 part in the DB and not store the aaa_ part since that will be identical for all rows in that table. Where I stand today I'm currently thinking of doing this as follows: Have a "private" field on the DB model (call it _db_id?) that is the UUID and technically the primary key on the model in the DB. Have a GeneratedField that takes the above private field and prepends the table prefix … -
How to convert query string parameters from Datatables.js, like columns[0][name] into an object in Python/Django?
I'm using DataTables.js and trying to hook up server-side processing. I'm using Django on the server. Currently, the data to Django looks like: {'draw': '1', 'columns[0][data]': '0', 'columns[0][name]': 'Brand', 'columns[0][searchable]': 'true', 'columns[0][orderable]': 'true', 'columns[0][search][value]': '', 'columns[0][search][regex]': 'false', 'columns[1][data]': '1', 'columns[1][name]': 'Sku', 'columns[1][searchable]': 'true', 'columns[1][orderable]': 'true', 'columns[1][search][value]': '', 'columns[1][search][regex]': 'false', 'columns[2][data]': '2', 'columns[2][name]': 'Name', 'columns[2][searchable]': 'true', 'columns[2][orderable]': 'true', 'columns[2][search][value]': '', 'columns[2][search][regex]': 'false', 'order[0][column]': '0', 'order[0][dir]': 'asc', 'order[0][name]': 'Brand', 'start': '0', 'length': '10', 'search[value]': '', 'search[regex]': 'false', '_': '1725412765180'} (as a dictionary) However, there's a variable number of columns and order values that might come through. So I'd like to convert all of this into a few key variables: start length search value search regex draw array/list of column objects array/list of order objects But I don't know a lot of python -
JWT token claims in Django Rest Framework
I am using rest_framework_simplejwt, and would like to add extra information to the access token returned for authorization purposes. Following along with https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html I am able to modify the access token. However I want to be able to add a claim based on the initial POSTed login. For example: curl -X POST -H 'Content-type: application/json' -d '{"username": "user1", "password": "supersecretpassword", "project": "project1"}' https://myurl.com/api/token/ I would like to be able to add project1 to the access token. Is there a way to add extra information in that manner? -
Spotify API 403 Forbidden Error When Adding Tracks to Playlist Despite Correct Token and Scopes
I'm experiencing a 403 Forbidden error when trying to add a track to a Spotify playlist using the Spotify Web API. Despite having a correctly configured token and permissions, I’m still facing this issue. Details: Spotify Client ID: 8273bf06015e4ba7a98ca3bbca70acaa Spotify Client Secret: a581f789e2f0442aa95bb33cfe0c7dcb Redirect URI: http://127.0.0.1:8000/callback Access Token Details: { "access_token": "my access token", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "my refresh token", "scope": "playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative", "expires_at": 1725396428 } Error Log: INFO 2024-09-03 20:16:02,097 cron Distributing 1 playlists to job scheduled at 2024-09-03 20:47:02.097874 for Order ID 28. INFO 2024-09-03 20:16:02,100 cron Adding track 0TT2Tzi8mEETCqYZ1ffiHh to playlist 4CeTjVTCZOFzTBdO8yaLvG ERROR 2024-09-03 20:16:02,557 cron Spotify API error: https://api.spotify.com/v1/playlists/4CeTjVTCZOFzTBdO8yaLvG/tracks: Check settings on developer.spotify.com/dashboard, the user may not be registered. ERROR 2024-09-03 20:16:02,558 cron Check if the user 31rizduwj674dch67g22bjqy7sue is correctly registered and has permissions to modify the playlist. What I’ve Tried 1- Verified Token Scopes: The token includes scopes playlist-modify-private and playlist-modify-public. 2- Checked Token Validity: The token is valid and has not expired. I also attempted to refresh it. 3- Confirmed Playlist Ownership: Ensured that the playlist is either owned by or shared with the user whose token is being used. 4- Re-authenticated: Re-authenticated and re-authorized the application to confirm there … -
ImproperlyConfigured: TaggableManager is not supported by modeltranslation
model.py from taggit.managers import TaggableManager class Blog(models.Model): tags = TaggableManager() fields.py if empty_value not in ("", "both", None, NONE): raise ImproperlyConfigured("%s is not a valid empty_value." % empty_value) field = cast(fields.Field, model._meta.get_field(field_name)) cls_name = field.class.name if not (isinstance(field, SUPPORTED_FIELDS) or cls_name in mt_settings.CUSTOM_FIELDS): raise ImproperlyConfigured("%s is not supported by modeltranslation." % cls_name) translation_class = field_factory(field.class) return translation_class(translated_field=field, language=lang, empty_value=empty_value) Can you help me buy such an error after the blog page tag loading process is completed? -
drf-spectacular not recognizing file upload type
I have a Django endpoint that takes a file upload My annotations look like this @extend_schema( request=UploadObservationalSerializer, responses={ 200: GenericResponseSerializer, 400: OpenApiResponse( response=ErrorResponseSerializer, description="Validation error or parsing error" ), 500: ErrorResponseSerializer }, description="Allow user to upload observational data" ) Here is my serializer: class UploadObservationalSerializer(BaseSerializer): calibration_run_id = serializers.IntegerField(required=True) observational_user_file_path = serializers.CharField(required=True) observational_file = serializers.FileField(required=True) def validate_observational_file(self, value): request = self.context.get('request') files = request.FILES.getlist('observational_file') if len(files) != 1: raise serializers.ValidationError("Only one observational file should be uploaded.") return value But in the Swagger, drf-spectacular lists observational_file as a String, not a File Field { "calibration_run_id": 0, "observational_user_file_path": "string", "observational_file": "string" } Why is drf-spectacular not recognizing the file field? -
How can I call delay task in zappa django
In celery I can call task with <func_name>.delay() How can I do it in zappa? I have task: @task() def task_name(): pass -
Implementations of users in django
i was face with problem in implementing users logic, i have five users with the different roles. So in that five users there is admin which have all abilities of system. so i want to add another users which is called master super user. I want to have ability to login than the other users(admin and other users). so even the system is used by the owner ( admin and others) , but i can login and check details. so how can i handle that logic ? am trying to implement but the master super user is like the admin. i want to be unique -
from myshop.shop import views ModuleNotFoundError: No module named 'myshop.shop'
[enter image description here](ht[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/65otzFwB.png)AJ3ur5i8.png)p4Ait5fgenter image description here.png)tps://i.sstatic.net/nY8mtrPN.png) Actually, this is what my project looks like, but for some reason Django doesn't see the module, I've already tried a bunch of things, but nothing helped. Maybe there is someone faced with this ? -
Heroku Django performance issues - Request Queuing
We run a Django application on Heroku, and lately we've been seeing some performance issues. We have New Relic APM add-on installed, and I can see that any time there is a peak in response times, the time is mostly spent in what New Relic calls "Request Queuing" (see attached image). enter image description here Can someone help me figure out what the problem is here? Why are requests queued? Is this a horizontal scaling issue? It does not seem like the Python app itself is Any help welcome! Kind regards, Martijn -
An error occurred while attempting to login via your third-party account in microsoft allauth callback in django
The all auth settins for microsoft is provided here. The authedication is success and getting 200 after microsoft login. [03/Sep/2024 11:44:38] "GET /accounts/microsoft/login/callback/?code=M.C532_BL2.2.U.aec38xxxxxxx0f2ee&state=fi0hMAxxxxU2K HTTP/1.1" 200 1119 Finally page show error Third-Party Login Failure An error occurred while attempting to login via your third-party account. SOCIALACCOUNT_PROVIDERS = { "microsoft": { "APPS": [ { 'client_id': '14bb4', 'secret': 'ed91f8adc68', "settings": { "tenant": "consumers", "login_url": "https://login.microsoftonline.com", "graph_url": "https://graph.microsoft.com", }, 'SCOPE': [ 'openid', 'profile', 'email', ], 'AUTH_PARAMS': { 'response_type': 'code', }, 'OAUTH_PKCE_ENABLED': True, 'TENANT': 'common', 'LOGIN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', 'TOKEN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 'GRAPH_URL': 'https://graph.microsoft.com', } ] } } The authendication and azure directry configuration is fine, no error description is available on the call back side from django allauth. i found that the same will work here - https://allauth.org/ but there is no specific description in this page. The callback function is not working after authentication success. -
How do I correctly render a django-view using Apphooks in django-cms?
I am building a project in Django CMS using version 4.1.2. Part of the project will be a news-section, for which I defined a Django model like this: # news/models.py from django.db import models from django.utils import timezone from djangocms_text_ckeditor.fields import HTMLField class Post(models.Model): title = models.CharField(max_length=200, verbose_name="Title") text = HTMLField(verbose_name="Text") user = models.ForeignKey('auth.User', on_delete=models.CASCADE, verbose_name="Author", blank=True, null=True) date = models.DateTimeField(default=timezone.now, verbose_name="Date") class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title I want this model to be a django model instead of handling it with CMS-Plugins, so that editors can manage Posts using the admin-interface and to make it easier to use things like pagination. I have a little experience with Django, but not really with Django CMS. However, on the page displaying the news-section, I also want to have a header, a sidebar and a footer that should be editable using the CMS-Toolbar. Therefore I made an Apphook - from what I understand this should allow me to integrate the news-page with Django CMS. This is what my Apphook looks like: # news/cms_apps.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.urls import path from django.utils.translation import gettext_lazy as _ from news import views @apphook_pool.register … -
Django Template: How to connect chat script passing in Django Tag with JavaScript?
I'm working on a Django project where I need to conditionally render and execute a chat script based on user cookie consent. Here's what I've got so far: In my Django template, I have the following snippet: {% if page.page_type.chat_script %} {{ page.page_type.chat_script|safe }} {% endif %} This snippet is responsible for rendering a chat script (something like chat script code) which is set via the Django admin panel. However, I only want this script to execute if the user has accepted all cookies. I already have a separate JavaScript file (cookies_configuration.js) that handles cookie consent and injects various scripts into the head or body once consent is given (it works pretty fine when I use it with normal different scripts placed in other files). Here's a simplified example of how that injection looks (a little snippet from my code): 'injections': [ { 'location': 'head', 'code': 'initGoogleAnalytics()' }, ] Now, I want to do something similar for the chat script—essentially wrap the Django template snippet in a function like initChatScript() and then call this function only after cookie consent is granted. However, I'm not sure how to dynamically include and execute this Django template code within the JavaScript function. I've … -
Django update form sending additional field using AJAX
I have Django ModelForm contains Select2 field. I'm using jquery to send AJAX request on backend depends on select2 field choosen and return updated form with additional fields replacing the previous one (same form class but with additinal kwargs). But this causes init problems with select2 as looks like updating the form "resets" event listener on that select2. Is there a way to send not whole form but particular fields as a response for further append on existing form? -
Overriding DRF ListAPIView list() method
I have a DRF Project, wich has a ListAPIView for a model called Category. This model, has a ForeginKey to itself named parent_category and with related name of subcategories. I want my URLs to behave like this: get a list of Categories with no parent: example.com/api/categories get a list of subcategories of an object with some id: example.com/api/categories/{id_here} models.py: class Category(models.Model): name = models.CharField(max_length=100) parent_category = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='subcategories') views.py: class CategoryList(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer And I have no idea how to write my urls.py. Do I need DRF routers? or Django path works fine? I don't know which to choose or how to use them for this project. I thought if i override ListAPIMixin's list() method, it would work, but I don't even know what to write in that. -
Django Search View Not Filtering by Subcategory Name
Problem Description: I'm working on a Django project where I have a Product model that is linked to a SubCategory model through a ForeignKey. I want to implement a search functionality that allows users to search for products by their title and subcategory name. Model Definitions: Here are the relevant parts of my models: from django.db import models from shortuuidfield import ShortUUIDField class Category(models.Model): cid = ShortUUIDField(length=10, max_length=100, prefix="cat", alphabet="abcdef") title = models.CharField(max_length=100, default="Food") image = models.ImageField(upload_to="category", default="category.jpg") class SubCategory(models.Model): sid = ShortUUIDField(length=10, max_length=100, prefix="sub", alphabet="abcdef") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='subcategories') title = models.CharField(max_length=100) class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name="products") subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, blank=True, related_name="products") title = models.CharField(max_length=100, default="Apple") description = models.TextField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) Search View Implementation: I have implemented the search functionality as follows: from django.db.models import Q from django.shortcuts import render from .models import Product def search_view(request): query = request.GET.get('q') if query: products = Product.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(subcategory__title__icontains=query) # Trying to filter by subcategory name ).order_by('-date') else: products = Product.objects.none() context = {'products': products, 'query': query} return render(request, 'core/search.html', context) Issue: The search by title works as expected, but filtering by subcategory name doesn't … -
Apache: UnicodeEncodeError when opening Django template file with non-ascii character in file name
In my Django app I had a bit code that would check if a template with some file name exists: from django.template.loader import get_template def has_help_page(name): """Return whether a help page for the given name exists.""" try: get_template(f"help/{name.lower()}.html") except TemplateDoesNotExist: return False return True The name argument is derived from a Django model's verbose name, and some models have verbose names that contain non-ascii characters (f.ex. "Broschüre"). When running locally or in a Docker container (via mod_wsgi), this works absolutely fine. But when I let Apache serve the app from a Debian machine (Apache/2.4.56 (Debian)), and when I request a page that would call the above function with a name that contains an Umlaut I get an UnicodeEncodeError: Traceback (most recent call last): File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/list.py", line 174, in get context = self.get_context_data() File "/srv/archiv/MIZDB/dbentry/site/views/base.py", line 1127, in get_context_data ctx = super().get_context_data(**kwargs) File "/srv/archiv/MIZDB/dbentry/search/mixins.py", line 62, in get_context_data ctx = super().get_context_data(**kwargs) … -
How does web development works?
I'm planning on creating a website for my project and this is my first time doing it. I browsed all over the internet and I learnt few things. However im not able to understand the logic of it. I'll explain what I understood and how I am going to approach it, if my understanding is wrong can anyone correct it? As far as I understand, to create a front end, I have to use HTML and css along with javascript and I am planning on using a jQuery framework for it. when it comes to back end, it is very confusing for me. but this is what I understood. I have to create a database which I'm planning on using Mysql for it. too all the data collected from the frontend should be stored there and any requested data from the frontend should be sent from the database, so for my frontend to communicate with my database which I created using MYSql it requires a API. Here I need a software architecture for which I am using RESTAPI however I dont understand the role of the architecture. so for me to build REST API I have to use a framework, … -
React-django npm errors
Folder Structure: (https://i.sstatic.net/oJ63TecA.png) Error message: (https://i.sstatic.net/FybPFJ9V.png) I am trying to implement the index.html I created with my react-django framework. I am using REST. From my understanding, I need to use this npm command but this is the error I'm getting. I attached my folder structure as well in case I am missing something there. Any ideas on how to proceed? I tried creating a package.json file which included the script for build but the error persisted. -
Unauthorized response to POST request in Django Rest Framework with Simple JWT
I am doing a project with REST API and Django Rest Framework. I currently have an issue in my post request where some of my endpoints return HTTP 401 Unauthorized, though all other get or update objects are returning correct responses. I am using -> djangorestframework-simplejwt==5.2.2. settings.py INSTALLED_APPS = [ # ... 'rest_framework_simplejwt.token_blacklist', # ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=50), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, "JSON_ENCODER": None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } main urls.py schema_view = get_schema_view( openapi.Info( title="Blog Backend API's", default_version="v1", description="This is the documentation for the backend API", terms_of_service="http://mywebsite.com/policies/", contact=openapi.Contact(email="sabab@gmail.com"), license=openapi.License(name="BDSM License"), ), public=True, permission_classes=(permissions.AllowAny, ) ) urlpatterns = [ path('admin/', admin.site.urls), path("api/v1/", include("api.urls")), path("", schema_view.with_ui('swagger', cache_timeout=0), name="schema-swagger-ui"), ] views.py class PostCommentApiView(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'post_id': openapi.Schema(type=openapi.TYPE_INTEGER), 'name': openapi.Schema(type=openapi.TYPE_STRING), 'email': openapi.Schema(type=openapi.TYPE_STRING), 'comment': openapi.Schema(type=openapi.TYPE_STRING), }, ), ) def post(self, request): post_id = request.data["post_id"] name = request.data["name"] email = request.data["email"] comment = request.data["comment"] post = api_models.Post.objects.get(id=post_id) api_models.Comment.objects.create( post=post, name=name, email=email, comment=comment, … -
Wagtailmenus does not seem to recognize the sub_menu tag in my install
First of all, all of these pages have the "Show in menu" item checked, and in my menu config, it has "Allow 3 levels of sub-navigation" selected. Apologies if I'm being short, but I lost this question the first time I tried to post it. The browser went into perpetual loading state. There is a tutorial in the first few pages of the wagtailmenus plug-in. I'm following that tutorial, which cuts off half-way through and instead turns into a tag reference manual. The docs are terrible due to that, and it's a little bit of divination studies based on bad writing. Based on the tutorial, however, I have in my config: ` INSTALLED_APPS = [ 'home', 'scripts', 'settings', 'triggers', 'tasks', 'schedules', ..... 'wagtailmenus', 'wagtail_modeladmin', # if Wagtail >=5.1; Don't repeat if it's there already ] ..... TEMPLATES = [ { .... "context_processors": [ .... 'wagtailmenus.context_processors.wagtailmenus', ], }, }, ]` I have this menu structure: -my dashboards (There are no sub-menus here.) -settings -Triggers -Scripts -Tasks -Schedules This is really just items created to get this displaying before I add additional items. I only want the sub-menus to display, but they won't do so. My templates are setup according to the … -
Django static url not seem to be loading css file
I'm actually new to Django and tried to load my theme into newly created project. I have a home.html template file placed at {APP_NAME}/templates/ directory of my Django project. The APP_NAME is called website here and projectname is dentist. Here is the structure top-level directory of project: dentist env (virtual environment) static website css templatemo_style.css images ... website templates home.html manage.py As you see the static files are placed in the static under the APP_NAME. Now here is the home.html: {% load static %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>free template one - templatemo</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="{% static 'website/css/templatemo_style.css' %}" rel="stylesheet" type="text/css" /> </head> And this is settings.py added configuration: STATIC_URL = 'static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static') ] But now the problem is whenever I load the project, the css file is not being loaded and the html is corrupted! I check the source code and it shows this link: <link href="/static/website/css/templatemo_style.css" rel="stylesheet" type="text/css" /> However it is not found and the page comes up this way: