Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User login not working on different view django
I use Django's authentication system to login a user. When I login a user like this: views.py: class Login(APIView): def post(self, request): data = request.data username = data.get("username") password = data.get("password") user = authenticate(username=username, password=password) if user is None: return Response(status=400, data={"error": "wrong input", "statusCode": 400}) else: login(request, user) #outputs True print(request.user.is_authenticated) #outputs True print("is_active: ", request.user.is_active) return Response() I can't verify the user in a different view, e.g: views.py class Files(APIView): def get(self, request): #outputs False print("is_authenticated", request.user.is_authenticated) return Response() In my settings.py I've included: INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.contenttypes', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ... ] Any ideas? -
Why autoescape cannot substitute safe in Django template?
I am a beginner in Django and working on the template and get confused on autoescape and |safe. I thought autoescape could substitute |safe, but it is not. I don't know why. Following is my code. Could anyone help me out? Thanks a lot. |safe works well: {% block title %} {{ name|safe }} {% endblock %} {% block body %} {{ description|safe }} {% endblock %} autoescape does not work: {% autoescape on %} {% block title %} {{ name }} {% endblock %} {% block body %} {{ description }} {% endblock %} {% endautoescape %} -
Not able to get the requested URL in django new version
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/customer/ Using the URLconf defined in crm.urls, Django tried these URL patterns, in this order: admin/ The current path, customer/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is my code crm/urls.py---> from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] now accounts/urls.py---> from django.urls import path from . import views urlpatterns = [ path('', views.home,name="ShopHome"), path('products/', views.products,name="ProductsHome"), path('customer/', views.customer,name="customerHome"), ] Now accounts/view.py---> from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('home') def products(request): return HttpResponse('products') def customer(request): return HttpResponse('customer') Please help me out guys I'm struck here for 2 days -
How to make Django dictionary serializer
So i tried to make a serializer but my server keeps giving me this error Traceback (most recent call last): File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\aldya\OneDrive\Рабочий стол\work\SmartTeens\proshop_django\base\views\marathon_views.py", line 56, in getMarathon marathon = Marathon.objects.get(_id=pk) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1377, in add_q child_clause, needed_inner = self.build_filter( File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\aldya.virtualenvs\proshop_django-fBhdlF-V\lib\site-packages\django\db\models\sql\query.py", line 1165, … -
Django error with admin form TypeError at /admin/syst/pet_history/add/ __str__ returned non-string (type NoneType)
I am trying to make a django admin form and all my other componenet work however when I try to add to this class on the form it comes back with the following error: TypeError at /admin/syst/pet_history/add/ str returned non-string (type NoneType) Does anyone know why this is happening here is the code for the class: class Pet_History(models.Model): pet_history_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pet_ID = models.ForeignKey(Pet_Description, on_delete=CASCADE) visit_Num = models.IntegerField(null=True) Visited_vet_before = models.CharField(max_length=50, null=True) First_time_of_illness = models.DateField(null=True) Special_Medication = models.CharField(max_length=50, null=True) Medication_Description = models.CharField(max_length=50,null=True) def __str__(self): return {self.visit_Num} -
Is there a way to convert Text to Image base64 without having to store the image?
Currently I have a captcha that generates random text in the Django backend and then pass the value via Jinja template, Then on the client side the Captcha is freshly drawn into the Canvas, There is one problem with this approach, The text is displayed in the View Page Source, Therefore a script can fetch the value and bypass it easily without having to crack the actual image. So I am planning to send it as an Image Base64 and then have canvas draw it on the client side without having to store the Image(Text to Image to base64 but image is not stored), And if possible, Without having to create the image(Text to Image base64 directly) -
Heroku 403 Forbidden Error while using Python requests module
I am working on a Django application, currently deployed on a Free Heroku dyno, which consumes the CoWin public API. On Heroku server, the requests.get() method returns HttpResponse status code 403. This is what my API call looks like - headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'} url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=110001&date=23-05-2021" api_response = requests.get(url, headers = headers) When I run it locally using heroku local command, everything works fine & the HttpResponse status code returned is 200. I am failing to understand why it returns 403 status code when running it on Heroku server. -
How do I run migrations when I'm re-deploying Django app on server?
I'm new to Django and programming in general. After we have deployed a Django app either on VPS or AWS, and need to replace the files, how do I go about it? Had it been in development, I would just need to run the makemigrations and migrate commands. What is the safe way to do without affecting the data already there? Note: I would be using MS SQL server on VPS, or one of the RDS on AWS. -
Django only saving one option from custom multi select field
So I am trying to save class to my model which is a many to many field and when I try to save it from my custom form using multi select it only save one valu This is my views.py @login_required() def create_class(request): tea_user = request.user.username validate = teacher_validation(tea_user) if validate: if request.method == 'POST': Link = request.POST.get('link') Subject = request.POST.get('Subject') Class = request.POST.get('Class') teacher_user = Teacher.objects.get(User=request.user) teacher = Teacher.objects.get(id=teacher_user.id) created_class = Online_Class.objects.create( Link=Link, Subject=Subject,Created_by =teacher ) created_class.Class.set([Class]) return redirect('home') return render(request, 'online_class/Teacher/class-create.html') else: messages.warning(request, 'Sorry You Dont have Permission to access this page') return redirect('logout') And My models.py looks like this class Online_Class(models.Model): Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) Class = models.ManyToManyField(Classes) Subject = models.CharField(max_length=100) Link = models.CharField(max_length=200) Joined_by = models.ManyToManyField(Student, blank=True) created_at = models.DateTimeField(auto_now_add=True) choice = (('Yes','Yes'),('No', 'No')) Class_Ended = models.CharField(choices=choice, default='No', max_length=10) And my template looks like this {% extends 'dashboard/teacher/base.html' %} {% block title %} Create Class {% endblock title %} {% block class %} active {% endblock class %} {% block body %} <div class="pc-container"> <div class="pcoded-content"> <div class="row"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label >Zoom Link</label> <input type="url" class="form-control" name="link" placeholder="URL" required=""> </div> <div class="form-group"> <label>Subject</label> <select class="form-control" name="Subject" required=""> {% for subject in … -
export two querysets into one excel using django-import-export
I can't get two querysets export into a single excel. How should I do it??? This is what I tried. class ExportIssuedBooksResource(resources.ModelResource): def export(self, queryset = None, *args, **kwargs):#this method helps capture the current user school queryset = Issue.objects.all().filter(borrower_id__school = kwargs['school']) queryset2 = TeacherIssue.objects.all().filter(borrower_teacher__school = kwargs['school']) return super().export(queryset, queryset2,*args, **kwargs) class Meta: model = Issue fields = ('book_id__reg_no','book_id__book_name','borrower_id__name','borrower_id__student_id','issue_date') export_id_fields = ('book_id__reg_no',) And the view def ExportIssuesView(request): dataset = ExportIssuedBooksResource().export(school = request.user.school) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All Issued Books.xls"' return response -
AssertionError: You cannot call `.save()` on a serializer with invalid data
def update(self, request, pk=None): queryset = Product.objects.all() product = get_object_or_404(queryset, pk=pk) serializer = ProductSerializer(product, data=request.data, context={"request": request}) serializer.is_valid() serializer.save() # print(request.data["product_details"]) for type_detail in request.data["product_details"]: if type_detail["id"] == 0: # For Insert New product_type Details del type_detail["id"] type_detail["product_id"] = serializer.data["id"] serializer2 = ProductDetailsSerializer(data=type_detail, context={"request": request}) serializer2.is_valid() serializer2.save() else: # For Update product_type Details queryset2 = ProductDetails.objects.all() type_product = get_object_or_404(queryset2, pk=type_detail["id"]) del type_detail["id"] serializer3 = ProductDetailsSerializer(type_product, data=type_detail, context={"request": request}) serializer3.is_valid() serializer3.save() print("UPDATE") return Response({"error": False, "message": "Data Has Been Updated"}) hi guys I have got this error in my view set Django can you guys help me with it ..whenever I want to update the date this is the error I get -
Django rendering error while using request.session in html page?
why i am getting error during rendering?? views.py: r.session["name"]="testing" return render(r,"home.html")``` home.html: -------- ``` <body> <h1>{{ r.session["name"] }}</h1> </body> -
APITestCase throws 403 when no credentials needed
I', strugglinh with strange APITestCase behaviour while testing. I'm keep getting 403 Error on views that doesn't require any authentication. Settings.py are completly free from any DEFAULT_PERMISSION_CLASS etc. Only additional lines there are installed apps and "API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY"" line. More over I explicit said in views "AllowAny" what You can see below. While testing with Postman everything works like a charm. views.py @api_view(['GET']) @permission_classes([AllowAny]) def message_detail(request, pk): try: message = Message.objects.get(pk=pk) except Message.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = MessagesSerializer(message) message.add_view() return Response(serializer.data, status=status.HTTP_200_OK) tests.py def test_detail_view_status(self): pk = 3 url = reverse('message_detail',kwargs={'pk': pk}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_detail_view_content(self): pk = 3 url = reverse('message_detail', kwargs={'pk': pk}) response = self.client.get(url) message = Message.objects.get(pk=pk) serializer = MessagesSerializer(message) self.assertEqual(response.data, serializer.data) tracebacks test_detail_view_content self.assertEqual(response.data, serializer.data) AssertionError: {'detail': ErrorDetail(string='Authenticati[57 chars]ed')} != {'views': 0, 'text': 'Example text message number 3'} test_detail_view_status self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 403 != 200 -
How to create "Delete Event" botton on Django Calendar in Python
I want to be able to Delete Event on my Calendar in Django using Python? I am not able to figure out how I delete the Event after it creates it. HOW TO CREATE A CALENDAR USING DJANGO I used this person code to make my calendar in Django but now I need some type of delete button to delete a event on there. Please help.... -
Google API OAuth 2 and Django
I work on a project with Django, Google API Calendar and OAuth 2 and I have the follow error: (insecure_transport) OAuth 2 MUST utilize https. When I set the redirect_uri with google_auth_oauthlib.flow.Flow, the URI that I set is: http://localhost:8000/google/oauthcallback. -
multiple form in django view raise csrf token error
when using multiple form in one view raise error csrf token missing or incorrect using django 3.2 views.py def post(self,request,**kwargs): context = {} if request.method== 'POST': form = RegisterForm1(data=request.POST) form2 = RegisterForm2(data=request.POST) if form.is_valid(): form.save() if form2.is_valid(): form2.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email,password=raw_password) login(request,user) return redirect('core:login') signup.html <form method="post" action=""> {% csrf_token %} <div class="form-group col-md-6"> {{form1.as_p}} </div> <div class="form-group col-md-6"> {{form2.as_p}} </div> </form> User successfully signup and authenticated but raise error 403 CSRF Token missing or incorrect -
How to use template tags in javascript? Django
I am using python(Django), I created a template tag which returns an array of dictionary, now I want to use it in my javascript. It works fine when I call it from views by dumping in JSON format and parsing back in my javascript. But in template tag the case is different. So far, I tried couple of ways but all of them had issues, they are listed below. First Way The most common, inside my template tag I dumped array into JSON format and called it in Javascript with JSON.parse Code for following - Template Tag @register.simple_tag(takes_context = True) def messageRequest(context): request = context['request'] messageData = Message.objects.all() jsMessageData = [] if 'user' in request.COOKIES: currentUser = request.COOKIES.get('user') i = 0 for i in range(len(messageData)): if messageData[i].receiver == currentUser: jsMessageData.append({"receiver":messageData[i].receiver, "sender":messageData[i].sender, "message":messageData[i].message}) if messageData[i].sender == currentUser: jsMessageData.append({"receiver":messageData[i].receiver, "sender":messageData[i].sender, "message":messageData[i].message}) i += 1 return dumps(jsMessageData) Index.html - testVal = JSON.parse("{%messageRequest%}"); Result: I got error Uncaught SyntaxError: Unexpected token & in JSON at position 2 Second Way I tried calling {%messageRequest%} inside a normal javascript variable thinking that I will use that variable inside JSON function to prevent syntax error, but this gave me same error. So I concluded that I cannot … -
__init__() missing 1 required positional argument: 'request' parent constructor error while extending class
I am trying to extend my class based views from a baseView for my custom admin Section. The following is a view for the dashboard section. class Dashboard(BaseAdminView): def __init__(self, request): super().__init__(request) def get(self, request): return render(request, 'admin/pages/dashboard.html', {'hello': 'World'}) Similarly, the following is the base admin view which I'll be extending for almost all of the related view classes. class BaseAdminView(View): loggedInUser = None def __init__(self, request): if (request.session['loggedInAdministrator'] is None): return redirect('adminlogin') else: loggedInUser = request.session['loggedInAdministrator'] My issue is that I am getting __init__() missing 1 required positional argument: 'request' error in the console when I try to access the dashboard. Isn't self then request the order of variables here or am I missing something. Also I removed self still the issue was the same. If I opt out of using request variable, the constructor works fine though, but using sessions is my only need for which I am doing this in the first place. How do I make this work?? How do I access request in the parent class?? Also I see that def __init__(self, request): super().__init__(request) this code in the dashboard is unnecessary, as the base constructor gets called even if I remove this. Is this … -
Django - MigrationSchemaMissing error windows
django MigrationSchemaMissing error I am trying to connect Oracle 11g with django through cx_Oracle here i am able to fetch data from my database and show it in command prompt. in settings.py i have wrote- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XE', 'USER': 'name', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '1521' } } and in view.py for extracting data i have written- import cx_Oracle # create connection conn = cx_Oracle.connect('name/pass@//localhost:1521/xe') print(conn.version) # create cursor # cur.execute(sql_create) #print('table created') cur = conn.cursor() cur.execute('select * from des') res = cur.fetchall() list = [] for r in res: list.append(r) print(r) print(list) cur.close() conn.close() here i have used the list data for showing dynamically in the frontend. in model.py i have written- from django.db import models class Destination(models.Model): id = models.IntegerField name = models.CharField(max_length=100) img = models.CharField(max_length=100) desc = models.CharField(max_length=100) price = models.IntegerField But while migration i am facing the below errors- The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 68, in ensure_schema editor.create_model(self.Migration) File "C:\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 331, in create_model self.execute(sql, params or None) File "C:\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute cursor.execute(sql, params) File "C:\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File … -
Django admin foreign key field combo box
Previous I modified html input of Django charfield to html texture by admin.py from django.contrib import admin from .models import * from django import forms # admin CharField as TextArea class ModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'header': forms.Textarea, 'params': forms.Textarea, 'desc': forms.Textarea, 'code': forms.Textarea, } return super().get_form(request, obj, **kwargs) admin.site.register(Func, ModelAdmin) admin.site.register(Example, ModelAdmin) admin.site.register(Tag, ModelAdmin) I wonder if there is way to change a foreign key field into a combo box. I did following: from django.contrib import admin from .models import * from django import forms # admin CharField as TextArea class ModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'belong': forms.ComboField, 'header': forms.Textarea, 'params': forms.Textarea, 'desc': forms.Textarea, 'code': forms.Textarea, } return super().get_form(request, obj, **kwargs) admin.site.register(Func, ModelAdmin) admin.site.register(Example, ModelAdmin) admin.site.register(Tag, ModelAdmin) however I got: TypeError: __init__() missing 1 required positional argument: 'fields' the name of the foreign key field is belong, any suggestion will be appreciated. -
Paypal server side integration in python
I am unable to follow this.I want to use it in my django application. Can you please show me how to use these things or where to place those code. Or if you have any other ways to integrate the paypal payment gateway(server side) in python, Please help me!! thank you -
Django Query to get count of all distinct values for column of mongodb ArrayField
What is the best way to count all distinct values in mongodb ArrayField? Here is my model: class tweet(models.Model): topic = models.JSONField() 3 sample documents: 1. ["investment", "economy"] 2. ["investment"] 3. ["economy", "politics"] Desire result: [{"investment":2},{"economy":2},{"politics":1}] Maybe something like this: tweet.objects.annotate(t=Func(F('topic'), function='$unwind')).values_list('t').annotate(c=Count('_id')) any help would be appreciated -
Custom text for exceptions and informations in external python libraries
How can I translate (customize) some strings and arguments in an external library without changing it directly (without modifying the library)? For example this is line 103 of file oauth2_grants.py in rest_framework_social_oauth2 library: if not user: raise errors.InvalidGrantError('Invalid credentials given.', request=request) And I want receive something like this when it return to my program: if not user: raise errors.InvalidGrantError('اطلاعات شناسایی نا معتبر', request=request) Is there any way to translate/change library texts without modifying directly? -
ajax call not firing up success function on status 200
I'm trying to implement a simple login system using Django. The page takes credentials and submits them to server using ajax call. If information submitted is correct,it logs in user. Otherwise, it returns a json response which should give an alert. Below is view which returns json response on invalid information submitted. def login(request): email=request.POST['email'] password=request.POST['password'] username=get_object_or_404(users,email=email) user=authenticate(username=username,password=password) if user is not None and user.active_status: request.session['id']=user.pk return render(request,'home.html') else: return JsonResponse({"status":"1"}) and javascript part handling ajax using jquery <script> $("#submit").click( function(){ var email= $("email").val(); var password=$("password").val() $.ajax({ url: $(".login-form").attr('action'), method:"POST", data:{ 'email':email, 'password':password, 'csrfmiddlewaretoken' : '{{ csrf_token }}' }, dataType: 'json', success: function(){ alert("wrong") } From debug section of browser, it gives status 200 on wrong credentials but doesn't execute alert. Instead it changes entire page to blank html with only text '{"status":"1"}' which was json response by server. I've tried changing or omitting 'dataType' in ajax call but that doesn't seem to work. Please help with it -
How to convert a array of dictionaries in form of string into an array javascript?
Read the full question before you say duplicate, I have imported an array from python, the array is in form of string for example - "["{"key1":"value1","key2":"value2"}","{"key1":"value1","key2":"value2"}"]" I want to parse this into an actual array in javascript, so basically I want it like - [{"key1":"value1","key2":"value2"}, {"key1":"value1","key2":"value2"}] I have tried a way though it didn't produce the results I wanted temp = JSON.parse(testVal); //testVal is that array On debugging temp I got it value as ["{'key1': 'value1', 'key2': 'value2'}", "{'key1': 'value1', 'key2': 'value2'}"] It converted it into array but the dictionary remained in string format. So I thought I should not convert each dictionary into string so changed array to - "[{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value1', 'key2': 'value2'}]" But this gave me error on parsing - Uncaught SyntaxError: Unexpected token ' in JSON at position 2 Is there any possible way to do this? Any help is appreciated