Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
decorator action in generics
i need to add action decorator from rest_framework.decorators to view on generics views.py class AnswerDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsOwnerOrAdminOnly] queryset = Answer.objects.all() serializer_class = AnswerSerializer @action(['POST'], detail=True) def like(self, request, pk=None): answer = self.get_object() author = request.user serializer = AnswerReviewSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: answer_review = AnswerReview.objects.get(answer=answer, author=author) answer_review.delete() message = 'disliked' except AnswerReview.DoesNotExist: AnswerReview.objects.create(answer=answer, author=author) message = 'liked' return Response(message, status=200) urls.py from django.urls import path from . import views urlpatterns = [ path('answers/', views.AnswerCreateView.as_view()), path('answers/<int:pk>/', views.AnswerDetailView.as_view()), path('comments/', views.CommentCreateView.as_view()), path('comments/<int:pk>/', views.CommentDetailView.as_view()), path('answers/<int:pk>/like/', views.AnswerDetailView.like), ] i've tried on ModelViewSet and it works but how can i do it on generics? also i need my urls for like button look like this: urlpatterns = [ path('answers/<int:pk>/like/', <view>), ] -
Using fakeredis in a Django development settings file?
My Django settings.py file contains the following configuration options: # Caches CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } # Queues RQ_QUEUES = { 'default': { 'HOST': 'redis', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 360, }, } Both CACHES and RQ_QUEUES contain configuration details that point to a redis server. Is it possible to reconfigure these settings to point to an instance of fakeredis instead ? I have reviewed the fakeredis documentation and so far I have only seen examples where the redis connection is manually over-ridden, every time a call to redis is made. It seems to me that when running tests, it would be much more convenient to simply point the Django CACHE location directly to fakeredis. Is this possible? -
How customize chooser views and add a specific widget to a field using wagtail-generic-chooser
I want to override the basic view in the Article snippet selector, which does not display the checkbox correctly. class ArticleChooserMixin(ModelChooserMixin): def get_edit_item_url(self, item): # for Wagtail 4.x return reverse( "wagtailsnippets_app_name_article:edit", args=(quote(item.pk),) ) class ArticleChooserViewSet(ModelChooserViewSet): icon = "user" model = Article page_title = _("Choose a article") per_page = 10 order_by = "title" fields = ["title", "body", "url", "categories", "countries"] chooser_mixin_class = ArticleChooserMixin piece of code from the Article model from dal import autocomplete ... @register_snippet class Article( DraftStateMixin, RevisionMixin, index.Indexed, ClusterableModel, Orderable, SourceDataMixin, ): ... categories = ParentalManyToManyField("app_name.ArticleCategory", blank=True) countries = ParentalManyToManyField("app_name.Country", blank=True) ... FieldPanel("categories", widget=autocomplete.ModelSelect2Multiple()) FieldPanel("countries", widget=autocomplete.ModelSelect2Multiple()), ... Similar problem: https://github.com/wagtail/wagtail-generic-chooser/issues/65 View from the snippet creation how I want it to look and form elements that display the currently selected item current problem -
How can I measure code coverage of API integration tests?
In my company we have a Django project that has API endpoints. We are using Pytest as testing framework and some of our tests executing requests to such endpoints using requests.Session(). For example: The test is perform a GET request to /api/account/data content of root/dir/tests/test_api.py def test_some_api(self): client = requests.Session() response = client.get('/api/account/data') assert response.status_code == 200 When performing the request, the backend execute this function: ` root/models/account/api.py def user_data(request, format=None): """ @api {get} /api/account/data """ if request.method == "GET": return APIResponse(code=200) We would like the measure the code executed in `user_settings` by the test, but I failed to make it work. We are using: coverage==4.5.4 # forced to use an old version as we have dependencies conflict pytest-cov==2.10.1 To measure coverage I run this command from root pytest -v --cov-report html:html-report --cov=dir --cov-config=dir/.coveragerc .coveragerc - has only files to exclude I verified in backend logs that when the test runs, it execute the if block inside user_settings I have tried adding this code to conftest.py as written in coverage docs, but it still didn't measure user_settings code execution. @pytest.fixture(scope='session', autouse=True) def run_cov(): process = coverage.process_startup() source_path = os.path.join(_home_path, "/models/account") cov = coverage.Coverage(config_file='root/.coveragerc', source=[source_path]) cov.start() yield cov # Tests runs … -
Django, Unable to view certain database information
I've been working on a project and I've been stuck for over a week and haven't been able to find the solution to this problem. I'm creating a school management app. I've successfully allowed the teachers to create a schedule, allowed the students to view it and select it as part of their class. The problem I'm running into is that the teacher is not able to see the students information after they've chosen a class. For models I have: class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) englishName = models.CharField(max_length=200) studentName = models.CharField(max_length=200) studentId = models.CharField(max_length=200) birthday = models.DateField() gender = models.CharField(max_length=6) gradeLevel = models.CharField(max_length=8) since = models.DateField() duration = models.CharField(max_length=3) contactNumber = models.CharField(max_length=13, default=00000000) email = models.EmailField(max_length=200, default='address@email.com') def __str__(self): return self.studentName def index(request): data=Student context = {'form': data} return render(request, 'student-information.html', context) class Schedule(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateField(null = True, blank = True) time = models.TimeField(null = True, blank = True) duration = models.TextField(null = True, blank = True) capacity = models.PositiveSmallIntegerField(default=1) student = models.ForeignKey(Student, null = True, on_delete=models.CASCADE) def __datetime__(self): return self.date + '' + self.student def index(request): data = Schedule context = {'form': data} return render(request, 'set-schedule.html', context) For my views file I … -
How to merge Django queryset result, collecting values from matching keys?
My Views.py context['user'] = User.objects.filter(code='01').values('name', 'phone') print(context['user']) The current results are as follows: <QuerySet [{'name': 'John', 'cellphone': '1234567890'}, {'name': 'Doe', 'cellphone': '1234512345'}]> How can I get a result like this from templates? {% for u in user %} <span>name :</span> <span> {{ u.name }} / </span> <span>cellphone :</span> <span> {{ u.cellphone }}</span> {% endfor %} # want result name : John, Doe / cellphone : 1234567890, 1234512345 -
Gunicorn fails to spawn new worker, 3 hour hang between booting and exiting worker
I had a server outage overnight, these are the gunicorn logs (2 workers). [2023-02-13 22:17:30 +0000] [27553] [DEBUG] GET /users [2023-02-13 22:18:30 +0000] [30798] [CRITICAL] WORKER TIMEOUT (pid:27553) [2023-02-13 22:18:31 +0000] [30798] [WARNING] Worker with pid 27553 was terminated due to signal 9 [2023-02-13 22:18:31 +0000] [27997] [INFO] Booting worker with pid: 27997 [2023-02-14 02:27:04 +0000] [27997] [INFO] Worker exiting (pid: 27997) [2023-02-14 02:27:04 +0000] [27554] [INFO] Worker exiting (pid: 27554) [2023-02-14 02:27:04 +0000] [30798] [INFO] Handling signal: term [2023-02-14 02:27:04 +0000] [30798] [WARNING] Worker with pid 27554 was terminated due to signal 15 [2023-02-14 02:27:04 +0000] [30798] [INFO] Shutting down: Master [2023-02-14 02:28:07 +0000] [826] [DEBUG] Current configuration: config: ../config_live.py ... [2023-02-14 02:28:07 +0000] [826] [INFO] Starting gunicorn 20.1.0 [2023-02-14 02:28:07 +0000] [826] [DEBUG] Arbiter booted [2023-02-14 02:28:07 +0000] [826] [INFO] Listening at: unix:/run/gunicorn_live.sock (826) [2023-02-14 02:28:07 +0000] [826] [INFO] Using worker: sync [2023-02-14 02:28:07 +0000] [902] [INFO] Booting worker with pid: 902 [2023-02-14 02:28:07 +0000] [908] [INFO] Booting worker with pid: 908 [2023-02-14 02:28:07 +0000] [826] [DEBUG] 2 workers [2023-02-14 02:28:10 +0000] [902] [DEBUG] GET /users I'm trying to interpret the logs: "pid 27553 was terminated" - worker #1 crashed, outage starts "Booting worker with pid: 27997" - … -
Create super user in Django
In Django - Python, When I tried to create superuser with Django : Email : Password : Password : " CommandError: La valeur « » doit être soit True (vrai), soit False (faux). " I can't connect to my Django admin and create a new super user. I tried : Alter the file settings.py adding allauth. Not worked. python manage.py makemigrations and python manage.py migrate. Not worked. Someone has an idea ? -
Show querys data instead of model with django-ajax-datatable
I'm trying to show a the result of Django query using the module django-ajax-datatable. According to the documentation (Ajax datatable documentation)the attributes model und column_defs are at least needed to define the table. The problem is that I wanted to show a query based on some joins where the result is not based on a specific model but on a lot of attributes coming from different tables and even calculation which are only present in the query and in no table at all. As the model is mandatory, but I cannot/don't want to define a model, i don't know what to assign for the model. Everything a tried with generic names or datatypes etc. failed. For example: Query: query_result = (Model1.objects.filter(model2__id=3) .order_by("id") .values("id", "name", "model2__start", "model3__number", ) ) Datatable class: class ExampleDatatableView(AjaxDatatableView): """.""" model = *Shouldbeaquery* title = datatable_example initial_order = [["id", "asc"], ] length_menu = [[10, 20], [10, 20]] search_values_separator = '+' column_defs = [ #AjaxDatatableView.render_row_tools_column_def(), {'name': 'id', 'visible': True, }, {"name": "name", "visible": True, }, {'name': 'start', 'visible': True, }, {'name': 'number', 'visible': True, }, ] -
PyTest warning - RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path()
when i'm using pytest to run test cases i'm getting 10 warnings - RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^password/reset/$', PasswordResetView.as_view(), RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), RemovedInDjango40Warning: django.conf.urls.url() is deprecated in favor of django.urls.re_path(). url(r'^login/$', LoginView.as_view(), name='rest_login'), 10 warnings like this. using django==3.2.4 djangorestframework==3.12.4 pytest-django==4.5.2 tried filterwarnings in setup.cfg -
Post data along with photo to django rest with requests package
I wrote an api with django rest and I want to post data and photo with requests package. When I want to send data like this -> data = { 'name':'data', 'price':'123', 'category':1 } everything works correctly and the data is saved in the database, but when I want to send a photo along with the data, I get an error. models.py class Menu(models.Model): image = models.ImageField(upload_to="img", blank=True, null=True) name = models.CharField(max_length=100) price = models.IntegerField() category = models.IntegerField() availability = models.BooleanField(default=False) serializers.py class MenuSerializer(serializers.ModelSerializer): class Meta: model = Menu fields = ('id', 'image', 'name', 'price', 'category','availability') views.py class MenuViewset(ListCreateAPIView): queryset = Menu.objects.all() serializer_class = MenuSerializer and this is my post request with the requests package that I wrote in PyQt: class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__() url = 'http://127.0.0.1:8000/api/upload/' headers = {'Content-Type': 'multipart/form-data'} data = {'image':('chat2.png', open('chat2.png','rb'),"multipart/form-data"), 'name':'data', 'price':'123', 'category':1 } r = requests.post(url, data=data , headers=headers) if __name__ == '__main__': app = QApplication([]) window = MainWindow() app.exec_() -
i am getting server error while calling post method in my api using batch file
I am getting right result using both methods when i running my manage.py script through pycharm, but when i am running it through batch file, then i am getting server error 500 for post method. This is my batch file- @echo off cd F:/hash/hashtaggenerator/ set "VIRTUAL_ENV=F:\hash\env" if defined _OLD_VIRTUAL_PROMPT ( set "PROMPT=%_OLD_VIRTUAL_PROMPT%" ) else ( if not defined PROMPT ( set "PROMPT=$P$G" ) if not defined VIRTUAL_ENV_DISABLE_PROMPT ( set "_OLD_VIRTUAL_PROMPT=%PROMPT%" ) ) if not defined VIRTUAL_ENV_DISABLE_PROMPT ( if "" NEQ "" ( set "PROMPT=() %PROMPT%" ) else ( for %%d in ("%VIRTUAL_ENV%") do set "PROMPT=(%%~nxd) %PROMPT%" ) ) REM Don't use () to avoid problems with them in %PATH% if defined _OLD_VIRTUAL_PYTHONHOME goto ENDIFVHOME set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%" :ENDIFVHOME set PYTHONHOME= REM if defined _OLD_VIRTUAL_PATH ( if not defined _OLD_VIRTUAL_PATH goto ENDIFVPATH1 set "PATH=%_OLD_VIRTUAL_PATH%" :ENDIFVPATH1 REM ) else ( if defined _OLD_VIRTUAL_PATH goto ENDIFVPATH2 set "_OLD_VIRTUAL_PATH=%PATH%" :ENDIFVPATH2 set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%" F:/hash/env/Scripts/python.exe manage.py runserver ip address:4321 pause -
DRF: API root view doesn't list my APIs for some reasons
I have the following urls.py for an app named service where I register API endpoints: from .views import AccessViewSet, CheckViewSet app_name = "api" router = DefaultRouter() router.register(r"access/(?P<endpoint>.+)", AccessViewSet, basename="access") router.register(r"check/(?P<endpoint>.+)", CheckViewSet, basename="check") urlpatterns = [ path("", include(router.urls)), ] Below is my project's urls.py where I use it: from django.conf import settings from django.contrib import admin from django.urls import include, path from django.views.generic import RedirectView import service.urls as service_urls urlpatterns = [ path("service/", include('service.urls')), ] The APIs themselves work fine, but I cannot make them work with the DRF's default API root view. It shows an empty list of available endpoints. How do I fix this? I am not sure, but maybe it is somehow related to the regular expressions I use while registering endpoints, i.e.: r"access/(?P<endpoint>.+)". If that's the issue, then how do I go about dealing with such cases? -
django_migrations table in DB causing ValueError: Not naive datetime (tzinfo is already set)
I did lot's of try, catch on this issue and basically still not find the core problem but this is what I got for now. in the settings.py I am turning on the USE_TZ = True TIME_ZONE = 'UTC' and creating a model like below. class Plan(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100) price = models.IntegerField() description = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name when I try to makemigration for this is no problem. Here is the first migration file of Plan model class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Plan', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('code', models.CharField(max_length=100)), ('price', models.IntegerField()), ('description', models.TextField(blank=True, null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ] Now, when I try to migrate this file. There are two table created in the DB. one for django_migrations and the other is Plan model. After running migrate command. error follows. raise ValueError('Not naive datetime (tzinfo is already set)') ValueError: Not naive datetime (tzinfo is already set) first plan model causing this error. But when I delete the django_migrations table from DB. error not recurring. any idea why django_migrations causing not naive datetime error? Additionally. … -
Integrity error while running migrate to add new column in Django
Having a table that has millions of records, and wants to add a new column to that table in Django, so while running migrate, it is taking time (due to huge data) but getting failed after sometime with Error django.db.utils.IntegrityError: (1062, "Duplicate entry '2287526-softwareengineer' for key 'api_experience_entity_id_585e67e2a704aaa3_uniq'") Though the entity_id(2287526) has no duplicate entries, but i could see that this entry was updated during the time migration was running. what could be the possible solution to perform migration without affecting data and near to no downtime for system? SHOW CREATE TABLE api_experience; CREATE TABLE api_experience(idint(11) NOT NULL AUTO_INCREMENT,typevarchar(100) NOT NULL,durationvarchar(200) NOT NULL,created_atdatetime NOT NULL,updated_atdatetime NOT NULL,entity_idint(11) NOT NULL,designation varchar(100), PRIMARY KEY (id), UNIQUE KEY api_experience_entity_id_585e67e2a704aaa3_uniq (entity_id,type), KEY api_experience_599dcce2 (type), KEY api_experience_5527459a (designation), KEY api_experience_created_at_447d412d906baea1_uniq (created_at), CONSTRAINT api_entity_id_3fbe8eb2deb42063_fk_api_entity_id FOREIGN KEY (entity_id) REFERENCES api_entity (id`) ) ENGINE=InnoDB AUTO_INCREMENT=773570676 DEFAULT CHARSET=utf8 ` Have tried with running migration in low traffic in midnight but didn't help. -
Create dashboard for django 5xx errors
I want to build a dashboard for watching and tracing 5xx errors. So I need something constructed specially for this. I'm using Kibana to access my log which not contains 5xx errors. So what can I do? -
I need django inline dynamic
Basically I have this screen and according to the value selected in “metodo_pagamento” I want to display the amount of inline form, example if I select “2 Parcelas”, it shows 2 forms inline, but I wanted to do this dynamically how do I do that too to update and delete?formlike this: In this way that i did in using javascript onchange, but its dificult make update when user select other “Metodo pagamento”, anyone can help me? -
How to access uploaded images via URL in Django?
I'm building a simple blog style web app for a friend. I am using CK editor and mostly stock Django 4.1. I'm stumped in how in what would be the best approach to let the creator to upload and serve images in their posts. CK editor allows you to add images via URL and I'd like for it to be possible to the creator to upload their files to the backend and would like to know if there are best practices when it comes to this. Right now I have this: def editor_upload(request): if request.method == 'GET': form = UploadFileForm path = os.path.join(settings.STATIC_ROOT, 'files') files = os.listdir(path) return render(request, 'upload.html', {"form": form, "files": files}) if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) file = request.FILES['file'] title = str(file) if form.is_valid(): path = os.path.join(settings.STATIC_ROOT, 'files') fs = FileSystemStorage(location=path) fs.save(title, file) return redirect('/editor/upload') def open_file(request, file_name): print(file_name) return render(request, 'file.html', {"file": file_name}) in editor_upload, the user can see what files there are in the specified folder (but cannot access them yet) and there is the logic to upload new pictures to the folder. The problem comes now: I don't know how to properly access them. In open_file, the request receives the name … -
Django error trying to insert number from forms into Sqlite
I'm getting this error Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: Sistema_receita.value while trying to receive a number from this form <div class="mb-3"> <label for="dataReceita" class="form-label">Data</label> <input type="date" class="form-control" id="dataReceita" aria-describedby="dataReceita" value=""> </div> into this view def cadastrar_receita(request): if request.method == 'POST': receita = Receita() receita.date = request.POST.get('dataReceita') receita.value = request.POST.get('valorReceita') receita.professional = request.POST.get('profissionalReceita') receita.desc = request.POST.get('descricaoReceita') receita.pago = request.POST.get('pagoReceita') receita.save() and this is my model class Receita(models.Model): date = models.DateTimeField(auto_now_add=True) value = models.DecimalField(max_digits=12,decimal_places=2) professional = models.CharField(max_length=100, blank=True, null=True) desc = models.CharField(max_length=300, blank=True, null=True) pago = models.BooleanField(default=False, blank=True, null=True) I've tried using localize=True like this value = models.DecimalField(max_digits=12,decimal_places=2, localize=True) but it just gives me another error, and it doesn't matter whether I write a number like this 185,35 or 185.35, both gives me the same error I've tried using localize=True but it didn't help me -
Monkey patch disabled Sentry logging
I'm working on a Django project with Sentry attached for error logging. I want to log all outgoing HTTP requests made, so I wrote a monkey patch that modifies Python's http module. The idea was to modify the lowest level module possible so that all requests made by higher level libraries (urllib3, requests, and SDKs that use those libraries) would also be logged. Here is the patch code: def httpclient_logging_patch(): # NEEDS WORK: turning on this patch unexpectedly disables Sentry reporting. request = http.client.HTTPConnection.request getresponse = http.client.HTTPConnection.getresponse def patched_request(self, *args, **kwargs): try: method, url, body = args[:3] except ValueError: method, url = args[:2] body = kwargs.get("body") try: body = body.decode() except AttributeError: pass url_pieces = url.split("?") req_url = url_pieces[0] params = "?".join(url_pieces[1:]) stack = traceback.extract_stack() reduced_stack = traceback.StackSummary.from_list( [f for f in stack if "/venv/" not in f.filename] ) self.timestamp = datetime.datetime.utcnow() self._reporting_metadata = { "datetime": self.timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f"), "request_id": str(uuid.uuid4()), "host_name": self.host, "req_url": req_url, "method": method, "req_body": body or "", "req_parameters": params or "", "context": "".join(reduced_stack.format()), } request(self, *args, **kwargs) def patched_getresponse(self, *args, **kwargs): response = getresponse(self) latency = int((datetime.datetime.utcnow() - self.timestamp).total_seconds() * 1000) reporting_metadata = { **self._reporting_metadata, "res_code": response.code, "success": response.code < 400, "latency": latency, "res_body": "", } if settings.ENVIRONMENT … -
react-social-login How to send token facebook to django-graphql to register new user?
i have a prooject developed in django and graphene library my code in schema.py is follow: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from graphql import GraphQLError from .models import Profile from django.contrib.auth import get_user_model, authenticate, login as auth_login from django.utils.translation import gettext_lazy as _ from django.http import HttpRequest from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from allauth.socialaccount.providers.facebook.provider import FacebookProvider from allauth.socialaccount.models import SocialApp from graphql_jwt.shortcuts import get_token from .types import UserType class RegisterSocialMutation(graphene.Mutation): """ Mutation to handle social registration """ token = graphene.String() user = graphene.Field(UserType) class Arguments: accessToken = graphene.String(required=True) def mutate(self, info, accessToken): User = get_user_model() try: # Use allauth to complete the social registration app = SocialApp.objects.get(provider="facebook") request = HttpRequest() request.POST = {'access_token': access_token} request.user = AnonymousUser() adapter = + user = adapter.complete_login(request, app, None) # Login the user auth_login(request, user) # Issue JWT token for the user token = get_token(user) return RegisterSocialMutation(token=token, user=user) except Exception as e: raise GraphQLError(str(e)) class ProfileType(DjangoObjectType): class Meta: model = Profile class Query(graphene.ObjectType): profile = graphene.Field(ProfileType) def resolve_profile(self, info): user = info.context.user if user.is_anonymous: raise Exception(_('You must be logged in to see your profile')) return Profile.objects.get(user=user) class Mutation(graphene.ObjectType): register_social = RegisterSocialMutation.Field() on my file types.py import graphene from django.contrib.auth import … -
MySql database is read-only and I can't change it
I am creating an app in Django using MySql and AWS RDS to handle my database, but when I called form.save() to save my new model to the database, I got this error: OperationalError at /plan/create/ attempt to write a readonly database This is my settings.py: """ Django settings for travelApp project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CSRF_COOKIE_HTTPONLY = True # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com', "52.27.98.222", "35.166.8.118", "127.0.0.1",] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'crispy_forms', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig', ] 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 = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], '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', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) … -
Passing CHOICES to as an ID to template
As you can see the photo above, I have displayed all "CATEGORY_CHOICES" (in forms of (Groceries, Groceries) in category.html. views.py def category(request): context = {'CATEGORY_CHOICES': Category.CATEGORY_CHOICES} return render(request, 'category.html', context) def view_category(request, category_id): category = Category.objects.get(category_id=category_id) return render(request, 'view_category.html', {'category':category}) models.py class Category(models.Model): CATEGORY_CHOICES = [ ('Groceries', 'Groceries'), ('Salary', 'Salary'), ('Bills', 'Bills'), ('Rent', 'Rent'), ('Gym', 'Gym'), ('Restaurant', 'Restaurant'), ('Vacation', 'Vacation'), ('Travel', 'Travel'), ('Gift', 'Gift'), ('Investments', 'Investments'), ('Savings', 'Savings'), ('Entertainment', 'Entertainment'), ('Internet', 'Internet'), ('Healthcare', 'Healthcare'), ('Lifestyle', 'Lifestyle'), ('Insurance', 'Insurance'), ('Other', 'Other'), ] category_choices = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES) budget = models.DecimalField(max_digits=10, decimal_places=2) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) spending_limit = models.DecimalField(max_digits=10, decimal_places=2) category.html {% extends 'base_content.html' %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="row" style="width:90%"> <div class="col-sm-4 text-center my-3"> <div class="card card-block" style="height : 300px"> <div class="card-body align-items-center d-flex justify-content-center"> <h5 class="card-title">Overall</h5> <a href="" class="stretched-link"></a> </div> </div> </div> {% for item in CATEGORY_CHOICES %} <div class="col-sm-4 text-center my-3"> <div class="card card-block" style="height : 300px"> <div class="card-body align-items-center d-flex justify-content-center"> <h5 class="card-title">{{ item.1 }}</h5> <a href="{% url 'view_category' item ***this part is tricky for me*** %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} </div> </div> </div> {% endblock %} urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home_page, name ='home_page'), path('feed/',views.feed, … -
"no schema has been selected to create" when running Django tests
After creating a Django test script for my Django project which uses Postegres, I also created the migrations file. Now, when I try to run ./manage.py test apis/tests/, I got the following error: Using existing test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InvalidSchemaName: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): ... django.db.utils.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ^ During handling of the above exception, another exception occurred: Traceback (most recent call last): ... django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... -
Separate by apps in drf-spectacular
Here it is the UI i can get from drf-spectacular redoc: enter image description here As you can see the only way to know the apps is from the names: v1_foo_foodcourtrests_des v1_ord_customer_basket_li Here foo and ord are app names. But I want to have a separator or something to separate these by the app names Here is what I got so far and still no luck: https://drf-spectacular.readthedocs.io/en/latest/settings.html#example-swaggerui-settings