Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RAW SQL query how to pass date comparison
I am working with Django Raw SQL as I want to build a relatively complex query, As part of it, I have a case statement that says 'if the date on the record is < today then 1 else 0 - this works. overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw(''' SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count from app_task where taskid = "''' + taskidx + '''"''') overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw(''' SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count from app_task where taskid = "''' + taskidx + '''"''') However, when I want to swap the hard coded date for TODAY() I can't make it work. I have tried passing a python date variable into the script (td = datetime.date.today()), but it doesn't return the right results! Can anyone advise me please? -
APScheduler running multiple times for the amount of gunicorn workers
I have a django project with APScheduler built in it. I have proceeded to the production environment now so binded it with gunicorn and nginx in the proceess. Gunicorn has 3 workers. Problem is that gunicorn initiates the APScheduler for each worker and runs the scheduled job 3 times instead of running it for only once. I have seen similar questions here it seems it is a common problem. Even the APScheduler original documentation acknowledges the problem and tells no way of fixing it. https://apscheduler.readthedocs.io/en/stable/faq.html#how-do-i-share-a-single-job-store-among-one-or-more-worker-processes I saw in other threads people recommended putting --preconfig in the settings. But I read that --preconfig initiates the workers with the current code and does not reload when there has been a change in the code.(See "when not to preload" in below link) https://www.joelsleppy.com/blog/gunicorn-application-preloading/ I also saw someone recommended binding a TCP socket for the APScheduler. I did not understand it fully but basically it was trying to bind a socket each time APScheduler is initiated then the second and third worker hits that binded socket and throws a socketerror. Sort of try: "bind socket somehow" except socketerror: print("socket already exists")" else: "run apscheduler module" configuration. Does anyone know how to do it or … -
How to delete everything but the latest object in each group in Django
I want to group my model objects by three fields, and delete all objects but the youngest for each group. My model: class DataFile(models.Model): filename = models.CharField(unique=True, max_length=256) timestamp = models.DateTimeField() tile_label = models.CharField(max_length=256, blank=True) region = models.CharField(max_length=256, blank=True) resolution = models.CharField(max_length=256, blank=True) This query gives me the list of the values I want to keep: DataFile.objects.values('resolution', 'region', 'tile_label').annotate(maxfield=Max('timestamp')) The result of this is {'resolution': '30', 'region': 'SRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 9, 11, 7, 13, tzinfo=<UTC>)} {'resolution': '30', 'region': 'NRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 8, 16, 2, 8, tzinfo=<UTC>)} {'resolution': '30', 'region': 'NRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 15, 23, 5, tzinfo=<UTC>)} {'resolution': '300', 'region': 'SRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 11, 1, 13, 46, tzinfo=<UTC>)} {'resolution': '300', 'region': 'NRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 11, 5, 12, 20, tzinfo=<UTC>)} {'resolution': '300', 'region': 'NRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 18, 5, 54, tzinfo=<UTC>)} {'resolution': '30', 'region': 'SRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 5, 21, 8, tzinfo=<UTC>)} {'resolution': '300', 'region': 'SRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 18, 8, 29, tzinfo=<UTC>)} I now need to filter all DataFile objects except the one with the highest date in each group of resolution, region, tile_label, and then delete them (i.e. keep the one with the … -
Django Model with custom string id field not being deleted
I have a model with a custom string for an id. class BaseModel(Model): id = CharField( max_length=23, auto_created=True, primary_key=True, serialize=False, verbose_name="ID", default=generate, editable=False, ) When deleting, I am getting this error. Internal Server Error: /admin/sampleapp/user/ Traceback (most recent call last): File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q' The above exception was the direct cause of the following exception: response = func(self, request, queryset) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected ) = modeladmin.get_deleted_objects(queryset, request) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\options.py", line 2099, in get_deleted_objects return get_deleted_objects(objs, request, self.admin_site) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 120, in get_deleted_objects collector.collect(objs) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect return super().collect(objs, source_attr=source_attr, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 343, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 23, in CASCADE collector.collect( File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect return super().collect(objs, source_attr=source_attr, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 365, in collect sub_objs = field.bulk_related_objects(new_objs, self.using) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\contenttypes\fields.py", line 524, in bulk_related_objects return self.remote_field.model._base_manager.db_manager(using).filter( File "path\to\sampleapp\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter return self._filter_or_exclude(False, args, kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q clause, _ … -
How can I create a shortcut to go to a section on another page?
I have a book as an object and I am paginating its chapters, but, its chapters are OBJECTS, with chapter.number and chapter.story. I have a book summary with all the chapters’ numbers, but, thus summary should be a shortcut to the page, for example, book/chapter?page=5&#chapter_five. class ChapterView(DetailView): template_name = "tailwind/book_detail.html" model = Books slug_url_kwarg = "book_name" slug_field = "name" def get_object(self, queryset=None): try: return Books.objects.get(name=self.kwargs["book_name"]) except Books.DoesNotExist as e: raise Http404 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tuple_book = self.get_object().ordered_chapter().items() book = [{"chapter_number": chapter_number, "chapter_resume": chapter_resume} for chapter_number, chapter_resume in tuple_book] page = self.request.GET.get("page", 1) paginator = Paginator(book, 2) try: paginated_book = paginator.page(page) except PageNotAnInteger: paginated_book = paginator.page(1) except EmptyPage: paginated_book = paginator.page(paginator.num_pages) # just get the current page # the book is not paginated because I need to return all indexes in the template for chapter in book.object_list: if self.request.GET.get("chapter_number", None) == "a": context["chapter_page"] = chapter["chapter_number"].get_page_number() context["book"] = book context["paginated_book"] = paginated_book return context Now, this is my template, this is the part where I am returning the paginated chapters. <div> <div> {% for chapter in paginated_changelogs %} <div> <div> <h2>{{ chapter.chapter_number }} </h2> <div> {{ chapter.chapter_resume }} </div> </div> </div> {% endfor %} </div> And this is my … -
Django ASGI deployment - question about Procfile and Daphne
I've made a simple chat room application in Django, using Daphne as a web server, Channel Layers with Redis, and SQLite as a database. Now I'm trying to deploy it to Heroku. The whole project's directory looks like this: ├───Chat Room Application └───chat_project | ├───chat | ├───chat_project | ├───room |---Dockerfile |---Procfile |---requirements.txt Sorry for the design, the tree command didn't print it the way I wanted. The Chat Room Application directory is where the git repo has been initialized and where the Procfile is supposed to be in. The outer chat_project directory was generated automatically, by Django. And the inner chat_project directory is where the settings.py and asgi.py files are. chat and room are the different Django apps. Since it is an ASGI application, I use the following command to run the web server: daphne chat_project.asgi:application So the Procfile looks like this: web: daphne chat_project.asgi:application My problem is that in my current configuration, the Procfile doesn't see the inner chat_project directory. So when I deploy it, using git push heroku main , I get: === web (Free): daphne chat_project.asgi:application (1) web.1: crashed 2022/11/15 22:12:24 +0200 (~ 6s ago) And when I look at the log, I see: ModuleNotFoundError: No module … -
How to allow requests with API KEY for client application in DJANGO without user login?
I am trying to have a global API KEY where it would be mandatory for the client application to send the API key in headers to get a successful response. I intend to keep my APIs secure and not expose so much information to all public URLs by using IsAuthenticatedOrReadOnly. Even after passing the API keys from the headers if someone tries to go and get it from the network it would be harmful so can anyone help me with the better approach on how we cab secure our API's Find Below more information about what I am trying to achieve. GET /products/ HEADERS - EMPTY RESPONSE - PLEASE PASS THE API KEY TO ACCESS THE APIS GET /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - [PRO1, PRO2, PRO3, PRO4] POST /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - PLEASE PROVIDE AUTHENTICATION CREDENTIALS -
Django 4.0.1 - Deleting Instance results in `TypeError: Model instances without primary key value are unhashable`
When deleting a model instance from the admin portal, it raises TypeError: Model instances without primary key value are unhashable. Models.py from django.db import models from djongo import models as MDB_models from django.core.validators import RegexValidator from simple_history.models import HistoricalRecords import datetime,json,uuid from django.contrib.auth.models import User from ..API import Model_Notifications from ..PublicPages import colours from django.apps import apps import sys,requests def leading_zero(value:int): return "{:02d}".format(value) def GetImage(ID): IMG_APP = apps.get_model("VehicleImages","Image") QS = IMG_APP.objects.filter(id=ID) if len(QS) == 0: return None else: return QS.first() class Status(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150,default="",unique=True) icon = models.ImageField(blank=True,upload_to="StatusIcons") alternateText = models.TextField(max_length=500,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleChassis(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="",blank=True) vehicle_class = models.CharField( max_length=30, default="", blank=True, choices=[ ("MINI BUS","Mini Bus"), ("MIDI BUS","Midi Bus"), ("SINGLE DECKER BUS","Single Decker Bus"), ("ARTICULATED SINGLE DECKER BUS","Articulated Single Decker Bus"), ("DOUBLE DECKER BUS","Double Decker Bus"), ("COACH","Coach"), ("INTERDECKER COACH","Interdecker Coach"), ]) history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleModel(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO … -
Создание django-проекта
Не создается Django проект. Установил виртуальное окружение, Django (4.1.3), но при создании проекта выдает ошибку. Работаю на Macbook M1enter image description here Создавал несколько разных виртуальных окружений на разные версии Python, устанавливал разные версии Django -
Why Is Sub the Only Thing Returned in My Payload (Django pyjwt)?
So I recently just started django. I added some authentication for my backend. The issue is: when I decode my token, only the sub is returned. I'd like to know why. Here is my authentication.py file: from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import PermissionDenied from django.contrib.auth import get_user_model from django.conf import settings import jwt User = get_user_model() class JWTAuthentication(BasicAuthentication): def authenticate(self, request): header = request.headers.get('Authorization') if not header: return None if not header.startswith('Bearer'): raise PermissionDenied({'message': 'Invalid authorization header!'}) token = header.replace('Bearer', '') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) user = User.objects.get(pk=payload.get('sub')) except jwt.exceptions.InvalidTokenError: raise PermissionDenied({'message':'Invalid token'}) except User.DoesNotExist: raise PermissionDenied({'message':'User not found'}) return (user, token) Here is my model: class CustomUser(AbstractUser): username = models.CharField(max_length=200, null=True, blank=True) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) email = models.EmailField(_('email address'), unique=True) bio = models.TextField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] -
Why my url appears as a post request when its get django
I have some templates in a django project. I'm trying to save them in the the url with a post request even though I specify it in the html document. Here's my views.py ` from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import WcaForm, IdForm from . import wcaScraper # Create your views here. def id(response): form = IdForm(response.GET) return render(response, "main/id.html", {"form": form}) def idresults(response): print(response.method) if response.method == "GET": print(wcaScraper.getDataByName(response.GET.get('name'))) return render(response, "main/nameresults.html", {"ids": wcaScraper.getDataByName(response.GET.get('name'))}) def search(response): form = WcaForm(response.GET) return render(response, "main/search.html", {"form": form}) def results(response): wcaData = wcaScraper.getDataById(response.GET.get('id')) variablePassed = { "id": response.GET.get('id'), "single3": wcaData[0].single, "avg3": wcaData[0].avg, "single2": wcaData[1].single, "avg2": wcaData[1].avg, "single4": wcaData[2].single, "avg4": wcaData[2].avg, "single5": wcaData[3].single, "avg5": wcaData[3].avg, "single6": wcaData[4].single, "avg6": wcaData[4].avg, "single7": wcaData[5].single, "avg7": wcaData[5].avg, "blind3single": wcaData[6].single, "blind3avg": wcaData[6].avg, "fmsingle": wcaData[7].single, "fmavg": wcaData[7].avg, "ohsingle": wcaData[8].single, "ohavg": wcaData[8].avg, "clocksingle": wcaData[9].single, "clockavg": wcaData[9].avg, "megasingle": wcaData[10].single, "megaavg": wcaData[10].avg, "pyrasingle": wcaData[11].single, "pyraavg": wcaData[11].avg, "skewbsingle": wcaData[12].single, "skewbavg": wcaData[12].avg, "squaresingle": wcaData[13].single, "squareavg": wcaData[13].avg, "blind4single": wcaData[14].single, "blind4avg": wcaData[14].avg, "blind5single": wcaData[15].single, "blind5avg": wcaData[15].avg, "multisingle": wcaData[16].single, "multiavg": wcaData[16].avg, } return render(response, "main/results.html", variablePassed) ` And my html template <html> <h1>Search by name</h1> <form method="get" action="/idresults"> {% csrf_token %} {{form}} <button type="submit">Search</button> </form> <p>or</p> <a href="id/"> Search by WCA Id</a> </html> … -
improperly configured at /18/delete, Django views issue
I have searched through the other questions similar to my own problem and have come to no solution so im hoping someone can help me figure out where i went wrong. I'm trying to implement a delete post option in my blog program but it is throwing the following error once you click the 'delete' button: ImproperlyConfigured at /18/delete/ Deletepost is missing a QuerySet. Define Deletepost.model, Deletepost.queryset, or override Deletepost.get_queryset(). I am nearly sure its a problem with my URLS.py though what exactly i cannot figure out. the following is the code in question: Views.py # delete post class Deletepost(LoginRequiredMixin, DeleteView): form_class = Post success_url = reverse_lazy('blog:home') template_name = 'templates/post.html' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.PostCreateView.as_view(), name='blog_post'), # posts/comments path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), # edit post path('<slug:slug>/edit/', views.Editpost.as_view(), name='edit_post'), # delete post path('<int:pk>/delete/', views.Deletepost.as_view(), name='delete_post'), # likes path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), ] post.html <a class="btn btn-outline-danger" href="{% url 'delete_post' post.id %}">Delete</a> Thanks for your time and i'm sorry for the trivial question but you guys are much smarter than me! -
When using django-allauth how do I get the Sites section in the admin page to show?
I'm new to Django and I'm trying to learn it from Django for Professionals by William Vincent. After installing django-allauth and following the steps in the book, I managed to get the logging in and out the sign up functionality to work. However, when I go to 127.0.0.1:8000/admin, I don't see a Sites section. This section is later used in the book to change the site being referred to (example.com) in the registration confirmation email. I've searched for django-allauth Site admin in here and in the docs but I couldn't find anything about making the Sites section show. -
How can I use Transaction rollback with Multiple forms in Django
I have four forms and I need them to be saved one by one however when any one form yields validation error then I need the data saved in the database to be removed. I understand the transaction rollback with Django query but not able to figure out that how would I will do the same with forms. with transaction.atomic(): # to store errors from the forms if any errors = [] # FormSubmitter are the function to submit the forms or provide the errors. cartoon_image_form_submitter = CartoonImageFormSubmitter( data=cartoon, request=request, form_model_keys=CartoonImage_form_model_keys, ) if ('errors' in cartoon_image_form_submitter and cartoon_image_form_submitter['errors'] is not None): errors.append(cartoon_image_form_submitter["errors"]) swimming_level_master_form_submitter = SwimmingLevelMasterFormSubmitter( data=swimming_level_master, form_model_keys=SwimmingLevelMaster_form_model_keys, ) if ('errors' in swimming_level_master_form_submitter and swimming_level_master_form_submitter['errors'] is not None): errors.append(swimming_level_master_form_submitter["errors"]) stages_summary_form_submitter = StagesSummaryFormSubmitter( data=stages_summary, form_model_keys=StagesSummary_form_model_keys, ) if ('errors' in stages_summary_form_submitter and stages_summary_form_submitter['errors'] is not None): errors.append(stages_summary_form_submitter["errors"]) lesson_level_detail_form_submitter = LessonLevelDetailFormSubmitter( data=lesson_level_details, form_model_keys=LessonLevelDetail_form_model_keys, ) if ('errors' in lesson_level_detail_form_submitter and lesson_level_detail_form_submitter['errors'] is not None): errors.append(lesson_level_detail_form_submitter["errors"]) if errors: errors = '<br>'.join([str(elem) for elem in errors]) from django.utils.safestring import mark_safe errors = mark_safe(errors) messages.error(request, errors) return HttpResponseRedirect('../levels/new') return HttpResponseRedirect('../levels/new') I tried with transaction.atomic(): and thought it will work because forms also saves data in db -
Implemented google login using server side flow how can i do for LinkedIn for Django REST Framework and React?
Hi i have Successfully implemented server side google login But i can't find proper implementation for server side login for LikendIn I am using Django Rest framework for bckend and React as front-end i have followed this blog: https://www.hacksoft.io/blog/google-oauth2-with-django-react-part-2 any specific blog or implementation ? -
How can an included file know it is included
In django you can include html files in other html files. So my question is there a variable so that the second file knows that it has been included? If not by default can I create one? Here is an example: a.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>From a.html</h1> {% include "b.html" %} </body> </html> b.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% if included_in_file %} <h1>From b.html</h1> {% else %} <h1>Hello</h1> {% endif %} </body> </html> The point is that when a file is included it shows something else than if it is normally used. Or do I just have to make a second file for the same use? -
multi db routing problem when migrate models in Django
I want to create separate database for hold project logs which define its models on LogCenter app. All other tables of models hold on default database. This is my settings.py: DATABASE_ROUTERS = ['Core.models.ALLDBRouter', 'Core.models.LogCenterRouter', ] DATABASES = { 'default': { 'ENGINE': os.environ.get("DEFAULT_DATABASE_ENGINE"), 'NAME': os.environ.get("DEFAULT_DATABASE_NAME"), 'USER': os.environ.get("DEFAULT_DATABASE_USER"), 'PASSWORD': os.environ.get("DEFAULT_DATABASE_PASSWORD"), 'HOST': DEFAULT_DATABASE_HOST, 'PORT': os.environ.get("DEFAULT_DATABASE_PORT"), # 'OPTIONS': { # 'options': '-c statement_timeout=30000', # }, }, 'log_config': { 'ENGINE': os.environ.get("LOG_DATABASE_ENGINE"), 'NAME': os.environ.get("LOG_DATABASE_NAME"), 'USER': os.environ.get("LOG_DATABASE_USER"), 'PASSWORD': os.environ.get("LOG_DATABASE_PASSWORD"), 'HOST': LOG_DATABASE_HOST, 'PORT': os.environ.get("LOG_DATABASE_PORT"), } } And this is my database routers: class LogCenterRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'LogCenter', } def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'log_config' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'log_config' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth … -
Django API without DRF: What are the consequences
I'm not sure what might go wrong when I have to integrate a django API (built using JsonResponse and without extra frameworks) with a frontend, in this case, Next.js. I built a django API using JsonResponse (void of DRF). I want to build a frontend client with Next.js that would make API calls to my django API. My questions are: Will I have to run both django and next.js servers at the same time to execute the full project? I think I would face some challenge with csrf token, what other challenges may I face having built my API without an API framework as Django Rest Framework? -
Encountered two children with the same key...ecommerce website
why is it that there are two children with the same key Im using React and Im trying to make ecommerce website I dont understand the error of double keys import React, {useEffect} from 'react' import { Link, useParams, useNavigate, useLocation, useSearchParams } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { Row, Col, ListGroup, Image, Form, Button, Card} from 'react-bootstrap' import Message from '../components/Message' import { addToCart } from '../actions/cartActions' export default function CartScreen() { const { id} = useParams() const { search } = useLocation(); const [searchParams] = useSearchParams(); const dispatch = useDispatch(); const productID = id; const qty = search ? Number(search.split("=")[1]) : 1; const cart = useSelector(state => state.cart) const { cartItems} = cart console.log('cartItems:', cartItems) useEffect(() => { if(productID) { dispatch(addToCart(productID, qty)) } }, [dispatch, productID, qty]) return ( <Row> <Col md={8}> <h1>Shopping Cart</h1> {cartItems.length === 0 ? ( <Message variant='info'> Your cart is empty <Link to='/'>Go Back</Link> </Message> ) : ( <ListGroup varient='flush'> {cartItems.map(item => ( <ListGroup.Item key= { item.product }> <Row> <Col md={2}> <Image src={item.image} alt={item.name} fluid rounded/> </Col> <Col md={3}> <Link to={`/product/${item.product}`}>{item.name}</Link> </Col> <Col md={2}> ${item.price} </Col> </Row> </ListGroup.Item> ))} </ListGroup> )} </Col> <Col md={4}> </Col> </Row> ) } Im … -
no errors are coming also i print the values when i login its not none its the same details when i entered login time
i am creating a website so i finshed register page in login page every details are corret but thats showing please verify ur details i mean the else part also i put a print statment after username and password same details are printing when i typed but not access login views.py def sign_in(request): if request.method == "POST": username=request.POST['username'] password=request.POST['password'] print(username,password) user = authenticate(username=username,password=password) if user is not None: login(request,user) messages.success(request,"you are logged successfully ") return redirect("front_page") else: messages.error(request,"please verify your details") return redirect("sign_in") return render(request,"login.html") def front_page(request): return render(request,"frontpage.html") urls.py path('log_in',views.sign_in,name="sign_in"), path('front_page',views.front_page,name="front_page"), html <div class="signup-form"> <form action="{% url 'sign_in' %}" method="POST"> {% csrf_token %} <h2 class="text-center">Login</h2> <p class="text-center">Please fill in this form to login your account!</p> <hr> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <span class="fa fa-user"></span> </span> </div> <input type="text" class="form-control" name="username" placeholder="Username" required="required"> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> </div> <div class="form-group d-flex justify-content-center"> <button type="submit" class="btn btn-primary btn-lg">Login</button> </div> <div class="text-center text-primary">Dont have a account? <a href="{% url 'register' %}">Create here </a></div> </form> </div> i just want to login with username and password,but it shows please verify your details .but … -
How to execute a python function based on a selection of a Drop down list in HTML?
HTML: <div class="iq-custom-select d-inline-block sea-epi s-margin"> <select name="cars" class="form-control season-select"> <option value="season1">Season 1</option> <option value="season2">Season 2</option> <option value="season3">Season 3</option> <option value="season4">Season 4</option> <option value="season5">Season 5</option> </select> </div> And this is my Pyghon method I really do not know how it should be written. DJANGO: def single_show(request, pk): show = get_object_or_404 (Show, pk=pk) episode_s1 = Episode.objects.filter(series=pk,season=1).order_by("episode_number") episode_s2 = Episode.objects.filter(series=pk,season=2).order_by("episode_number") episode_s3 = Episode.objects.filter(series=pk,season=3).order_by("episode_number") episode_s4 = Episode.objects.filter(series=pk,season=4).order_by("episode_number") episode_s5 = Episode.objects.filter(series=pk,season=5).order_by("episode_number") return render(request, "listings/single_show.html",{ 'show' : show, 'episode_s1' : episode_s1, 'episode_s2' : episode_s2, 'episode_s3' : episode_s3, 'episode_s4' : episode_s4, 'episode_s5' : episode_s5, }) I have a dropdown made in html and when I select a value I want to show my episodes -
Create custom user model and Profile
Well I'm trying to create user addition form from frontend that creates user and additional info based on custom user model.But I'm getting duplicate key value violates unique constraint "users_driver_email_key" DETAIL: Key (email)=() already exists. here is my code: Models.py class CustomUser(AbstractUser): is_driver = models.BooleanField(default=False) is_accountant = models.BooleanField(default=False) is_dispatcher = models.BooleanField(default=False) class Driver(models.Model): driver_user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, primary_key = True) full_name = models.CharField(max_length=50, default=None) phone_number = models.CharField(max_length=50, default=None) email = models.EmailField(unique=True,max_length=255, default=None) address = models.CharField(max_length=70, default=None) country = models.CharField(max_length=50, default=None) state = models.CharField(choices=US_STATES,max_length=50, default=None) city = models.CharField(max_length=50, default=None) zipp = models.CharField(max_length=50, default=None) birth_date = models.DateField(default=None) license_no = models.IntegerField(default=None) license_exp_date = models.DateField(default=None) last_medical = models.DateField(default='', blank=True, null=True) next_medical = models.DateField(default='', blank=True, null=True) last_drug_test = models.DateField(default='', blank=True, null=True) next_drug_test = models.DateField(default='', blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS, default=1) class DriversFiles(models.Model): file = models.FileField(upload_to="media/", blank=True, null=True) driver_files = models.ForeignKey('Driver', on_delete=models.CASCADE, default=None, null=True) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): # if Created is true (Means Data Inserted) if created: # Check the user_type and insert the data in respective tables if instance.is_driver: Driver.objects.create( driver_user=instance, full_name = "123", phone_number = "123", email = "", address = "123", country = "123", state = "123", city = "123", zipp … -
ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead
I've been getting this error message for a while now, but actually the code works fine and runs as expected, the line causing the error is this: templates/users/dashboard.html-> <link rel="stylesheet" href="{% static 'css/dashboard.css' %}"> when i remove the quotations i get a deferent error: <link rel="stylesheet" href={% static 'css/dashboard.css' %}> ERROR: Invalid Token. Expected stringStart but found tag start "{%" instead. when i completely remove the line i get the same erro on the first tag with href: <a href="{% url 'login' %}">Logout</a> ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead. i suspect that its a vscode issue, because the code runs flawlessly, and it only catches the error when i clean the code(format), so as long as i open vscode and never hit (ctrl+shidt+f) i dont get the error message, is there a solution for this? -
Django/Python Libraries for Reporting
Python is a popular tool for all kind of great candidate for reporting tasks. I found 2 Django/Python Libraries for Reporting are : reportlab and pyreportjasper. Could you tell me the advantages and disadvantages of each, so that I could be able to pick the right library ? -
Update data in html without reloading the page
I have a dictionary with questions and answers. What I would like to do is send one question at a time. On the web page I have a div grouping the question and the answers. I would like only this part to update without reloading the page. There is also a submit button When the user presses the button data is sent to the views.py then the view sends the following question. I tried to do this but there is no update in html with the following question urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('quizz', views.initQuiz, name="quizz"), re_path(r'^nextQuestion$', views.nextQuestion, name='nextQ') ] views.py def initQuiz(request): #with open("testjson.json") as f: data = json.load(f) data = [{"question": "q1", "responses": ["rep1", "rep2", "rep3"]}, {"question": "q2", "responses": ["rep1", "rep2", "rep3", "rep4"]}] request.session['data'] = data request.session['numQuestion'] = 0 return nextQuestion(request) def nextQuestion(request): if request.method == "POST": request.session['numQuestion'] = request.session.get('numQuestion') + 1 data = request.session.get('data') numQuestion = request.session.get('numQuestion') numResponse = list(range(1, len(data[numQuestion]["responses"])+1)) return render(request, 'quizz.html', context={"question" : data[numQuestion]["question"], "responses": zip(data[numQuestion]["responses"], numResponse)} quiz.html <div class="container-quiz"> <p class="question"> {{question}} </p> <div class="listReponse"> <div class="reponses"> {% for rep in responses%} <input name={{rep.1}} type="checkbox" class="reponse"> <label for={{rep.1}}>{{rep.0}}</label> {% endfor %} </div> </div> </div> <form …