Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to limit FK choices based on kwargs input in Django for a form
I have a form which is for creating a booking slot. In the booking slot model there is a foreign key model to the location for that slot. #forms.py class BookingSlotForm(ModelForm): class Meta: model = BookingSlot fields = ['date','start_time', 'end_time', 'location'] #views.py class CreateBookingForm(CreateView): template_name = 'app_book/create_bookings.html' form_class = BookingSlotForm #urls.py urlpatterns =[path('create/<int:club>/', CreateBookingForm.as_view(), name="create_booking")] I want to be able to use the club id (given in the URL) to limit the choices for locations for a booking slot. For example, a club called Lambda can only see courts 4, 5 and 6 and not courts 2, 3 or 1. I have looked into "limit_choices_to" but I don't think this is the right way to do this. Help would be much appreciated -
CreateView/UpdateView to include related ForeignKey in form
I have a one-to-many relationship between two models using ForeignKey as usual, e.g.: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') I wanted to use the elegant generic CreateView and UpdateView to create/modify authors. When doing so, I would like to simultaneously edit their book list and even add books. I was hoping I could simply do: from django.views.generic.edit import CreateView from .models import * class AuthorCreate(CreateView): model = Author fields = ['name', 'books',] but it doesn't seem to be that easy and I get the exception Unknown field(s) (books) specified for Author. Is there an elegant way of doing this without writing my own view/formset? How are you dealing with such a use-case in your projects? PS: Bonus points if there is a similarly elegant solution for ManyToManyField relations. PPS: Within admin I have already found how to achieve this: class Book_InlineAdmin(admin.TabularInline): model = Book extra = 1 class Author_Admin(admin.ModelAdmin): inlines = (Book_InlineAdmin,) admin.site.register(Author, Author_Admin) -
Django URL duplication Bug
I'm developing a little application in Django and I need to add a contact form. U know, the typical send mail form. Everything works right, but when I was testing the nav bar I notice that, when I click the same route two times the route is douplicated http://127.0.0.1:8000/Contacto/Contacto Is really funny to see but I began to despair. My question is, is there any way to avoid this bug? This is how I declared the path in urls.py : path('Contacto/', views.contactPageRender, name="Contacto") This is the function that render the .html file: def contactPageRender(request): return render(request,"contact.html") And this is the html tag that drives to the URL: <nav class="navbar navbar-expand-lg navbar-light fixed-top" style="background-color: #bebebe;"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a href="Contacto" class="nav-link">Contacto</a> </li> </ul> </nav> -
Custom Wagtail admin page with fields of different models
My goal is to register and create only one Wagtail admin page where I can create/edit/see objects of the Question model, but also with the possibility of adding other fields from the other models that are related to this one through foreign keys (given that creating an instance of Question model also can create an instance of the QuestionVersion and AnswerVersion models, as shown in the models.py file: ... class Question(models.Model): filepath = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) order = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey('wiki.Article', on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "{}".format(self.id) class QuestionVersion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) slug = models.CharField(max_length=255, blank=True, null=True) title = models.TextField(max_length=255) description = models.TextField(null=True, blank=True) categories = models.ManyToManyField(Article, null=True, blank=True) approved = models.BooleanField(default=False) class AnswerVersion(models.Model): question_version = models.ForeignKey(QuestionVersion, on_delete=models.CASCADE) text = models.TextField() correct = models.BooleanField(default=False) def __str__(self): return self.text ... Right now I am registering/generating 3 pages to do the task in my wagtail_hooks.py (managing the Question model instances): ... class QuestionAdmin(ModelAdmin): model = Question list_display = ('id', 'user') class QuestionVersionAdmin(ModelAdmin): model = QuestionVersion list_display = ('question', 'title', 'description', 'categories', 'approved') class AnswerVersionAdmin(ModelAdmin): model = AnswerVersion list_display = ('question_version', 'text', 'correct') class Admin(ModelAdminGroup): menu_label = … -
why is this json string being implemented incorrectly into a django template?
So I am trying to pass some json data to a variable in a html template which will be able to be accessed globally by the client side code (for responding to an api but that isn't the point) The json is what a react app will use to parse some stored data on the server however when I pass the jsonified string to html it gives a weird result in the javascript ultimately not being able to parse the data: def get_data(request): context = {} # here the json function turns it to a json string fine context["some_data"] = json.dumps({"key": "data"}) return render(request, "ordering/somehtmlfile.html", context) <script> const menu_data = JSON.parse('{{ menu_data }}'); // I found the issue here from inspecting it in chrome // "data" variable is: '{&quot;key&quot;:&quot;data&quot;}' console.log(data); </script> Clearly this is some really weird result. I don't know if I've maybe missed some step or something but my javascript skills are really not up to standard so I'm sorry if this is a really stupid question but any help would be appreciated. -
JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0)
I'm working on a Django app and I'm trying to redirect based on a response from an API, but I can't seem to find a way to get the value of the response. This is the response: { "Body": { "stkCallback": { "MerchantRequestID": "24915-30681242-1", "CheckoutRequestID": "ws_CO_150220211305438433", "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": 1.00 }, { "Name": "MpesaReceiptNumber", "Value": "" }, { "Name": "TransactionDate", "Value": 20210215130604 }, { "Name": "PhoneNumber", "Value": } ] } } } Need help on passing ResultCode to variable. I have tried def callback(request): response = json.loads(request.body) ResultCode = response['ResultCode'] return render(request, 'callback.html') But it still throws an error, any help would be appreciated. -
Django image url redirect is going through link for HTML template rather than media file?
I have a django app, a template on which contains an image. The problem I know is that the server is trying to display the image via the redirect link from the html template rather than from the media file. Example: <tbody> {% for equipment in inventory_obj %} <tr> <td class="table-blocks">{{ equipment.id }}</td> <td class="table-blocks">{{ equipment.name }}</td> <td class="table-blocks">{{ equipment.total_quantity }}</td> <td class="table-blocks">{{ equipment.location }}</td> <td class="table-blocks"><a href= "{{ equipment.img_reference }}">IMAGE</a></td> <td class="table-blocks"> <a href="/EditInventory/{{ equipment.id }}" id="Edit-Page-Link">Edit</a> </td> </tr> {% endfor%} BUT when I add equipment.img_reference.url - the app returns an attribute error saying that no file was found. The equipment.img_reference also has a problem, when i click on the link, the app opens the image via the HTML app - url is: localhost/ViewInventory/images_uploaded/WIN_20210215_19_54_16_Pro.jpg - when it should be this: localhost/media/images_uploaded/WIN_20210215_19_54_16_Pro.jpg This is the urls.py file for the app and for the project: app: from django.conf import settings from django.conf.urls.static import static from . import views # . is from 'this app' import views urlpatterns = [ path("", views.homepage, name="home"), #name must be same as the function name in the views.py, the path('') in the urls.py of mysite looks for the same path in '' and then renders the … -
Django 3.1 and Django 3.0 Internationalization and localization
Although all the settings files are done as described in the document, meaningless multi-language change cannot be activated. Sample: from django.utils.translation import activate, get_language_info activate('fr') -
WSGIScriptAlias / /home/me/myproject/myproject/wsgi.py throws internal server error
I am having trouble linking my application to the base / (server IP or domain). But my problem is whenever I put this line in my /sites-available/project.conf and restart the apache server, the web page immediately throws from default apache page to internal server error. I want the application to run when type the base domain. This is the errors log: [Mon Feb 15 12:21:03.173931 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] mod_wsgi (pid=78014): Failed to exec Python script file '/home/me/myproject/myproject/wsgi.py'. [Mon Feb 15 12:21:03.173982 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] mod_wsgi (pid=78014): Exception occurred processing WSGI script '/home/me/myproject/myproject/wsgi.py'. [Mon Feb 15 12:21:03.174075 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] Traceback (most recent call last): [Mon Feb 15 12:21:03.174101 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/myproject/wsgi.py", line 16, in <module> [Mon Feb 15 12:21:03.174106 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] application = get_wsgi_application() [Mon Feb 15 12:21:03.174112 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Feb 15 12:21:03.174115 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] django.setup(set_prefix=False) [Mon Feb 15 12:21:03.174121 2021] [wsgi:error] [pid 78014:tid 140505444267584] [remote 111.145.95.126:37428] File "/home/me/myproject/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Mon Feb 15 12:21:03.174124 2021] [wsgi:error] [pid … -
Is it possible to include a Django url in a Pandas dataframe?
I am trying to include a Django URL in a Pandas dataframe but Django templates is not changing the url templatetag for the actual link. Reading here and there this is what I have gotten so far: This is my link that I include on each row: link = "<a href=\"{% url 'account_policies' " + "month=" + "'" + month_number + "' %}>Policies</a>" this is the url that I defined on urls.py: path( "account/<str:month>/policies/", AccountPoliciesView.as_view(), name="account_policies" ) Then I render the DataFrame as an HTML table: context['df'] = df.to_html(index=False, escape=False) Then I render the variable with the safe tag: <div> {{ df | safe }} </div> And when I inspect the element I get this: <td> <a href="{% url 'account_policies' month='01' %}"> Policies </a> </td> It is clickable but Django throws a 404. Is there a way to fix this or another way to do it? -
Cannot login to Admin panel after deploying Heroku
So I deployed a Django rest framework to Heroku and after setting up PostgreSQL, running the migrate command and also creating a superuser, I cannot seem to login into my Django admin panel. Below is my settings.py file. Django settings for ptracker project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from dotenv import load_dotenv load_dotenv() # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', 'trakkkr.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tracker.apps.TrackerConfig', 'corsheaders', # installed apps 'rest_framework', 'rest_framework.authtoken', ] AUTH_USER_MODEL = 'accounts.Account' 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 = 'ptracker.urls' CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL') 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', … -
How to upload image with ckeditor5 in django project?
Since some features of the ckeditor5 really attract me, so I want to integrate it into my django project. version By following the easiest way (for me maybe), I downloaded zip files version from the online builder so the ckeditor5 in my project looks: structure custom image upload adapter this is my custom image upload adapter, which I found from some blogs write by others class UploadAdapter { constructor(loader) { this.loader = loader; } upload() { return new Promise((resolve, reject) => { const data = new FormData(); data.append('upload', this.loader.file); data.append('allowSize', 10); $.ajax({ url: '/media/uploads/', type: 'POST', data: data, dataType: 'json', processData: false, contentType: false, success: function (data) { if (data.res) { resolve({ default: data.url }); } else { reject(data.msg); } } }); }); } abort() { if (this.xhr){ this.xhr.abort(); } } } editor creation <script> let ckdata; ClassicEditor .create( document.querySelector( "textarea[name='content']") ,{ toolbar: [ 'bold', 'italic','|','link','blockQuote', 'codeblock', 'imageupload','|','numberedList', 'bulletedList', 'insertTable', '|', 'MathType', 'ChemType', '|', 'undo', 'redo', ], // <--- MODIFIED }) .then(editor => { window.editor = editor; ckdata = editor.getData(); console.log(ckdata); window.editor.plugins.get('FileRepository').createUploadAdapter = (loader)=> { return new UploadAdapter(loader); } }) .catch( error => { console.error( error ); //end } ); </script> performance now I'm able to insert image into the … -
Django: How to renew SimpleJWT access token when token are stored in HttpOnly cookies?
I have stored the SimpleJWT access and refresh tokens in HttpOnly cookies. Now, how do I reproduce an access token from the refresh token once it expires? In React I used setTimeout() to request for new access token and it worked just fine. Now that I'm storing these as HttpOnly cookies, how do I check whether the access is valid or not and if not, create and send a new access token as HttpOnly cookie? I have this middleware where I add the tokens from cookie to Authorization middleware, is it possible to renew to token in any such middleware: class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): view_name = '.'.join((view_func.__module__, view_func.__name__)) #print(view_name) if view_name in EXCLUDE_FROM_MIDDLEWARE: return None def __call__(self, request): access_token = request.COOKIES.get('access') if access_token: request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token}' return self.get_response(request) -
Can I pass a context variable into a Django form?
I can't really seem to find the answer anywhere. Basically, I have data in my view coming from an API that I want to pass into form fields. Is that possible? -
Accessing multilevel json data in Django
I have a problem with one part of json file i need to use. json file looks more or less like that: "name1": { "item1":{ "value1": "value" "value2": "value" ... "name2": [ { "item1":[ { "value1": "value" "value2": "value" ... Values in "name1" can be easily accessible. views.py #response to string r = res.text j = json.loads(r) x = standings["name1"] y = standings["name2"] then i return x to template, and then i can iterate through data like that: {% for key, value in x.items %} but that doesn't work for "name2". "name1" is Dict, "name2" is list. In template i can't access values in name2. I have to show, both "item1" string from "name2", and all values inside "item1". How can i do that? -
Django redirect cors error even with django-corse-headers
In one of my Django views, I use a redirect to an external url like so: from django.shortcuts import redirect ... class SomeApi(generics.GenericAPIView): def post(self, request): if request.user.is_authenticated: #Do some stuff here link = #get some link return redirect(link) return Response(status=status.HTTP_401_UNAUTHORIZED) But the browser (Chrome) complains and gives the following error: Access to XMLHttpRequest at 'https://some.externalurl.com' (redirected from 'http://localhost:3000/api/some/call/') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, I have installed django-cors-headers and configured my settings as generally recommended: INSTALLED_APPS = [ ... 'corsheaders', ... ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True My front-end is written in React, but I gather this is supposed to be purely a server-side problem. Any suggestions? I have been stuck here for some time now and virtually every answer to Django CORS problems on the web ends in 'just use django-cors-headers'... I'm at a point now where I'm considering returning the url as part of a 200 response and try and redirect from the front-end. -
Deploy on `heroku` failed from different machines
I'm facing an issue with my Heroku deployment, let me explain my current stack : Local Machine 1: Here it's my old local machine which runs the same code base (Postgres/Django) under Docker and I usually used it to deploy on Heroku my app. Local Machine 2: My new laptop build and run exactly the same codebase, everything works locally but when deployed and released on Heroku I'm ending up with Error: Exec format error error without additional information. Build Process: docker login --username=_ --password="$HEROKU_API_KEY" $HEROKU_REGISTRY docker build --build-arg "${HEROKU_REGISTRY}/my_app/web" -f backend/Dockerfile backend docker push "$HEROKU_REGISTRY/my_app/web" Deploy process: heroku container:login heroku container:release web --app my_app -
Django UnicodeDecodeError after migrating to python 3.6
I am migrating project from django 1.11 to django 2 and have the following problem. After migration from python 2.7 to python 3.6 on django 1.11 there are a lot of UnicodeDecodeError's when im trying to get some data by the ORM. For example: class JournalName(models.Model): id = models.AutoField(primary_key=True) par_id = models.ForeignKey('Journal', db_column='par_id') parent = models.CharField(max_length=255) name = models.TextField(blank=True, db_column=u'name') lang = models.CharField(max_length=10, blank=True) class Meta: db_table = 'journal_name' def __str__(self): return self.name following print : print(JournalName.objects.all()) results with error: UnicodeEncodeError: 'ascii' codec can't encode character '\u0142' in position 768: ordinal not in range(128) Project is using MySQL database with utf8. I was trying to debug this but i have no idea what could cause the problem. On python 2.7 everything works ok so maybe there is something left in code that i should change compared to py2? I had to delete some option in db settings which caused other errors but maybe it has something with this: 'OPTIONS': { "init_command": "set names latin1;", } -
How to Link a template with the url of a class-based-view?
I'm trying to create a link <a> that redirects me to an url of a view DeleteView. I want that link to be in the template of my app. By clicking on that link you will get redirected to the url of the DeleteView. Here's the DeleteView: class imagenDelete(DeleteView): model = imagen def get_id(self, request): getall = imagen.objects.all() Here's the urls.py: urlpatterns = [ path('', views.galeria, name='galeria'), path('delete/<int:pk>', views.imagenDelete.as_view(), name='deletegaleria'), ] Here's the link im trying to create in the template of my App: <a style="font-size: 3rem;" href="{% url 'deletegaleria' pk %}">Click to delete</a> The problem is that in the url i must pass the id of the image that you want to delete. If i'd write it like this {% url 'deletegaleria' 14 %} it works, te link is shown in the template and it redirects you to the url to delete the image with id = 14. If i'd do it like this: {% for on in getall %} <a style="font-size: 3rem;" href="{% url 'deletegaleria' o.id %}">Click to delete</a> {% endfor %} This doesn't give me any error but doesn't show the link in the template. And if i do this way {% url 'deletegaleria' pk %} which … -
Why am I getting TemplateSyntaxError at 'bootstrap4' is not a registered tag library?
I'm making my way through the Django project in Python Crash Course, and I've run into the following error: 'bootstrap4' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 {% load bootstrap4 %} 2 3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6 <meta charset="utf-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8 <title>Learning Log</title> 9 10 {% bootstrap_css %} 11 {% bootstrap_javascript jquery='full' %} I've included it in my Installed apps, as seen: INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Third party apps. 'bootstrap4', # Default Django apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And it appears fine in my base.html file too: {% load bootstrap4 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Learning Log</title> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border"> <a class="navbar-brand" href="{% url 'learning_logs:index'%}">Learning Log</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'learning_logs:topics'%}">Topics</a> </li> </ul> <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li class="nav-item"> <span class="navbar-text">Hello, {{ user.username }}.</span> </li> <li … -
Unsupported lookup 'xx' for CharField or join on the field not permitted
I am trying to get a list created by a user with an AJAX GET request. However, my filtering is returning this problem: Unsupported lookup 'user' for CharField or join on the field not permitted. I'm not sure what is going wrong here. Here is my models: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) class Meta: unique_together = ['list','venue'] Here is the views.py: # dashboard def get_userlists(request): template_name = '/testingland/dashboard/' username = None if request.user.is_authenticated: username = request.user.username print(username) list = request.GET.get('userlist', None) qs = UserList.objects.filter(list_name__user=username) return qs And FWIW here is the ajax call: const showUserLists = function(){ document.getElementById("userLists") console.log('The Space Exists') $.ajax({ type: 'GET', url: '/electra/get_userlists/', data: { }, success: function (data) { console.log(data); } }); }; Traceback: Traceback (most recent call last): File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users//Desktop/Coding/anybody/anybody1/testingland/views.py", line 117, in get_userlists qs = UserList.objects.filter(list_name__user=username) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, … -
how to create a model for following requirements
I have profile model, it have multiple fields like passing, receiving, shooting. Then each fields have 4 section like(Right, Left, Top, Bottom). How to store the 4 different value for the every single field. -
How to read dropdown selection in Django admin form and perform particular action based on that
i'm working on a Django project for Complaint Management System, in which there is one model to add complaints. Inside that form there is one dropdown menu to select from various options like Pending, Rectified, Under Observation and so on as shown below. Dropdownselection image Now here i want as soon a user select "Rectified" option from dropdown menu a Date Field become visible or popup in front of dropdown to let user to select Date of rectification of fault. Please help or guide me how can i achieve this operation inside my Django admin form. Thanks -
How to deploy a django/gunicorn application as a systemd service?
Context For the last few years, I have been only using docker to containerize and distribute django applications. For the first time, I am asked to set things so it could be deployed the old way. I am looking for a way to nearly achieve the levels of encapsulation and automation I am used to while avoiding any pitfalls Current heuristic So, the application (my_app): is build as a .whl comes with gunicorn is published on a private Nexus and can be installed on any of the client's server with a simple pip install (it relies on Apache as reverse proxy / static files server and Postgresql but this is irrelevant for this discussion) To make sure that the app will remain available, I thought about running it as a service managed by systemd. Based on this article, here is what /etc/systemd/system/my_app.service could look like [Unit] Description=My app service After=network.target StartLimitIntervalSec=0[Service] Type=simple Restart=always RestartSec=1 User=centos ExecStart=gunicorn my_app.wsgi:application --bind 8000 [Install] WantedBy=multi-user.target and, from what I understand, I could provide this service with environment variables to be read by os.environ.get() somewhere in /etc/systemd/system/my_app.service.d/.env SECRET_KEY=somthing SQL_ENGINE=somthing SQL_DATABASE=somthing SQL_USER=somthing SQL_PASSWORD=somthing SQL_HOST=somthing SQL_PORT=somthing DATABASE=somthing Opened questions First if all, are there any obvious pitfalls? … -
is there any solve to my problem with Django rest framework login within viewset
AttributeError at /api/login/ 'ObtainAuthToken' object has no attribute 'request' Request Method: POST Request URL: http://localhost:8000/api/login/ Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'ObtainAuthToken' object has no attribute 'request' Exception Location: C:\Users\Ahmed\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\authtoken\views.py, line 45, in get_serializer_context Python Executable: C:\Users\Ahmed\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 this is my problem and I used this code in view class LoginViewSet(viewsets.ViewSet): serializer_class = AuthTokenSerializer def create(self, request): return ObtainAuthToken().post(request) login is not working can any one tall me what is the proble