Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/React set-cookie: csrftoken and X-CSRF-Token do not match and persists
I've been working through the nightmare that is decoupled React/Django and can't seem to figure out why my CSRF tokens, 1) do not match in the response, and 2) why the cookie is persisting between refreshes. Django View: def get_csrf_token(request): response = JsonResponse({'detail': 'CSRF cookie set'}) response['X-CSRFToken'] = get_token(request) return response Django CSRF Settings: CSRF_COOKIE_SAMESITE = 'Strict' CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_AGE = None React CSRF API Call: getCSRF = () => { fetch("/api/csrf/", { credentials: "same-origin", headers: { "Cache-Control": "no-cache, no-store, max-age=0, must-revalidate" } }) .then((res) => { let reqCsrfToken = res.headers.get("X-CSRFToken"); this.setState({csrf: reqCsrfToken}); }) .catch((err) => { console.log(err); }); } Now, the problem is that every time I ping the view with this call, the response headers between the set-cookie and the x-csrftoken will be totally different. Additionally, the original cookie value will persist across new calls and refreshes. set-cookie: csrftoken=KceWlQsdiQuM....... vs the X-CSRFToken Value x-csrftoken: Ymx3NCe5dwh....... I've checked and printed and logged everywhere, and the cookie value is always different. -
How to create REST viewset for following models.py and serializers.py? i am new with django rest framework
I created an REST API which generate coupon codes, but now i like to redeem/Validate coupon code using Postman, HTML, Python script so anyone can help me to create ViewSets for this models.py and serializers.py file, I am new with django so please little detaild explanation. Thank you Here is my models.py file :- from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my serializers.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Also if there are any mistakes in my code please tell. -
django including URLconf missing argument: 'view'
I'm starting right now with learning Django and I wanted to include a URLconf. I did it like in the comment on the top of the urls.py file. My urlpatterns: urlpatterns = [ path('home/', include('api.urls')) ] This throws me an Error: TypeError: _path() missing 1 required positional argument: 'view' So now I'm asking what is wrong because in the 'documentation' it says: Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) Please help -
Django request.user is still authenticated after logging out
I have a reactjs app with Django as backend. There's a page that has a toggle which makes an API call to the backend updateIsPaid: id => instance({ 'method': 'POST', 'url': BACKEND_RECEIPTS_LIST_URL + id + '/', 'data': id }), and in the backend class ReceiptDetailView(APIView): permission_classes = (permissions.,) def post(self, request, *args, **kwargs): receipt_id = kwargs['id'] receipt = Receipt.objects.get(id=receipt_id) receipt.is_paid = not receipt.is_paid receipt.save() return Response(receipt_id, status=status.HTTP_200_OK) What I've noticed is that when I log out the user in frontend, which destroys the auth token and username stored in localstorage as well as calling django logout in the backend, when i hit the back button and jump back to the page with the toggle, I can still make the POST call and the result is still 200. What I was expecting is the POST call would return a 401. Further investigation shows that the user, while being logged out, the user still passes the IsAuthenticated perm check. This really confuses me and I don't know how to block the accessibility of such user upon logout. Any idea? -
Django upload file + main thread
I'm new to django. I have a question: django is a synchronous framework. Is the main thread blocked when the client sends a file to the server? -
How do I add username of logged in user to model field in django..?
class CustomUser(AbstractUser): email = models.EmailField(unique=True,blank=True,max_length=254, verbose_name='email address') phone_number = models.IntegerField(blank=True,null=True,verbose_name="phone number") ids = models.UUIDField(blank=True,null=True,default=uuid.uuid4, editable=False) parent_id = models.IntegerField(blank=True,null=True) role_id = models.IntegerField(default = auto_increment) I have created a parent_id field in Django customeUser(AbsractUser) Model.I want to populate this field by primary key of the user who is adding the new user in customUser model and the data of user who is adding the new user is in same model only. Thanks in Advance.. -
Django: Zipped file download issue
I got an error : FileNotFoundError at /test/ [Errno 2] No such file or directory: '[' This is an error that might be with the query string in the template or anything else. def submit(request): paths = [list of filenames] context = {'paths' :paths} def test_download(request): paths = request.GET.get('paths') context ={'paths': paths} response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in paths: zip_file.write(filename) zip_file.close() response['Content-Disposition'] = 'attachment; filename='+'converted files' return response templates <p> <a href ="{% url 'test_download' %}?paths={{ paths|urlencode }} " download>Converted Files</a> </p> <br> Help me to find the issue here. -
(DRF) Why make a query before create when unique=True?
I have User model and serializer class which represents it. class User(models.Model): username = models.CharField(unique=True, max_length=50) is_admin = models.BooleanField(default=False) class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = (“username”, “is_admin”) def create(self, validated_data: Dict[str, Any]) -> User: username = validated_data["username"] try: user_object = User.objects.create(username=username) except IntegrityError: raise UserAlreadyRegistered() return user_object My database holds lots of users(appr. 10 million). When I create another user, Django Rest Framework look at the model fields and check that if there are any unique=True fields. If there are, then it assigns “UniqueValidator”. This validator calls “filter_queryset” which means it query the database and check that are there any given username record. If there are not, then it creates the user. My question is, why DRF make a query before create operation? Since database(PostgreSQL) holds the field attributes, it knows that username field is unique, and it can throw an exception if I try to create user with the same username field. The reason I’m asking it, my application gets a lot of create operation, and each create operation I have to query my database, which is I think more costly than create it wihout making a filter query. Do I missing something in this operation? … -
Page not found when trying to use Django url routing
So I've been trying to use django dynamic url routing but when I try to open the link, Django shows me that the page was not found (error 404). Here's my urls.py: from django.urls import path from pages.views import home_view, contact_view from products.views import ( product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view ) urlpatterns = [ path('', home_view, name = 'home'), path('contact/', contact_view, name = 'contact'), path('product/<int:my_id>', dynamic_lookup_view, name='product'), path('create/', product_create_view), path('admin/', admin.site.urls), ] Here's my views.py (Only included the main function which I'm trying to render right now): from django.shortcuts import render from .models import Product #from .forms import ProductForm, RawProductForm # Create your views here. def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/product_detail.html", context) When I'm trying to open the /product/ I get the error. Can anyone tell me what I'm doing wrong? This is the error: Request Method: GET Request URL: http://127.0.0.1:8000/product/ Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order: [name='home'] contact/ [name='contact'] product/<int:my_id> [name='product'] admin/ The current path, product/, didn't match any of these. -
httpd with django3 with python3.6 on Centos7
need urgent help. we are trying to run django3 (python3.6 on Centos7) with httpd. i get following error when i run it by HTTPD. [Tue Jan 12 06:52:04.575618 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] Traceback (most recent call last): [Tue Jan 12 06:52:04.575665 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/srv/django/django/wsgi.py", line 16, in <module> [Tue Jan 12 06:52:04.575670 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] application=get_wsgi_application() [Tue Jan 12 06:52:04.575678 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Jan 12 06:52:04.575682 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] django.setup(set_prefix=False) [Tue Jan 12 06:52:04.575690 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Tue Jan 12 06:52:04.575694 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Jan 12 06:52:04.575701 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ [Tue Jan 12 06:52:04.575706 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] self._setup(name) [Tue Jan 12 06:52:04.575713 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup [Tue Jan 12 06:52:04.575717 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] self._wrapped = Settings(settings_module) [Tue Jan 12 06:52:04.575724 2021] [wsgi:error] [pid 16778] [remote 100.10.100.10:53489] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ [Tue Jan 12 06:52:04.575729 2021] [wsgi:error] [pid … -
My generic Django ListView only updates once the user has logged out. How can I get it to auto-update?
I have a model called Strategy class Strategy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) organisation = models.CharField(max_length=20, default="Enter Text Here") strategy_name = models.CharField(max_length=20, default="Enter Text Here") summary = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ["-created_date"] verbose_name_plural = "strategies" @property def name(self): return "%s - %s" % (self.organisation, self.strategy_name) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('strategy_detail', args=[str(self.id)]) There are two views associated with the model. A ListView: class StrategyListView(ListView): model = Strategy context_object_name = 'strategy_list' template_name = 'simulator/strategy_list.html' And a FormView: class StrategyDefineView(FormView): template_name = 'simulator/strategy_define.html' form_class = StrategyForm success_url = '/simulator/' def get_initial(self): initial = super().get_initial() initial['user'] = self.request.user return initial def form_valid(self, form): form.save() return super().form_valid(form) When the user submits a form from the FormView, they are returned to the ListView. My problem is the ListView doesn't update until the user logs out and logs back in. So, if I submit a form on the FormView, I'm returned to the ListView where I don't see my submission. However, if I'm logged in as superuser, the ListView will update without the user logging out if I go to admin and then return to the ListView page. Does anyone know how I can … -
Removing Null nested fields in Django Serializer --- or how to iterate with Null?
This issue I am having is likely a React iteration problem but I think taking care of it at the root inside Django will be more efficient instead of on the front end. Possible remedies: ternary operation to conditionally display objects and parameters if not null remove null fields from response to avoid needing to do ternary operation through django itself Although, in the first place, I cannot seem to be able to iterate through my response. I have a double nested serializer: Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class VideoProduct(models.Model): ... class ImageProduct(models.Model): ... class ProfileProduct(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) video_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True) image_product = models.ForeignKey(VideoProduct, on_delete=models.CASCADE, blank=True) class Meta: unique_together = ('profile', 'video_product') unique_together = ('profile', 'image_product') Views.py: class VideoProductViewSet(viewsets.ModelViewSet): queryset = VideoProduct.objects.all() serializer_class = VideoProductSerializer class ImageProductViewSet(viewsets.ModelViewSet): queryset = ImageProduct.objects.all() serializer_class = VideoProductSerializer class ProfileProductsViewSet(viewsets.ModelViewSet): queryset = ProfileProduct.objects.all() serializer_class = ProfileProductsSerializer class ProfileBySlug(generics.ListAPIView): serializer_class = ProfileBySlugSerializer def get_queryset(self): slug = self.request.query_params.get('slug', None) queryset = Profile.objects.filter(slug=slug) if slug is not None: queryset = queryset.filter(slug=slug) return queryset Serializers: class VideoProductSerializer(serializers.ModelSerializer): class Meta: model = VideoProduct fields = ['id', 'price'] class ImageProductSerializer(serializers.ModelSerializer): class Meta: model = ImageProduct fields = ['id', 'price'] class ProfileProductsSerializer(serializers.ModelSerializer): video_product = VideoProductSerializer(read_only=True) image_product … -
how can i send file and get it in my app consumers.py to save it in my server
I'm making a chat application using django, django-channels, I could handle the text messages (send them via my front to consumer and save them or any other operation..), but I'm trying to send file and save them into my server, I can only get the name of the file as in my chat.html <script type="text/javascript"> ... var loc = window.location; var msg = $("#id_message") var formData = $("#form") var attachment = $('#chat-attachment').val(); var wsStart = "ws://"; if(loc.protocol == "https:"){ wsStart = "wss://" }; var endpoint = wsStart + loc.host + loc.pathname; var socket = new ReconnectingWebSocket(endpoint); socket.onopen = function(e){ console.log("open for", me ,e) formData.submit(function(event){ event.preventDefault() var msgText = msg.val() var finalData = { "message": msgText, "attachment": attachment, } if(msgText.trim()){ console.log("msg sent!") socket.send(JSON.stringify(finalData)) formData[0].reset() } }); }; ... my consumers.py ... async def websocket_receive(self, event): # print("msg recevied!", event) front_text = event.get("text", None) if front_text is not None: loaded_dic_Data = json.loads(front_text) msg = loaded_dic_Data.get("message") att = loaded_dic_Data.get("attachment") user = self.scope['user'] username = "default" if user.is_authenticated: username = user.username # save it to db # here i want the file to store it in my server print(f"event, {event}") myResponse = { "message": msg, "username": username } # brodcast msg to chatroom await … -
Django, I am trying to reduce ChoiceField form size but failed to do so? Help Appricated
I am able to reduce the text form size using the below properties in css. input {max-width: 16em}; Image for your reference But I am failed to reduce the multichoice drown field. Here is my moodle.py class ResultQuery(models.Model): os_choice = ( ('Select an Institution', 'Select an Institution'), ('School of Management', 'School of Management'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) Here is my forms.py from django import forms from search.models import ResultQuery from django.forms import MultipleChoiceField, ChoiceField, Form class ResultForm(forms.Form): Reg_No = forms.CharField() Name = forms.CharField() OS = forms.ChoiceField(choices=ResultQuery.os_choice) And also want to inform you that I am using a crispy form with bootstrap4 to render but it is coming to verify a big field where the multichoice text is bigger than what I have typed inside the multichoice. I have added a screenshot for your reference. -
How to save record ModelForm with belong to relationship django
I'm trying to adding or change the record in database based on id user, for example if there's no record profile exists from current user then create new one. if I add exists code it's okay because instance is model with get id as user_id Here's the code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=171) bank_name = models.CharField(max_length=191, null=True) bank_account = models.CharField(max_length=191, null=True) profile_picture = models.ImageField(upload_to='profile_pics', blank=True) phone_number = models.CharField(max_length=191) description = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @classmethod def get_accounts(cls, user_id): q = cls.objects.filter(user_id=User(pk=user_id)).first() try: return { "id": q.user.id, "username": q.user.username, "name": q.name, "profile_picture": q.profile_picture.url, "phone_number": q.phone_number, "bank_name": q.bank_name, "bank_account": q.bank_account, "description": q.description } except AttributeError as err: raise err.with_traceback(err.__traceback__) forms.py from django import forms from .models import UserProfileInfo class PatchUserProfileForm(forms.ModelForm): class Meta: model = UserProfileInfo fields = ('name', 'phone_number', 'profile_picture', 'description', 'bank_name', 'bank_account') class views.py @method_decorator(csrf_exempt, name='dispatch') class APIAccounts(View): def get(self, requests): if requests.user.is_authenticated: try: return JsonResponse(UserProfileInfo.get_accounts(requests.user.id), status=200) except AttributeError: return JsonResponse({"message": "Access denied"}, status=403) else: return JsonResponse({"message": "Unauthenticated"}, status=401) def post(self, requests): if requests.user.is_authenticated: try: try: data = UserProfileInfo.objects.get(user_id=requests.user.id) form = PatchUserProfileForm(requests.POST, requests.FILES, instance=data) except ObjectDoesNotExist: # … -
validate method not called django rest framework
I am trying to test validate method on modelSerializer but it is NOT CALLED. Why is not working ? Have i been missed something ? the same scenario works at different project at urls urlpatterns = [ path('api/allposts/', allposts, name='allposts') ] at views: from .serializer import PostSerializer from rest_framework.renderers import JSONRenderer from .models import Post from django.http import JsonResponse import json def allposts(request): qs = Post.objects.all()[:3] ser = PostSerializer(qs, many=True) data = JSONRenderer().render(ser.data) return JsonResponse(json.loads(data), safe=False) at models class Post(models.Model): title = models.CharField(max_length=100) url = models.URLField() poster = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title at serializer from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['title', 'poster', 'url'] def validate(self, data): if 'facebook' in data.get('url'): raise serializers.ValidationError('you can not add facebook') return data -
AbstractUser User With mongoengine in django
I am using mongodb(3.6) in python(3.8.5) django(3.1.5). and i have used djonjo(1.3.3) and mongoengine(0.22.1) for mongoDB. now i have trying to create AbstractUser model with mongoengine`s Document. and also i have create django model with EmbeddedDocument. like - from mongoengine import Document, EmbeddedDocument, fields class UserDepartment(EmbeddedDocument): department = fields.StringField(max_length=250, unique=True) created_at = fields.DateTimeField(default=datetime.now()) updated_at = fields.DateTimeField(default=datetime.now()) so it not adding in migration file and also not creating mongodb collection with this model. so how could i create AbstractUser and EmbeddedDocument model in mongoengine and migrate them -
Unauthorized: /msal/login_with_code/ while using pypi package: drf_msal_jwt
I am trying to implement Azure SSO with Django as Backend and React as Frontend. I was able to implement generate-login-url and login-with-code functionalities with the help of the documentation and it successfully runs in the postman. But implementing the same via react does not give the same result. I inspected the package and in the below code for login class MSALLoginWithCodeView(APIView): authentication_classes = [] permission_classes = [] def post(self, request, format=None): msal_check_state = api_settings.MSAL_CHECK_STATE code_serialized = CodeSerializer(request.data) if msal_check_state and request.session.get('msal_state', '') != code_serialized.data['state']: raise StateException() user_token = get_user_jwt_token(code_serialized.data['code']) return Response({ 'token': user_token }) I am getting different results while checking the same url via postman and my implementation with react. For postman I for the value request.session when i inspect it with request.session.__dict__ I get {'_SessionBase__session_key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'accessed': True, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, '_session_cache': {'msal_state': 'xxxxxxxx-xxx-xxxx-xxxx-xxxxxxxxxxxx'}} and will work correctly and will return a token, but for react implementation I get {'_SessionBase__session_key': None, 'accessed': False, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>} What do I need to update? -
How to find models where their member queryset contains another models query set in django
say I have the following models flag user project userflag -user fk -flag fk projectflag -project fk -flag fk what I want is the queryset of users where their set of flags contains the set of flags on a specific project, something like user.objects.filter(project.projectflag_set_in = userflags) -
How to redeem coupon code which i created in django?
I created Coupon code in django rest framework and now i like to redeem it using python script or any frontend method, i don't have way, path or logic which can guide me on how to do it. Here is my models.py file : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my serializers.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' here is my views.py file from django.shortcuts import render from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer Please do help -
I am making an User(AbsrtactUser) model and I need to make a field that auto increments
class CustomUser(AbstractUser): email = models.EmailField(unique=True,blank=True,max_length=254, verbose_name='email address') phone_number = models.IntegerField(blank=True,null=True,verbose_name="phone number") ids = models.UUIDField(blank=True,null=True,default=uuid.uuid4, editable=False) #parent_id = models.IntegerField(blank=True,null=True) role_id = models.IntegerField(null=True,blank=True) How do i create role_id as auto_increment field. I tried making role_id field AutoField but that just gave me an error that we cannot have 2 Autofield in one model and I dont want to make any changes with django default id primary key as i need that field. can we give reference of (id primary key) to (role id)..? -
Changing appearance of 'Remember Me' field for django-allauth+crispy_forms
I want to change the appearance of the "Remember me" checkbox but I can't find a solution that will work. Here is what I have right now: Image Additional info: Django==3.0.11 django-allauth==0.44.0 Running in the Docker Viewed in Chrome Macos Catalina Here is the code in the template: <form class="login" role="form" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form|crispy }} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary shadow-2 mb-4" type="submit" >{% trans "Sign In" %}</button> </form> I have tried to have a nested dict with css styling inside the form (based on this answer), but no luck so far. Here is the form from forms.py: class UserLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) # self.helper.form_show_labels = False # Doesn't work though it should self.fields["login"].label = "" self.fields["password"].label = "" self.fields["remember"].widget.attrs.update({ "div": { "class": "form-group text-left", "div": { "class": "checkbox checkbox-fill d-inline", "input": { "type": "checkbox", "name": "checkbox-fill-1", "id": "checkbox-fill-a1" }, "label": { "for": "checkbox-fill-a1", "class": "cr" } } } }) I do not want to go into the package itself to … -
I have stored the data in json format in Js file. i want to bring it to django.views how can i do that?
I am using Django where i am working with some project. In that i have stored the data in JSON format in JS file i want to render it and bring it to Views for further use.How can i use do it? JS: function save(){ var quizform=[]; quizform.push({quizname: document.getElementById("Quizname").value}); for (var z = 1; z <= container_count; z++) { var obj = new Object(); obj.question = document.getElementById("Q".concat(z.toString())).value; obj.answers = new Object(); obj.answers.a = document.getElementById("Qa".concat(z.toString())).value; obj.answers.b = document.getElementById("Qb".concat(z.toString())).value; obj.answers.c = document.getElementById("Qc".concat(z.toString())).value; obj.answers.d = document.getElementById("Qd".concat(z.toString())).value; obj.answers.e = document.getElementById("Qe".concat(z.toString())).value; obj.correctAnswer = document.getElementById("CorrectOption".concat(z.toString())).value; quizform.push(obj); } var myjson = JSON.stringify(quizform); console.log(myjson); } HTML: {% extends 'base.html' %} {% load static %} {% block content %} <body> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/popup.css'%}"> <div id="FC" class="flex-container"> </div> <div class="buttons"> <button id="add-question" class="add-question">+</button> <button id="save" class="save" method="POST">save</button> </div> <script type="text/javascript" src="{% static 'assets/js/CQ.js'%}"></script> </body> {% endblock %} Views: from django.shortcuts import render,get_object_or_404,redirect from students.models import * def PreviewQuizCreating(request,slug): session=get_object_or_404(Session_Details,slug=slug) context={'session':session} return render(request,'CQ.html',context) I need the variable myjson to my views -
'QuerySet' object has no attribute 'gmail'
I am working with Django. my models.py: class Admin(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, related_name='admin_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) def __str__(self): return self.name Now I am trying to get a list of gmail inside to named variable. in my views.py: def submit_report(request, pk): admin_obj = Admin.objects.all() to = admin_obj.gmail print(to) return redirect('app:index') but it says error like: Internal Server Error: /submit_report/1/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\django\hackathon practice\ProjectSurokkhaBeta_1.7\app\views.py", line 532, in submit_report to = admin_obj.gmail AttributeError: 'QuerySet' object has no attribute 'gmail' [12/Jan/2021 09:48:54] "GET /submit_report/1/ HTTP/1.1" 500 77827 How can I fix it? -
TypeError at /order 'datetime.time' object is not callable Django
I want to make estimate making order time in my Django Apps but I am confuse about the time that cannot be calculated. I defined the datetime first then values, so I reduce the datetime - values, which I hope the result is now time reduced by datetime. here is my templatetags\cart.py : @register.filter(name="estimasipending") def estimasipending(datetime): values = (datetime.datetime.today) return datetime - values` here is my Views order.py : from django.shortcuts import render, redirect from django.views import View from store.models import Customer from store.models import Order class OrderView(View): def get(self,request): customer_id = request.session.get('customer') orders = Order.objects.filter(customer=customer_id).order_by("-date").order_by("-id") print(orders) return render(request,'order.html',{"orders":orders})` here is my HTML template {% for order in orders %} <tr> <td>{{ forloop.counter }}</td> <td><img height="80px" width="100px" src="{{ order.product.image.url }}" alt=""></td> <td>{{ order.product }}</td> <td>{{ order.price|currency }}</td> <td>{{ order.quantity }}</td> <th>{{ order.quantity|multipy:order.price|currency }}</th> <th>{{ order.date }}</th> <th>{{ order.datetime }}</th> {% if order.completed %} <th><span class="badge badge-success">Your Order is Ready</span></th> {% elif order.confirmed %} <th><span class="badge badge-success">We are making your order estimate {{ order.datetime|estimasipending }}</span></th> {% else %} <th><span class="badge badge-warning">Pending</span></th> {% endif %} </tr> {% endfor %}` and the error show like this : TypeError at /order 'datetime.time' object is not callable sorry for my bad english, I still learn.