Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting Django APIs with Celery, Redis and ELK on AWS
I need some suggestions with the architecture of our application. The details are as follows: The application is being written in Django and hosted on AWS. We are using RDBMS as PostgreSQL and the ELK Stack (Open Source based, not the one provided by AWS) for storing Unstructured data for fast retrieval etc. So, my queries are: Currently we are using EC2 instances for hosting the application, but we would like to move to Serverless architecture and use AWS Fargate. Could someone please point towards how this can be done? We would like to use Celery and Redis to be used along with Django and host the same on AWS, but not 100% sure on how this can be done. How to incorporate/host the Open Source ELK on AWS? And that too along with AWS Fargate? How to use/enable the API Gateway and the Elastic Load Balancer in AWS for hosting the Django APIs? Regards, Subhash I'm unable to find a way to incorporate Celery and Redis with AWS Fargate. Also, I'm not sure if Open Source ELK can be hosted on AWS. -
FastAPI vs Flask vs Django for Machine Learning Projects with React.js as frontend?
I completed my Master's degree recently, and I now find myself with a significant amount of available time. I am eager to explore and bring Machine Learning ideas and projects to the web domain. In this regard, I would greatly appreciate valuable suggestions and recommendations for a suitable Python framework that aligns with my use case. I am looking for the best framework that allows me to seamlessly integrate Machine Learning capabilities into web-based projects. I have already gone through a lot of posts on Reddit, but nothing really speaks specifically to this topic. Thank you in advance for your insights and recommendations! -
Django deployment with Vercel error after succesful deployment: Serverless Function Invocation Failed
Tried to deploy my django project on vercel which was successfully deployed but then I get this error when I try to view my pages: [ERROR] ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Traceback (most recent call last): File "/var/task/vc__handler__python.py", line 159, in vc_handler response = Response.from_app(__vc_module.app, environ) File "/var/task/werkzeug/wrappers/base_response.py", line 287, in from_app return cls(*_run_wsgi_app(app, environ, buffered)) File "/var/task/werkzeug/test.py", line 1096, in run_wsgi_app app_rv = app(environ, start_response) File "/var/task/django/core/handlers/wsgi.py", line 131, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/var/task/django/dispatch/dispatcher.py", line 180, in send return [ File "/var/task/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/var/task/django/db/__init__.py", line 27, in reset_queries for conn in connections.all(): File "/var/task/django/utils/connection.py", line 76, in all return [self[alias] for alias in self] File "/var/task/django/utils/connection.py", line 76, in <listcomp> return [self[alias] for alias in self] File "/var/task/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "/var/task/django/db/utils.py", line 204, in create_connection backend = load_backend(db['ENGINE']) File "/var/task/django/db/utils.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/var/lang/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line … -
Django send html email with image as body
I am trying to send an html email with an image in the body using python-Django. But when I try to send the email I get the email without the image. So Tried hard coding a link to an image from the internet into my email context and the email was sent and the picture also did show up but then when i tried to send an email with a picture from my media files it wont load the picture when the user receives it. I wrote a test function to send an html email but it does not display the picture on the email. here is my code def send_html_email(subject, from_email, to_email, html_content): # Create the email message email = EmailMultiAlternatives(subject, strip_tags(html_content), from_email, to_email) email.attach_alternative(html_content, "text/html") # Send the email email.send() def send_email_with_picture(request): subject = "Example HTML Email" from_email = "sender email" to_email = ["<recipient email>"] # Retrieve the picture URL from your database email_instance = Emails.objects.get(subject="Test sending email with picture") picture_url = default_storage.url(email_instance.product1_image.name) # Retrieve the current domain current_site = get_current_site(request) domain = current_site.domain # Construct the complete absolute URL of the image picture_url = f"http://{domain}{picture_url}" # Render the HTML content with the absolute image URL html_content = … -
What is the best practice for displaying and filtering data in Django
I'm finding it difficult to find the answer to my question as the wording is too similar to how Django works! I have a simple database with a table called Records that has fields group id, project id, device_name. I want to show all the records for a particular project on a page and give the user filters to select a specific group and/or a specific device. I've no problem getting the data, connecting to foreign keys etc. At the moment I've got all the data loading and am displaying all the groups and devices for the project in select lists in a form. My idea was when they select a different item from a select list it posts the form to get the correct data. For example when they select Group1 it loads all the devices and records in group1. My question is: Is that the best way to do this? I feel this is a common use case but searching for Django filters obviously returns query filters. (The reason I'm using dropdown lists is I have limited space on the screen) Also, does anyone recommend any slick css templates or tools for making this common scenario look good? … -
POST error 403 trying to use auth token on local storage to access Django view, then display output in React component
I want to create a component that displays all the songs that were uploaded by a user. I am trying to do this by sending a POST request, which contains the user's username and the auth token from local storage, to the Django view which will filter out all the songs that were not uploaded by the user. The view should then send the list of the songs back to the component. The issue is that when I click on the page to see the user's songs, I get the POST error 403 forbidden. I suspect the issue is with the auth token because when I use a get request to get all songs from all users, not just one, it works. Here is my song list component function SongList(props) { const [songs, setSongs] = useState([]) useEffect(() => { axios.post('/api/songs/', { username: props.username }, { headers: { Authorization: `Bearer ${localStorage.getItem('authToken')}`, }, }).then((response) => { setSongs(response.data); }).catch((error) => { console.log(error); }); }, []); return ( <div> {songs.map((song) => ( <div key={song.id}> <h3>{song.name}</h3> </div> ))} </div> )} Here is my Django view, which worked normally before I added the username filter def getSongs(request): username = request.POST.get("username") songs = Song.objects.filter(username=username) return JsonResponse(list(songs), safe=False) … -
ModuleNotFoundError: No module named 'daphnedjango'
I am trying to add web sockets to my Django application. From my existing project, I starting following the Chat app found in the Daphne documentation. I installed Daphne and Channels, add daphne to the top of Installed Apps and reconfigure asgi.py exactly like the instructions. When I run the server, I get the following error. ❯ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ben/Projects/tabshare/tabshare-backend/src/tabshare_backend/venvdaphne/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Why am I getting a 405 error when my Django Stripe Checkout integration returns my success or cancel urls?
Intro I've been integrating Stripe Checkout into my django project, mainly following this tutorial. Essentially, it involves a view with some forms that submit a request (SubscriptionsView) to another view you create (CreateCheckoutSessionView) that sends a properly configured API request to Stripe and redirects to a page hosted by Stripe. If the checkout works out, it redirects to a success URL you configure (SuccessView); if the user cancels, it redirects to a cancel URL you configure (CancelView). The problem The external Stripe checkout page is working just fine; it's the success and cancel URLs that are not working. Everything was working just fine earlier, but now (as I'm on my mobile hotspot; don't know if that would somehow affect things) it's throwing an HTTP 405 error every time Stripe redirects me to the success or cancel URLs. Stuff I've checked I've checked to make sure my paths in my urls.py file are configured correctly I get the same error when I try to manually type in the two URLs that are throwing the 405. My code views.py views.py import stripe from django.conf import settings from django.http import JsonResponse from django.http import HttpResponseRedirect from django.urls import reverse from django.views import View … -
Django: A query to filter data by hour range
I am trying to run a query that gets me all the records from hour A to hour B (Example: all records saved within hour range of 23-00.) I tried using date__range and ofcourse it did'nt help here's the view def issue_report(request, pk): try: issue = Issue.objects.get(id = pk) start = issue.date_time end = issue.date_time + timedelta(minutes=30) if issue.merge == '2': pass else: issue = Issue.objects.filter(date__range = (start, end), customer = issue.customer.id, merge = '2').order_by('date_time').first() a = issue.date x = int(a.strftime('%Y')) y = int(a.strftime('%m')) z = int(a.strftime('%d')) hijri = Gregorian(x,y,z).to_hijri() dbs = [Issue] transactions = sorted( [m for db in dbs for m in db.objects.filter(customer = issue.customer.id, date__range = (start, end), merge= '1', ).order_by('date_time')], key=attrgetter('date_time') ) for tx in transactions.copy(): if tx.date_time < issue.date_time: transactions.remove(tx) transactions.insert(0, issue) return render(request, 'issue/report.html', context={'issue':issue, 'transactions':transactions ,'hijri':hijri}) except AttributeError: return HttpResponse("<h1>Change Transaction type to ``Don't Merge``.</h1>") -
Passing a variable in get()
Using CreateView, I am displaying a form that has a header set in the admin panel. I have no idea how to do it anymore because the variable set in context is not visible in html template. Otherwise, the variable is visible, but no form fields are displayed. html file: <div class="navbar"> <div class="image"> <img src="{% static 'images/logo.png' %}"> </div> <div class="text"> <h1>{{name}}</h1> </div> </div> <div class="card"> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input class="button" type="submit" value="Submit"> </form> </div> In this case, the entire form is shown correctly, but the header is not displayed (the content is empty). views.py: class ItemCreate(CreateView): template_name = 'form/additem.html' model = Parts fields = ['number', 'item'] success_url = reverse_lazy('parts_list') def form_valid(self, form): username = self.request.user.get_full_name() form.instance.user = username form.instance.desc = getDescFromDB(form.cleaned_data['number']) return super(ItemCreate, self).form_valid(form) def get(self, request): match checkUserGroup(self.request.user): case "Service": return redirect("/") case "Shop": context = { 'name': getHeader('PartsForm') } return super().get(request, context) In this case, the header displays correctly, but the form does not display (no form field is visible). views.py: class ItemCreate(CreateView): template_name = 'form/additem.html' model = Parts fields = ['number', 'item'] success_url = reverse_lazy('parts_list') def form_valid(self, form): username = self.request.user.get_full_name() form.instance.user = username form.instance.desc = getDescFromDB(form.cleaned_data['number']) return super(ItemCreate, … -
Having issues with static file storage when deploying a django 4.2 project
I am having issues with deploying a django 4.2 project. When I push it to Heroku I get an application error that reads, "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail." When I inspect the logs I believe the issue is boiling down to this, " django.core.exceptions.ImproperlyConfigured: STATICFILES_STORAGE/STORAGES are mutually exclusive." I believe I have done something wrong in my settings.py file as the tutorial I was watching used an older version of Django and there were updates made to the syntax on define storage in settings.py in this version of Django. However, I am confused because I am not using "STATICFILES_STORAGE" anywhere. I tried to follow along with the tutorial while also reading the new documentation to handle this correctly. I must have used some old syntax, but am unsure where I did that. Here is my settings.py from pathlib import Path import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
Difficulty in dealing with response from promise in React frontend
I'm having a hard time getting actual values from Django objects I created using API calls on the React frontend (and I believe my issue is with frontend). I'm trying to set an array to values from an API response to then be displayed on the frontend. I'm fairly new to this stuff so I apologize if I leave out something relevant It seems, based on console logs I've done, that an array I create to eventually use to display these things gets populated with something but not what I'm expecting. In my component I have this provisions array that I am referencing and use to display values on the frontend: this.state = { provisions: [], }; Next in the componentDidMount() method I call the method that will make the API call: componentDidMount() { this.provisionsRequest(); } and then the provisions request method: provisionsRequest(){ Api.getProvisions().then((resp) => { this.setState({ provisions: resp, }); }); } For the time being, I'm just checking the length of the provisions array, which happens to be 6. The issue though is that in the console log once I deploy the testing site, its an array of 6 'category' objects with null values: Array(6) 0: {category: null} 1: … -
Modifying a table in django admin panel by editing another table
I want to be able to delete some elements in a model after editing the name of a field and answering a question. This are my models: class Cursuri(models.Model): id_curs = models.CharField(max_length=50) titlu_curs = models.CharField(max_length=50) an = models.IntegerField() semestru = models.IntegerField() credite = models.IntegerField() class Meta: verbose_name_plural = "Cursuri" class Note(models.Model): nr_matricol = models.CharField(max_length=20) id_curs = models.CharField(max_length=50) valoare = models.IntegerField() data_notare = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name_plural = "Note" When i edit the name of the field "titlu_curs" i want to delete the elements from "Note" that have the same "id_curs" as the one modified in "Cursuri" I tried doing this: class CursuriAdmin(admin.ModelAdmin): list_filter = ("an","semestru","credite", ) list_display=("id_curs","titlu_curs","an","semestru","credite",) def change_view(self, request, object_id, form_url='', extra_context=None): if request.method == 'POST': new_name = request.POST.get('titlu_curs') old_name = Cursuri.objects.get(id=object_id).titlu_curs id_curs = Cursuri.objects.get(id=object_id).id_curs Cursuri.objects.get(id=object_id).titlu_curs=new_name if new_name != old_name: return render(request,'vizualizare/confirmare_subiect.html',context={ 'new_name': new_name, 'old_name': old_name, "id_curs":id_curs, } ) return super().change_view(request, object_id, form_url, extra_context) and this is the template: {% extends 'base.html' %} {% block content %} <form action="admin/vizualizare/cursuri/<int:pk>/change" method="POST"> {% csrf_token %} <h2>Is the new subject "{{ nume_nou }}" related to the previous subject "{{ nume_vechi }}"?</h2> <input type="submit" value="Yes, it is related" name="Yes"/> <input type="submit" value="No, it is not related" name="No"/> </form> {% endblock %} I … -
django saving the wrong time in database
so it's my how I updated my code: journal.update(**new_) and new_ is a dictionary with name of the fields which I want to update but when I set the dictionary something like: new_ = {'symbol': <Symbols: btc>, 'status': 'o', 'side': 'l', 'open_date': datetime.datetime(2023, 6, 1, 11, 52), 'entry_price': '995945994564156'} it's setting the wrong time on the database for this example it's setting it as 2023-06-01 08:22:00 which is -3:30 less than what I sent... the timezone I used is UTC+3:30 and it's the field in my Journal model: open_date = models.DateTimeField(default=timezone.localtime(timezone.now()), editable=False) I tried changign the format of the datetime but still didn't work... -
Django ModuleNotFoundError "django" module
I just started back in Django (so I am back from scratch) and now I'm trying the tutorials from Django for now and I am getting moduleError thingy. For some reason, I cannot import anything thru urls.py and I haven't found a way to resolve it. Is it in the local folder I created in project? or is there something that needs to be added to PATH (which I believe I already did)? Also if I check the terminal logs, it shows this relating to "django": Any suggestions how to make them work? -
Django ModelForm Validation: Is it a security risk to set an object field before validating the dependent form data
I have two questions regarding Django ModelForm validation behavior that has perplexed me. Issue 1: Manually Assinging Model Field Before Form Validation: I have a Listing model set up for an e-commerce app: Models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.core.validators import MinValueValidator, DecimalValidator from decimal import Decimal class User(AbstractUser): pass class Listing(models.Model): CATEGORY_CHOICES = [ ("APPAREL", "Apparel"), ("COLLECTIBLES", "Collectibles"), ("COMICS", "Comics"), ("MEMORABILIA", "Sports Memorabilia"), ("SNEAKERS", "Sneakers"), ("TRADING_CARDS", "Trading Cards"), ("OTHER", "Other") ] title = models.CharField(max_length=80) description = models.CharField(max_length=800) starting_bid = models.DecimalField(max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) current_bid = models.DecimalField(default=0, max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) image = models.URLField(blank=True) category = models.CharField(max_length=40, choices=CATEGORY_CHOICES, blank=True) def __str__(self): return f"{self.title}" I am excluding current_bid from my ModelForm, as I am setting current_bid equal to the starting_bid value entered into the form by the user for each new Listing. Originally, I did this (per below) repeating the .save() command, which seemed to be a poor solution – though Django's docs does this in certain examples: views.py – Validating Form Before Manually Assigning Field def create_listing(request): class NewListingForm(ModelForm): template_name = "auctions/form_template.html" class Meta: model = Listing exclude = ["current_bid"] widgets = { "description": forms.Textarea(attrs={"placeholder": "Enter a description for your new listing..."}), "title": forms.TextInput(attrs={"placeholder": "Enter new listing title..."}), "starting_bid":forms.NumberInput(attrs={"placeholder": "Minimum … -
axios can't receive cookies from django
I have a Django API application deployed on AWS EC2 with the domain name 'https://example.xyz', and a React frontend application deployed on Netlify with the domain name 'https://example.com.tr'. In my backend application, I'm using the drf-social-oauth2 library to authenticate users with JWT and save their access_token and refresh_token in HTTP-Only cookies. When I post appropriate data to the 'https://example.xyz/api/users/login' endpoint, I can get the cookies. However, when I log in to my domain 'https://example.xyz' and send a post request to the 'https://example.xyz/api/users/login' endpoint via axios, I can't get the cookies. Everything was working smoothly on localhost before deploying. Is there anyone who can help me with this issue? Here is the code I have: Settings.py: ALLOWED_HOSTS = [ 'example.xyz', 'example.com.tr', ] # Cors Settings CORS_ALLOWED_ORIGINS = [ 'https://example.xyz', 'https://example.com.tr', ] CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken'] CORS_COOKIE_SAMESITE = None SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None # CSRF Settings CSRF_COOKIE_SECURE=True CSRF_COOKIE_HTTP_ONLY=True CSRF_TRUSTED_ORIGINS = [ 'https://example.xyz', 'https://example.com.tr', ] CustomMiddleware.py class CookieAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): token = request.COOKIES.get('access_token') refresh = request.COOKIES.get('refresh_token') if not token and refresh: data = { 'grant_type': 'refresh_token', 'client_id': os.environ.get('MAIN_AUTH_KEY'), 'client_secret': os.environ.get('MAIN_AUTH_SECRET'), 'refresh_token': refresh } headers = { 'Content-Type': 'application/x-www-form-urlencoded', } response = requests.post('https://example.xyz/api/users/login/', data=data, headers=headers) if response.status_code == … -
Docker container running but not working on local port
When I run docker run -p 8000:8000 containername the container server runs but I can't access it on localhost:8000. This is my first experience using Docker and every fix I'm finding online hasn't worked for my very simple project. I used Django and this was Dockerfile that I found online. Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PORT=8000 EXPOSE 8000 CMD ["python", "manage.py", "runserver"] For the docker-compose.yml file I wasn't sure what exactly to put so any tips would help. docker-compose.yml services: web: build: context: app target: builder ports: - '8000:8000' -
Automatic showing of objects on a website
so basically I have a table with 16 objects. I want to show only four of them on my website and want it to automatically rotate every week to another four and so on. I was thinking maybe a cronjob would do it, but I rather ask here before I take any action. Here is my models.py class Liturgicketexty(models.Model): id = models.AutoField(primary_key=True) text = models.CharField(max_length=45) url = models.URLField(max_length=200, blank=True, null=True) class Meta: verbose_name_plural = 'Liturgické texty' def __str__(self): return self.text and here is the part in html where I use this table. <div id="table"> <table> <thead> <tr> <th>Čtení na neděli</th> </tr> </thead> <tbody> {% for l in liturgicketexty %} <tr> <td><a href="{{ l.url }}">{{ l.text }}</a></td> </tr> {% endfor %} </tbody> </table> </div> If someone needs it. Like I said. I tried to research some solution, but found nothing promising. If you find or know something I will be more than grateful. -
Django database error when checking exist email on databese mongodb using djongo engine
I made a function to check if email is exist on database, but after accessing on browser with email that already exist in database it show database error but the connection with database isn't the problem. How to solve it? url: http://127.0.0.1:8000/api/check-email/?email=adrianbadjideh02@gmail.com error: DatabaseError at /api/check-email/ Request Method:GETRequest URL:http://127.0.0.1:8000/api/check-email/?email=adrianbadjideh02@gmail.comDjango Version:4.1.9Exception Type:DatabaseErrorException Location:C:\Users\xdead\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\djongo\cursor.py, line 81, in fetchoneRaised during:UserApps.views.check_emailPython Executable:C:\Users\xdead\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exePython Version:3.11.3Python Path:['D:\\api_enchant', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\win32', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\win32\\lib', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\Pythonwin', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Pyt This is my code: #views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from UserApps.models import Users from UserApps.serializers import UserSerializer # Create your views here. @csrf_exempt def userApi(request, id=0): if request.method == 'GET': users = Users.objects.all() user_serializer = UserSerializer(users, many=True) return JsonResponse(user_serializer.data, safe=False) elif request.method == 'POST': user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == 'PUT': user_data = JSONParser().parse(request) user = Users.objects.get(userid=user_data['userid']) # Updated here user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update", safe=False) elif request.method == 'DELETE': user = Users.objects.get(userid=id) # Updated here user.delete() return JsonResponse("Deleted Successfully", safe=False) @csrf_exempt def get_user(request, … -
How to display selected choices from a field of a Django ModelForm, on the basis of attribute value of choice object?
As part of a Django web app, I am working on a page that would show the user a list of jobs that can be filtered by category and/or subcategory. Each category has several subcategories, each subcategory has only one category. A job can have several categories/subcategories. So, the idea is to get a filtering form that looks like in the image below: Below is what I have tried so far. In models.py: class Category(models.Model): name = models.CharField(max_length=30, default='') class Meta: verbose_name_plural = u'categories' def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=30, default='') category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) class Meta: verbose_name_plural = u'subcategories' def __str__(self): return self.name class Job(models.Model): title = models.CharField(max_length=150, null=True, blank=True) categories = models.ManyToManyField(Category, null=True, blank=True) subcategories = models.ManyToManyField(Subcategory, null=True, blank=True) def __str__(self): return self.title In forms.py: class JobModelForm(forms.ModelForm): class Meta: model = Job fields = ['categories', 'subcategories'] widgets = {} for field in fields: widgets[field] = forms.CheckboxSelectMultiple In HTML template: Method 1: <form method="get"> {% csrf_token %} {% for category in form.categories %} <div> {{ category }} {% for subcategory in form.subcategories %} <div style="text-indent: 2em"> {{ subcategory }} </div> {% endfor %} </div> {% endfor %} <input type="submit" value="Search"> </form> Because the subcategories are … -
How to make a checkbox inside ModelMultipleChoiceField filled depending on the value in the DB Django
The Plugins model contains information about existing plugins. The UserPlugins model contains summary information about which user has which plugins activated, the activation of the user's plugins depends on the isActive field. IisActive field has the value True or False, depending on whether the user has activated the plugin or not. How do I change the checkbox value to checked in ModelMultipleChoiceField if isActive is True in the DB? models.py class Plugin(models.Model): plugin_name = models.CharField(null=False, blank=True) plugin_description = models.TextField(null=True, blank=True) isDisplay = models.BooleanField(default=True) def __str__(self) -> str: return f"{self.plugin_name}" class UserPlugins(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plugins = models.ForeignKey(Plugin, on_delete=models.CASCADE) isActive = models.BooleanField(default=True) forms.py class UserPluginForm(forms.Form): model = UserPlugins fields = ['plugins', 'isActive'] plugins = forms.ModelMultipleChoiceField( queryset=Plugin.objects.all(), widget=forms.CheckboxSelectMultiple(), ) I tried using initial in views, but in the end nothing worked. When going to another page and returning back, the values are reset views.py def userPluginsSettings(request): form = UserPluginForm(request.POST, initial={ 'plugins': [idx for idx in UserPlugins.objects.all()] }) if request.POST.get('plugins'): plugins_id_list = request.POST.getlist('plugins') plugins = UserPlugins.objects.all() for plugin in plugins: if str(plugin.plugins_id) in plugins_id_list: plugin.isActive = True else: plugin.isActive = False plugin.save() context = {'form':form} return render(request, "profile/plugin_list.html",context) template.html <form method="POST" class="home_main_unit" style="flex-direction:column;"> {% csrf_token %} {{ form.plugins }} <input type="submit" name="submit_btn" … -
NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z']
I'm getting this error: NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z'] For this line in my template: . When I am trying to print it to the screen ({{ subject.list.0.id }}) it prints the id without any problem, but for some reason when I am trying to pass it here <a href="{% url 'story' id=subject.list.0.id %}">, it doesn't work. the url: path("story/<int:id>", views.story, name="story"), the view: def story(request, id): story = Story.objects.get(id=id) last_post = story.posts.all()[::-1][0] return render(request, "story.html", { "posts": story.posts.all(), "deadline": last_post.deadline, }) The page view: def index(request): user = User.objects.get(id=request.user.id) user_genre = user.genres.all() stories = [{'list': Story.objects.order_by("-likes").all()[0:20], 'popular': 'true'}, {'list': Story.objects.all()[::-1][:20], 'new': 'true'}, ] for genre in user_genre: stories.append({'list': Story.objects.filter(genres=genre)[0:20], "genre": genre}) print(stories) return render(request, "homepage.html", { "genres": Genre.objects.all(), "user": User.objects.get(id=request.user.id), "stories": stories }) *The 'subject' in the homepage template is from {% for subject in stories %}. What can be the problem? What am I missing? I will appreciate any help! -
Reverse for 'post_comment' with keyword arguments '{'kwargs': {'pk': 1}}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/\\Z']
I have this comment section that allows users to comment, but the problem I have is that I want users to stay on the same page after commenting. And that is giving me a headache about how to go about it. I wanted to redirect using 'post-detail," but because I have a slug in there, it doesn't work. The second option is to use "post_comment," and this is the error I'm getting. I need to redirect either by using post-detail or post_comment. views.py class PostDetailView(DetailView): """ show the detail of a specific post """ model = Post template_name = 'blog/post_detail.html' slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['author'] = lowercase_first_name(self.object.author) context['tags'] = self.object.tags.all() # context['comments'] = self.object.comment.all() context['comments'] = Comment.objects.filter(blog=self.object) context['pk'] = self.kwargs.get('pk') return context def post_comment(request, pk): blog = Post.objects.get(pk=pk) comment = Comment( user_comment=request.user, comment =request.POST['comment'], blog=blog) comment.save() return redirect('post_comment', kwargs={'pk': pk}) urls.py urlpatterns = [ path('', views.post_list, name='home'), path('<author_slug>/<slug:slug>/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/', views.post_comment, name='post_comment'), ] -
how to condition use with field in django using python
Why does it not ap class opportunity(models.Model): lead_id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) TYPE_CHOICES = [ ('...', '...'), ('Individual', 'Individual'), ('Company', 'Company'), ] type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='...') if type == 'Individual': name = models.CharField(max_length=200) elif type == 'Company': Company = models.CharField(max_length=200) pear field based on the selection? nothing showed up Is the condition correct?