Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create three dependent drapdowns in Django, that the second is dependent on the first, and the third is dependent on the first and the second?
In this program, the first drapdown is a field named education level, which is independent. Then there is a drapdown named field of study, which is related to the level of study. Then it has a drapdown called book, which is related to the first and second drapdown, which means the level of study and field of study. It is expected that after selecting a education level and field of study, the book drapdown will bring only the list of books that are related to this degree and field of study. -
Shopify embedded app "frame-ancestors 'none'" error
I am having some issues with my embedded app. I checked the app in incognito mode (chrome) and found that it is not loading any page. I have configured CSP headers on my django backend with django-csp with middleware (adding screenshot of the API call from XHR section from network tab. Tech Stack Frontend: React Backend: Django Inspection console prints this error: Refused to frame '' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'". I am not able to figure out the issue. I can provide more info if needed. class CSPMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Check if the request URL matches the desired prefix if request.path.startswith('/endpoint'): # Apply the CSP header for the desired URL prefix response['Content-Security-Policy'] = "frame-ancestors https://shopify-dev.myshopify.com https://admin.shopify.com;" return response -
ValueError: No route found for path 'admin/'
I'm running a Django server and encountering an error when trying to access all backend URLs. The specific error messages I'm receiving are: Exception inside application: No route found for path 'admin/'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'admin/'. HTTP GET /admin/ 500 [1.00, 127.0.0.1:54986] Exception inside application: No route found for path 'favicon.ico'. Traceback (most recent call last): File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dev/Documents/DotSlashProj/Backend/core/venv/lib/python3.10/site-packages/channels/routing.py", line 165, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'favicon.ico'. HTTP GET /favicon.ico 500 [0.84, 127.0.0.1:54986] I have a routing.py file where I define the routes for WebSocket consumers. Here's the content of that file: from django.urls import path from channels.routing import URLRouter from WS.consumers import ( CodeConsumer, WhiteboardConsumer, ChatConsumer, ) ws_application = URLRouter( [ path("ws/code/", CodeConsumer.as_asgi()), path("ws/whiteboard/", WhiteboardConsumer.as_asgi()), path("ws/chat/", ChatConsumer.as_asgi()), ] ) And here's my asgi.py file: import os from django.core.asgi import get_asgi_application from channels import URLRouter, ProtocolTypeRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack … -
Using serializer with foreign key model when creating new entry
At first, I had this serializer and it works well for GET and POST(create new entry) class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') in viewset where creating entry. class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): request.data['user'] = request.user.id #set userid serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # it makes the new entry with user return Response(serializer.data) and models.py class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Drawing(models.Model): drawing = f.FileField(upload_to='uploads/') detail = models.JSONField(default=dict) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In this casel, user is foreign key model. So I want to get the user's name,email and so on, then I changed Serializer like this. class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() detail = serializers.JSONField() user = CustomUserSerializer(read_only=True) # change here class Meta: model = m.Drawing fields = ('id','detail','drawing','user','created_at','updated_at') It also works well for get. I can get the data from CustomUser Model as user. however when POST(creating), it shows the error django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") Why does this happen and what is the user_id? -
inline many to many field inside django admin
I have a model that has a many-to-many relationship with another model. I want to have the options inline in my question model in my Django admin. That is, stacked inline is not enough for me, because I want to be able to edit all the option fields there, not just a box to add in a more beautiful way. class Option(models.Model): ... class Question(models.Model): options = models.ManyToManyField(Option) i use TabularInline and StackerInline but not enough for me. Also, I used the Django-nested-inline package, but to implement it, it is necessary to have a foreign key relationship from the options to the questions, and I don't want it to be like that. -
In django how do i keep the user logged in in websocket
In my django project, I have a page that will send http request only when it is opened for the first time, after that a websocket connection is established and all data is passed through websocket. In order to keep the user logged in, I added this logic in the sent data method. During the test, it seems to have worked, and the expiration time of the session has always been what I expected. But after a period of time (more than SESSION_COOKIE_AGE), I refreshed the page and found that I was redirected to the login interface. async def send_data(self, event=None): data = event['message'] data = self.request_data(data) self.scope["session"].set_expiry(SESSION_COOKIE_AGE) await sync_to_async(self.scope["session"].save)() dic = {'status': '1', 'msg': 'success', 'data': data} await self.send(text_data=json.dumps(dic)) I want to know why this is happening and how can I go about it -
How to make auto search without pressing the search button in django
I want to create a search function where if I enter some words, it can automatically display the corresponding results of those words without pressing the search button. Here's the html script that I made: <div class="container-fluid"> <div class="landingtext text-center" style="margin-top: -450pt; color: aliceblue;"> <h1>#SearchBook,<br> Search your book</h1> </div> <br> <main style="text-align: center;"> <div style="display: inline-block;"> <form action="{% url 'search:search' %}" autocomplete="off" method="GET"> <input type="search" id="textInput" onkeyup="callSearchAPI(event)" name="q" placeholder="Search your book..." value="{{search}}"> <button type="submit" class="btn btn-light">Search</button> </form> <div class = "dropdown" id="dropdown"> </div> </div> </main> </div> <div class="container text-center"> {% for data in data %} <div class="book-wrapper text-center"> <div class="coverpage"> <img src="{{ data.book_cover}}"/> </div> <a>{{ data.book_title|text_short }}...</a> <p> {{ data.stock }} </p> </div> {% endfor %} {% if data|length > 0 %} <div class="d-pagination"> <ul class="pagination"> {% if data.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ data.previous_page_number }}">Previous</a> </li> {% endif %} {% for ord in data.paginator.page_range %} {% if data.number == ord %} <li class="page-item active"> <span class="page-link">{{ ord }} <span class="sr-only">(current)</span> </span> </li> {% elif ord > data.number|add:'-3' and ord < data.number|add:'3' %} <li class="page-item"> <a class="page-link" href="?page={{ ord }}">{{ ord }}</a> </li> {% endif %} {% endfor %} {% if data.has_next %} … -
issue with setting dynamo db created_at field
I am trying to add a new field 'created_time' in my existing dynamodb. another field 'updated_time' field already exists. I want to set the created_time only once, when the new record is created. updated_time updates at every change in record using .save() function of pynamodb. For this purpose I am using default_for_new for created_time in my django model class. But still my created_time is updated even when updated_time updates. (they are kind of moving in sync) Below is my code: from pynamodb.models import Model from pynamodb.attributes import UTCDateTimeAttribute from datetime import datetime class MyModel(Model): id = UnicodeAttribute(hash_key=True) created_time = UTCDateTimeAttribute(default_for_new=datetime.utcnow) updated_time = UTCDateTimeAttribute(default=datetime.utcnow()) and I am using the code as def fun(key, isrecordexist): data = MyModel(id=key, updated_time=datetime.utcnow(), created_time=datetime.utcnow) if isrecordexist: data.save(MyModel.id.does_not_exist()) else: data.save() isrecordexist is a bool value that is passed if record already exist in table. I have already tried the solution in Saving object creation datetime using Pynamodb -
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 == …