Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Docker Postgresql database import export
I have a problem with postgresql database. I just want to able to export and import database like .sql file. But when using command line I am able to get .sql database file but when I'm trying to import it to database it's giving syntax errors in sql file. I can try to fix syntax errors in sql file but I don't want to solve this problem it like that. I need to get exported sql file without any errors and to be able to import it without any issue. What can be a problem? Postgresql version:postgres:14.6 For example here is auto generated sql code by exporting db as sql file. it gives syntax error in this line : "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, DROP TABLE IF EXISTS "core_contact"; CREATE TABLE "public"."core_contact" ( "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "first_name" character varying(50) NOT NULL, "last_name" character varying(50) NOT NULL, "company_name" character varying(50) NOT NULL, "email" character varying(128) NOT NULL, "message" text NOT NULL, "created_at" timestamptz NOT NULL, CONSTRAINT "core_contact_pkey" PRIMARY KEY ("id") ) WITH (oids = false); But, when I change it manually like that : "id" bigint NOT NULL, And … -
problem with creating APIView for celery flower dashboard
I have Django, DRF and React application with few endpoints. I'd like to create APIView that redirects user to flower pages. The flower urls should be hosted under www.myapp.com/flower. I've created docker container with django, react, celery-beats, celery-worker, flower and nginx images and I can run them normally however I am not sure how to do it on lcoud. I am using Azure App Service. I have 2 files in my nginx folder but: nginx.conf server { server_name myapp; location / { proxy_pass http://myapp.com/flower; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Dockerfile FROM nginx:1.17.4-alpine RUN rm /etc/nginx/conf.d/default.conf ADD nginx.conf /etc/nginx/conf.d -
Post Form object has no attribute 'cleaned'
This is my Post Form from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' def clean_slug(self): return self.cleaned['slug'].lower() Here is my Traceback: Traceback (most recent call last): File "django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "E:\Django Unleashed\suorganizer\blog\views.py", line 28, in post if bound_form.is_valid(): File "django\forms\forms.py", line 205, in is_valid return self.is_bound and not self.errors File "django\forms\forms.py", line 200, in errors self.full_clean() File "django\forms\forms.py", line 437, in full_clean self._clean_fields() File "django\forms\forms.py", line 452, in _clean_fields value = getattr(self, "clean_%s" % name)() File "suorganizer\blog\forms.py", line 11, in clean_slug return self.cleaned['slug'].lower() AttributeError: 'PostForm' object has no attribute 'cleaned' [26/Apr/2023 14:51:24] "POST /blog/create/ HTTP/1.1" 500 93820 -
Django LDAP Active Directory Authentification
Im trying to adjust my django project to connect to AD. Using libraries django-auth-ldap, ldap. Binding user is fine, creating and populating django user - ok. But in the end, authentification fails with next output: Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ Invoking search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=admin)') search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=admin,cn=users,dc=atk,dc=biz Binding as cn=admin,cn=users,dc=atk,dc=biz Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ cn=admin,cn=users,dc=atk,dc=biz is a member of cn=django-admins,cn=users,dc=atk,dc=biz Creating Django user admin Populating Django user admin Caught LDAPError while authenticating admin: OPERATIONS_ERROR({'msgtype': 111, 'msgid': 6, 'result': 1, 'desc': 'Operations error', 'ctrls': [], 'info': '000020D6: SvcErr: DSID-031007E5, problem 5012 (DIR_ERROR), data 0\n'}) My settings.py file is below: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', "django.contrib.auth.backends.ModelBackend", ] AUTH_LDAP_SERVER_URI = "ldap://BORUM.ATK.BIZ" AUTH_LDAP_BASE_DN = "DC=ATK,DC=BIZ" AUTH_LDAP_BIND_DN = "CN=bind,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_BIND_PASSWORD = "***" AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) # AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,cn=users,dc=ATK,dc=BIZ" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 255, ldap.OPT_REFERRALS: 0, } AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", # "last_name": "sn", } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "DC=ATK,DC=BIZ", ldap.SCOPE_SUBTREE, "(objectCategory=group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "CN=django-admins,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser": "CN=django-admins,CN=Users,CN=ATK,CN=BIZ", "is_staff": "CN=django-admins,CN=Users,DC=ATK,DC=BIZ", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 Any ideas would be highly appreciated. Error number 000020D6 indicates that ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD, I dont really understand how to treat that error, how binding … -
How to inner join two models in django?
I have two models: Available Options: class AvailableOptions(models.Model): name = models.CharField(max_length=20, default="") image = models.ImageField(upload_to=upload_to, blank=True, null=True) Stock: class Stock(models.Model): name = models.ForeignKey( AvailableOptions, on_delete=models.CASCADE, related_name="Stock") quantity = models.IntegerField(null=False, default="") created_at = models.DateTimeField(auto_now_add=True) How do i query and return response the two models? I want to return name , quantity from the second model and image from the first model. I tried this in my view (testview) but it only returned the second model fields. @api_view(['GET']) def testview(request): query = Stock.objects.select_related('name') data = serializers.serialize('json', query ) return Response(data) -
Django postgres migration issues when adding fields to existing models
I currently have a project in development. When trying to add new fields to existing models I am having issues with migrations which is causing me to worry about data loss. The errors I'm getting is that it says the fields don't exist when I can clearly see in the latest migrations file it has been added. I have never had this issue before when adding new fields and then pushing to the remote repository and then pulling it into production where I would then do the migrations. -
I need to prevent showing previous pages from my django app
Even after I logged out I'm still able to see my previous pages how to prevent the browser from showing this? I tried this piece of JavaScript code . Note: I used template inheriting and templates statically imported. function preventBack() { history.pushState(null, null, location.href); window.onpopstate = function () { history.go(1); console.log("worked") }; } window.onload = function() { preventBack(); console.log("worked call ") }; when I tried this "console showed worked call" but the 'worked' is not yet printed in console means wins=down.onpopState not worked what's the cause of this problem. I'm quiet new in Django feels like I tarped here!! -
django-keycloak refresh openID connect .well-known error
Hello everyone i really need help in a issue i faced while working on django-keyclock: you can see here the documentation thet I'm following: https://django-keycloak.readthedocs.io/en/latest/ I did the initial setup and I setup for remote user , then i configured the server and the realms in the django admin panel and everything looks good. but when i try to Refresh OpenID Connect .well-known I got this error in the image. And i think that /auth is the problem because when I remove it I got a json response. please if anyone can help me. and thank you in advance. [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/g09Jc.png [2]: https://i.stack.imgur.com/Bv1E1.png -
How can I deploy an app on Heroku that is not located in the root directory?
I've got a project that has a directory structure as such: ├── backend │ ├── backend-files.py │ └── procfile ├── docker-compose.yml └── frontend I want to be able to deploy the Python backend (Django) on Heroku. As you can see it is located in it's own directory. However, Heroku does not allow me to specify a subdirectory when pointing to a github repo. This means that I would need my backend code to be at the root level in order to use their CD pipeline features. Does anyone know of a way to modify my configuration in Heroku so that I can keep the directory structure as is? -
Django-allauth Redirect any unauthenticated user to login page
I’m developing a django project and my veiws are function based and using django-allauth for authentication. Now, I’m searching for a pattern to work on all project so that any unauthenticated user is redirected automatically to login page. An alternative way is to add @login_required() decorator over every view function but I don’t see that as logical method. -
Custom OrderingFilter Django REST + Vue
I'm working on backend part of project (Django REST). I have a task - to do sorting for the front (Vue). The frontend sends a key for sorting and a parameter for sorting. Example: GET /api/v1/stocks/?sort_key=FBS&sort_type=ascending GET /api/v1/stocks/?sort_key=FBS&sort_type=descending I guess it can be done with OrderingFilter and DjangoFilterBackend. Any suggestions will be helpful. my models.py class Stock(models.Model): class Meta: verbose_name_plural = "Stocks" verbose_name = "Stock" ordering = ("-present_fbs",) store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Store") fbs = models.PositiveIntegerField(default=0, verbose_name="FBS") my views.py class StocksApi(ListModelMixin, GenericViewSet): serializer_class = StocksSerializer permission_classes = (IsAuthenticated,) pagination_class = StocksDefaultPagination def get_queryset(self): return Stock.objects.filter(store__user_id=self.request.user.pk).order_by("-fbs") -
TK to run django server on windows
I have windows server running Django as a CMD process. Some workers mistakenly closing it. I want to switch to TK running the Django server and put output on screen. How safe is that ? How do I close the django properly ? class TextRedirector(object): def __init__(self, widget, tag="stdout"): self.widget = widget self.tag = tag def write(self, str): self.widget.configure(state="normal") self.widget.insert("end", str, (self.tag,)) self.widget.see(tk.END) self.widget.configure(state="disabled") class TkApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) toolbar = tk.Frame(self) toolbar.pack(side="top", fill="x") # set window size self.geometry("500x200") self.title("DJANGO") self.text = tk.Text(self, wrap="word") self.text.pack(side="top", fill="both", expand=True) self.text.tag_configure("stderr", foreground="#b22222") self.text.yview("end") self.iconbitmap("activity.ico") sys.stdout = TextRedirector(self.text, "stdout") sys.stderr = TextRedirector(self.text, "stderr") self.protocol('WM_DELETE_WINDOW', self.on_close) self.run() def on_close(self): response = tkinter.messagebox.askyesno('Exit', 'Are you sure you want to exit?') if response: try: # KILL THE DJANGO PROCESS .... finally: sys.exit(0) def run(self): # RUN THE DJANGO PROCESS .... if __name__ == '__main__': app = TkApp() app.mainloop() will this work ? I also need to tell the django to close nicely (same as I would click the X button on command line) Instead: I want: -
Scan python link and iframe it?
i want to execute one python code and try to get output in browser import os tools=os.popen('pip list | seashells').read() output is this link serving at https://seashells.io/v/rWXx9XvF how to iframe the link generated in terminal ? i try to store this seashell generated link in python veriable and iframe in html code but cuould not do it? i neeed help!! -
ModuleNotFoundError: No module named 'phone_verify.views'
I am using django-phone-verify in my drf project to send otp and phone call for sign in. When i want to import start_verification from phon_verify.views this error is showing"ModuleNotFoundError: No module named 'phone_verify.views" views.py from rest_framework.decorators import api_view from rest_framework.response import Response from phone_verify.views import start_verification @api_view(['POST']) def sign_in_sms(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='sms') return Response({'success': 'Verification started'}) @api_view(['POST']) def sign_in_phone_call(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='call') return Response({'success': 'Verification started'}) urls.py from django.urls import path, include from phone_verify.urls import urlpatterns as phone_verify_urls from django.urls import path from sms.views import sign_in_sms, sign_in_phone_call urlpatterns = [ path('api/', include('sms.urls')), path('phone-verify/', include(phone_verify_urls)), path('sign-in/sms/', sign_in_sms), path('sign-in/phone-call/', sign_in_phone_call), ] settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phone_verify', 'sms', ] PHONE_VERIFICATION = { 'FROM_NUMBER': 'my number', 'TWILIO_ACCOUNT_SID': 'my sid', 'TWILIO_AUTH_TOKEN': 'my token', } -
decode PDF from Django BinaryField using Angular / Typescript
I have an issue regarding encoding a PDF file into a BinaryField (MySQL as database) and then retrieving it via endpoint with Angular and decoding it into the file again. My model and save-to-database method looks like this: import os from django.db import models class Report(models.Model): report_file_type: models.CharField = models.CharField(max_length=50, null=True, blank=True) report_file: models.BinaryField = models.BinaryField(null=True, blank=True) def save_report_in_database(self, file_path: str, file_type: str) -> None: with open(file_path, 'rb') as file: content = file.read() self.report_file_type = file_type # type: ignore # PyCharm doesn't like this self.report_file = content # type: ignore # PyCharm doesn't like this self.save() # delete the file from the file system os.remove(file_path) The PDF is generated in a celery task via matplotlib and PdfPages and it's reasonably small (around 60kB) i.e. import matplotlib.backends.backend_pdf with matplotlib.backends.backend_pdf.PdfPages(pdf_out) as pdf: for _idx, fig in enumerate(figs): fig.text( 0.999, 0.005, # bottom right corner f"{_idx + 1}/{len(figs)}", ha='right', fontsize=10, fontweight="bold", ) pdf.savefig(fig) When complete, the save_report_in_database method is called. When I log the output I get: 2023-04-26 05:56:57,539 - project logger - INFO - PDF as bytes: b'%PDF-1.4\n%\xac\xdc \xab\xba\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n8 0 obj\n<< /Font 3 0 R /XObject 7 0 R /ExtGState 4 0 R … -
"User with this email already exists." False Error Upon Signup in Django / React Application with Custom User
I am using redux to manage the state. Email is the username for my custom user model. Here is my django User model. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError("Please provide an e-mail") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) # user.is_superuser = False user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) last_login = models.DateTimeField( blank=True, null=True, verbose_name='last login') date_joined = models.DateTimeField( blank=True, null=True, default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email objects = UserAccountManager() Here is the User Serializer and below auth.js "from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): fields = ['id', 'email', 'name', 'password', ] " Here is the auth.js "export const signup = (name, email, password, re_password) => async ( dispatch ) => { const config = { headers: { "Content-Type": "application/json", }, }; … -
how to solve problem with AJAX requests in django?
script.js: console.log('work') const url = window.location.href const searchForm = document.getElementById('search-form') const searchInput = document.getElementById('search-input') const resultsBox = document.getElementById('results-box') const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value console.log('first module success') const sendSearchData = (product)=>{ $.ajax({ type: ' POST', url: 'search/', data: { 'csrfmiddlewaretoken':csrf, 'product': product, }, success: (res)=>{ console.log('---res ---', res) }, error:(err)=>{ console.log('---error---',err) } }) } searchInput.addEventListener('keyup', e=>{ console.log(e.target.value) if (resultsBox.classList.contains('not-visible')){ resultsBox.classList.remove('not-visible') } if (e.target.value == '') { resultsBox.classList.add('not-visible') } sendSearchData(e.target.value) }) views.py: class ProductListView(ListView): model = Product paginate_by = 10 template_name = 'shop/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() if self.request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': product = self.request.POST.get('product') return context, JsonResponse({'data':product}) return context after entering something into the search bar, this code is activated and sends Ajax requests that pass this text, but I get an error in the console ''' statusText: "SyntaxError: An invalid or illegal string was specified" ''' -
Write uploaded file by chunks in an async context
I have a Python async function receiving a django.core.files.uploadedfile.TemporaryUploadedFile from an Django API endpoint, as well as from a Django form. Once this function is launched, it needs to write the file, and since the files are larges Django suggests to use UploadedFile.chunks() method to do so. So I have a classical sync method to write the file by chunks to a destination path, looking like this: from pathlib import Path from django.core.files.uploadedfile import TemporaryUploadedFile def write_file(file: TemporaryUploadedFile, destination: Path) -> None: with open(destination, "wb+") as out: for chunk in file.chunks(): out.write(chunk) As said, it is called from an async context, using asgiref.sync.sync_to_async. The main function logic looks like this: from asgiref.sync import sync_to_async from pathlib import Path from django.core.files.uploadedfile import TemporaryUploadedFile async def process_submission(file: TemporaryUploadedFile) -> None: ... do stuff ... await sync_to_async(write_file)(file=file, destination=Path("/my_path.mp4")) ... do other stuff ... ...but I get the error ValueError: read of closed file. I believe it might be related to the fact that the file is a stream, but I'm not really sure on what's happening. Any idea on why and how to solve that? -
Django-Allauth Google OAuth get approved scopes
I have added additional Google API scopes to my Django application. I wanted to check if the user has approved the other scopes. I searched online and found references to scopes in the extra_data. But I couldn't find it. Appreciate any help in checking if the user has approved the extra scopes. -
Vercel Deploy Django Raised Sqlite3 Version Exception
I am deploying Django to Vercel. But it raised the error below during running. django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher How to upgrade the Sqlite3 into 3.8.3 on Vercel server? -
Django using prefetch_related to reduce queries
I am trying to understand how I can improve the following query: class PDFUploadRequestViewSet(viewsets.ModelViewSet): def get_queryset(self): project_id = self.request.META.get('HTTP_PROJECT_ID', None) if project_id: return PDFUploadRequest.objects.filter(project_id=project_id) else: return PDFUploadRequest.objects.all() def get_serializer_class(self): if self.action == 'list': return PDFUploadRequestListSerializer else: return self.serializer_class The issue is that the more PDFPageImage objects are in the DB then it creates separate query for each of them thus slowing down the request. If there is only one value if PDFPageImage related to given PDFUploadRequest then its pretty fast, but for each additional value it is producing extra query and after doing some research I found out that prefetch_related might somehow help with this, but I have not been able to figure out how to use it with my models. This is how the model for PDFUploadRequest looks like: class PDFUploadRequest(models.Model, BaseStatusClass): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(upload_to='uploaded_pdf') file_name = models.CharField(max_length=255) status = models.CharField( max_length=50, choices=BaseStatusClass.PDF_STATUS_CHOICES, default=BaseStatusClass.UPLOADED, ) completed = models.DateTimeField(null=True) processing_started = models.DateTimeField(null=True) text = models.TextField(default=None, null=True, blank=True) owner = models.ForeignKey(User, related_name='pdf_requests', on_delete=models.PROTECT, null=True, default=None) project = models.ForeignKey(Project, related_name='pdf_requests', on_delete=models.PROTECT, null=True, default=None) class Meta: ordering = ['-created'] def no_of_pages(self): return self.pdf_page_images.count() def time_taken(self): if self.completed and self.processing_started: return self.completed - self.processing_started And this is the related … -
How to show all messages from gmail who logged in with his google account to my site Django
I used for auth django-allauth. I was able to get some user data with google_account = SocialAccount.objects.get(user=user, provider='google').extra_data but i don't know how to get access_token. I used access_token = extra_data.get('access_token') but this return None I also try without .extra_data google_account = SocialAccount.objects.get(user=user, provider='google') social_token = google_account.socialtoken_set.first() How can i take the token and show all mails and i use: try: service = build('gmail', 'v1', credentials=credentials) # Fetch the user's 10 most recent emails results = service.users().messages().list(userId='me', maxResults=10).execute() messages = results.get('messages', []) # Print the subject line of each message for message in messages: msg = service.users().messages().get(userId='me', id=message['id']).execute() return msg['payload']['headers'][16]['value'] except HttpError as error: return f'An error occurred: {error}' settings.py SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'}, 'SOCIALACCOUNT_QUERY_EMAIL': True, 'APP': { 'client_id': os.environ.get('GOOGLE_CLIENT_ID'), 'secret': os.environ.get('GOOGLE_SECRET'), 'key': '' } }} SOCIALACCOUNT_QUERY_EMAIL=True SOCIAL_AUTH_ENABLED_BACKENDS = ['google', 'google-oauth'] -
Datetiemfield saved to database but showing in adminsite is null
Ordered_date was saved in db But not display in adminsite My code: My code Please help me fix this issue -
Reuse modal implemented in Django
I know this is common to ask but I search for different solutions but couldn't yet find one, Is there any way to reuse the modal? instead of making different modals in each function why not reuse it into just one, is there any way to implement it, especially in Django? should I transfer it into a javascript file? What I've tried is extending the HTML to the main file but it couldn't work modal.html templates/modal.html {% block modal_scripts %} <div class="modal-onboarding modal fade animate__animated" id="onboardImageModal" tabindex="-1" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header border-0"> <a class="text-muted close-label" href="javascript:void(0);" data-bs-dismiss="modal" >Skip Intro</a > <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body p-0"> <div class="onboarding-media"> <div class="mx-2"> <img src="../../assets/img/illustrations/girl-unlock-password-light.png" alt="girl-unlock-password-light" width="335" class="img-fluid" data-app-light-img="illustrations/girl-unlock-password-light.png" data-app-dark-img="illustrations/girl-unlock-password-dark.png" /> </div> </div> <div class="onboarding-content mb-0"> <h4 class="onboarding-title text-body">Test</h4> <div class="onboarding-info"> In this example you can see a form where you can request some additional information from the customer when they land on the app page. </div> <form> <div class="row"> <div class="col-sm-12"> <div class="mb-3"> <label for="roleEx3" class="form-label">Discount</label> <select class="form-select" tabindex="0" id="roleEx3"> <option>Senior Citizen - 20%</option> <option>Business Owner</option> <option>Other</option> </select> </div> </div> </div> </form> </div> </div> <div class="modal-footer border-0"> <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal"> … -
Faile to load resource: the server responded with a status of 500 (Internal Server Error)
my web page runs normally, until i do a javascript AJAX snippet, it starts showing error 500 in cart function at the plus sign, when I click add it just increases the amount in the data and has to reload the page to see the number quantity, the user side won't see it script in html <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="" crossorigin="anonymous"></script> Views.py def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect('/cart') def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0.0 shipping_amount = 10.0 total_amount = 0.0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount context = {'cart':cart, 'total_amount':total_amount, 'amount':amount,'shipping_amount':shipping_amount} return render(request, 'general/addtocart.html', context) else: return redirect('login') def plus_cart(request): if request.method == 'GET': prod_id = request.GET['prod_id'] c= Cart.objects.get(Q(product=prod_id) & Q(user = request.user)) c.quantity+=1 c.save() amount = 0.0 shipping_amount = 10.0 cart_product = [p for p in Cart.objects.all() if p.user == request.user] for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount data={ 'quantity':c.quantity, 'amount': amount, 'total_amount': total_amount }, return JsonResponse(data) Javascript.js $('.plus-cart').click(function () { //console.log("Click") var id …