Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django annotate one model queryset with another model's queryset method
I am not sure if what I want to do can be done. I want to filter or exclude elements from one QuerySet object, using the annotated values of the QuerySet of another model, related to the first via FK. models Below an overview of the models I'm talking about: the two models sit in my main.models.py a Member class and its Manager from django.db import models from django.contrib.auth.models import UserManager class MemberManager(UserManager): def get_queryset(self): return MemberQuerySet(self.model, using=self._db) def annotate_something(self): return self.get_queryset().annotate_something_important() class Member(User): objects = MemberManager() field_1 = models.BooleanField(default = False) field_2 = models.CharField(max_length = 1, blank = True, null = True) ... an Experience class and its Manager class ExperienceManager(models.Manager): def get_queryset(self): return ExperienceQuerySet(self.model, using=self._db) def annotate_duracion(self): return self.get_queryset().annotate_duracion() class Experience(models.Model): objects = ExperienceManager() member = models.ForeignKey(Member, related_name='experiences', on_delete = models.CASCADE) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) note the FK in Experience to Member both MemberQuerySet and ExperienceQuerySet classes are defined in a separate main.queryset.py file class MemberQuerySet(models.QuerySet): def annotate_something_important(self): return self.something_important ... class ExperienceQuerySet(models.QuerySet): def annotate_duration(self): current_date = datetime.now().date() return self.annotate( end_date_obj = Case( When(end_date = None, then = Value(current_date)), default = F('end_date'), output_field = DateField(), ) … -
DRF multiple qyeryset serializer
need some help with serializers. I am a beginner in DRF. I query for objects and serialize each with their own model serializer then manually write down all serializer data in the response in json format. I am sure there is a better way to do this that could also be more efficient. Currently my code looks like this: class GetData(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = request.user subjects = Subject.objects.all() serializersubject = SubjectSerializer(subjects, many=True) subject_skill_levels = SubjectSkillLevel.objects.filter(user=user) serializer2 = SubjectSkillLevelSerializer(subject_skill_levels, many=True) topic_skill_levels = TopicSkillLevel.objects.filter(user=user) serializer3 = TopicSkillLevelSerializer(topic_skill_levels, many=True) progress = Progress.objects.filter(user=request.user).order_by("-date") todays = progress[:1][0] last_5_days = progress.exclude(id=todays.id)[:5] todays_serializer = ProgressSerializer(todays) last_5_days_serializer = ProgressSerializer(last_5_days, many=True) history = ExerciseToken.objects.filter(user=request.user, completed=True).order_by("-id") history_serializer = HistorySerializer(history, many=True) notes = Note.objects.filter(user=request.user) notes_serializer = NotesSerializer(notes, many=True) data = { "username": user.username, "subjects": serializersubject.data, "skill_level": { "subjects" : serializer2.data, "topics" : serializer3.data }, "progress": { "todays": todays_serializer.data, "last_5_days": last_5_days_serializer.data }, "history": history_serializer.data, "notes": notes_serializer.data } return Response(data) -
Running Django Project in PyCharm: ModuleNotFoundError: No module named 'sql_server' - windows10
I was given a zipped django project from others, and after unzipped it, I directly openned it with pyCharm. The directory is as follows, Project logs App Project templates venv db.sqlite3 manage.py It was my very first time using Django, sqlite and Pycharm. It seems like PyCharm could directly connect to the db.sqlite3 database, therefore I did so. And when I ran python manage.py runserver, everything seemingly worked just fine - PS C:\Users\dell\Project> python manage.py runserver engine: Engine(mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes) create engine: mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes engine: Engine(mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes) create engine: mssql+pyodbc://LAPTOP-RITC6JLO/nlp_db?driver=ODBC+Driver+17+for+SQL+Server&trusted_connection=yes Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 15, 2022 - 20:13:53 Django version 4.0.7, using settings 'Project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. But when I openned http://127.0.0.1:8000/, the page shown A server error occurred. Please contact the administrator. with web console giving Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) Then the project terminal gave Traceback (most recent call last): File "C:\Users\dell\anaconda3\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\Users\dell\anaconda3\lib\importlib\__init__.py", line 127, in import_module … -
use the next of the url in the custom login view
I have this customized views login the problem is that when I have a view with the decorators login the url with next does not work but it redirects me to the page I marked in my customized views class Login(auth_views.LoginView): def get_success_url(self): if self.request.user.is_superuser: return reverse('dashboard') else: return reverse('homepage') -
How to choose default choice field from a list
In a django model I need to set a default for a choice field but I don't get how to do the syntax part This is the list CHAT_STYLES = [ ("orange", "orange"), ("purple", "purple"), ("aquamarine", "aquamarine"), ("aqua", "aqua"), ("beige", "beige"), ("yellow", "yellow"), ("green", "green"), ("blue", "blue") ] I tried to do like this chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES."purple") or chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES["purple"]) but it didn't work -
problemas ao criar uma querySet ao fazer uma consulta em loop
Bom dia, tenho esse codigo abaixo que faz uma consulta para buscar ids cadastrados e apos isso, eu percoro essa lista e pego o ID dessa queryset, gero outra consulta com este ID... o meu problema e que essa variavel loadcartrep dentro do loop retorna uma lista [valor1, valor2] e não uma queryset<[valor1:'1', valor2:'2']> e assim não consigo acessar os registros no html para exibir. alguem consegue me ajudar a como eu faço para que essa agregação na variavel loadcarrep+= crie uma lista queryset ou alguma forma de como acessar ou fazer essa consulta com loop funcional? loadcartrep = [] loadcart = carrinho.objects.filter(id_empresa_id=empresa, status__range=[0, 1]) for l in loadcart: log = PecasReposicao.objects.filter(codigoSap=int(l.codigoSap)) if log: loadcartrep = log -
Django hidden field value is not in POST data
I need to send form data via POST request to save a new model instance to DB. I have a hidden field name="owner" in html wich has a value of authorized user id. I can see this value in HTML code, but not in POST request. This gives me Chrome Devtools: <input type="hidden" id="owner" name="owner" value="3"> And this gives me a pyCharm's debugger: cleaned_data = {'latitude': 55.2288, 'longitude': 24.3686, 'comment': '', 'category': <Category: Host>} What is the problem? I have this code in Django views.py: if request.method == "POST": form = AddMarkerForm(request.POST) if form.is_valid(): form.save() messages.success( request, _("Marker added successfully!"), extra_tags="success" ) return redirect(to="home") else: messages.error(request, _("Error. Check coordinates."), extra_tags="danger") else: form = AddMarkerForm() And html: <form class="row g-3" method="post" enctype="multipart/form-data" id="addMarkerForm" name="addMarkerForm"> {% csrf_token %} {% for field in form.visible_fields|slice:":2" %} <div class="col-md-6"> {{ field }} </div> {% endfor %} {% for field in form.visible_fields|slice:"2:" %} <div class="col-12"> {{ field }} </div> {% endfor %} <input type="hidden" id="owner" name="owner" value="{% if request.user %}{{ request.user.id }}{% endif %}"> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% translate "Close" %}</button> <button type="submit" name="submit" class="btn btn-primary">{% translate "Add" %}</button> </div> </form> A form code in forms.py: class AddMarkerForm(forms.ModelForm): """Form for adding a new … -
Django formset not saving with particular code
I have a helper function to save a formset for the model Fields. This function does not save any records, unless I remove a specific piece of code. code that does not save: @transaction.atomic def update_fields_and_fields_group(formset, fg_id, fg_name, ordered_ids): fg = FieldsGroup.objects.get(pk=fg_id) fg.name = fg_name fg.save() # store fields as dictionary fields_list = Fields.objects.filter(fields_group__pk=fg_id) fields_dict = {} for f in fields_list: fields_dict[f.id] = f num_fields = len(fields_dict) # save values instances = formset.save(commit=False) print(instances) for fields in instances: # populate order for new fields with order at the end if not fields.id: fields.order = num_fields + 1 # populate FK fields.fields_group_id = fg_id print(fields.id) fields.save() # save order current_order = 1 for id in ordered_ids: # id is none for new rows if id == 'None': continue fields = fields_dict[int(id)] fields.order = current_order current_order += 1 fields.save() code that does save: @transaction.atomic def update_fields_and_fields_group(formset, fg_id, fg_name, ordered_ids): fg = FieldsGroup.objects.get(pk=fg_id) fg.name = fg_name fg.save() # store fields as dictionary # fields_list = Fields.objects.filter(fields_group__pk=fg_id) # fields_dict = {} # for f in fields_list: # fields_dict[f.id] = f # num_fields = len(fields_dict) # save values instances = formset.save(commit=False) print(instances) for fields in instances: # populate order for new fields with order at … -
Image from an ImageField ModelForm not uploading into the server
Hi so I am new to Django and one of the things I'm trying to do is make a simple gallery application. Somehow I can't add images through the server via the forms if I use a Model Form although I can do it using a plain form. I've tried a lot of the stuff in here and also tried some Youtube stuff but it didn't still work. Here is my models.py from django.db import models from django.urls import reverse from django.core.validators import validate_image_file_extension from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/media') class FavoriteImages(models.Manager): def get_queryset(self): return super().get_queryset().filter(favorite=True) # Create your models here. class Photo(models.Model): name = models.CharField(max_length=120, null=True) photo = models.ImageField(storage=fs, upload_to='media/', validators=[validate_image_file_extension]) date_uploaded = models.DateTimeField(auto_now=True) favorite = models.BooleanField(default=False, blank=False) slug = models.SlugField(null=True, blank=True) gallery = models.Manager() gallery_favorites = FavoriteImages() class Meta: ordering = ['-date_uploaded'] My Views.py from PIL import Image def image_new(request, *args, **kwargs): Image.init() form = PhotoForm(data=request.POST, files=request.FILES) if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save() redirect('../all') context = { 'form': form } return render(request, "form.html", context) My forms.py class PhotoForm(forms.ModelForm): name = forms.CharField(label='',widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title'})) photo = forms.ImageField(widget=forms.FileInput(attrs={'class':'form-control'})) favorite = forms.BooleanField(label='Mark as Favorite',widget=forms.CheckboxInput(attrs={'class':'form-check-input'})) class Meta: model = Photo fields = ['name', 'photo', 'favorite'] my .html … -
AWS Beanstalk django and reactjs app 504 error when registering?
I am trying to get a django REST framework api with reactjs as frontend to work on Beantstalk. The pages are now showing, however when I try to register I get a 504 error. Looking at the logs: First error: /var/log/nginx/error.log 2022/09/14 15:39:29 [error] 4456#4456: *1127 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.32.240, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "django-env1.eba--.us-west-2.elasticbeanstalk.com" /var/log/web.stdout.log Sep 15 10:51:30 ip-172-31-29-189 web: Traceback (most recent call last): Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection Sep 15 10:51:30 ip-172-31-29-189 web: self.connect() Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner Sep 15 10:51:30 ip-172-31-29-189 web: return func(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 225, in connect Sep 15 10:51:30 ip-172-31-29-189 web: self.connection = self.get_new_connection(conn_params) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner Sep 15 10:51:30 ip-172-31-29-189 web: return func(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 244, in get_new_connection Sep 15 10:51:30 ip-172-31-29-189 web: connection = Database.connect(**conn_params) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/MySQLdb/init.py", line 123, in Connect Sep 15 10:51:30 ip-172-31-29-189 web: return Connection(*args, **kwargs) Sep 15 10:51:30 ip-172-31-29-189 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/MySQLdb/connections.py", line 185, in … -
Dockerizing Django. How to reload each time I make changes to my code [duplicate]
I am dockerizing my Django app and I have the following docker-compose.yml file: version: '3' services: # other services as db etc. web: container_name: web build: context: . dockerfile: Dockerfile.web restart: 'always' env_file: - csgo.env ports: - '8000:8000' volumes: - web:/code depends_on: - db volumes: web: I want my container (or the app, idk) to reload whenever I let's say make changes to my models or functions etc. For now, I add some functionality to my app, edit some html views, but no changes appears and the app logs doesn't say that it's reloading. I have to rebuild and up my compose again to see my changes. How to do live-reload composing up? How to send changes to docker? Should I do something with wsgi or gunicorn? I need broad explanation please! Thanks! -
Django 'QuerySet' object has no attribute
With this model: class Batch(models.Model): product = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) stock = models.IntegerField() expiration = models.DateField() This view: @api_view(['GET']) def getByProduct(request, product_name, format=None): try: batches = Batch.objects.filter(product=product_name) except Batch.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = BatchSerializer(batches) return Response(serializer.data, status=status.HTTP_200_OK) And this URL: path('get_by_product/<str:product_name>/', views.getByProduct), I get the following error when running this: http://127.0.0.1:8000/get_by_product/Potatoes/ Got AttributeError when attempting to get a value for field `product` on serializer `BatchSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'product'. However if I force a different error I get this: Cannot resolve keyword 'many' into field. Choices are: created, expiration, history, id, product, stock I cannot .get() as that query expects many batches with the same property "product". -
Django table or Dict: performance?
I have multiple small key/value tables in Django, and there value never change ie: 1->"Active", 2->"Down", 3->"Running".... and multiple times, I do some get by id and other time by name. So I'm asking, if it's not more optimize to move them all as Dict (global or in models) ? thank you -
Django: How to create a registration feauture in django without using the Django Usercreation Form?
I am trying to allow users create an account from without using the from django.forms import UserCreationForm. I just want the users to use just the input field and i can grab unto what ever they are passing into the input field and create an account for them. This is the django forms for creating users with UserCreationForm, how do i now do the same but without the UserCreationForm? views.py def RegisterView(request): if request.method == "POST": form = UserRegisterForm(request.POST or None) if form.is_valid(): new_user = form.save() username = form.cleaned_data.get('email') messages.success(request, f'Account Created') new_user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password1'],) login(request, new_user) return redirect('index') elif request.user.is_authenticated: return redirect('index') else: form = UserRegisterForm() context = { 'form': form, } return render(request, 'userauths/sign-up.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from userauths.models import User class UserRegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
how to solve error (1241, 'Operand should contain 1 column(s)') when using Django with MySQL
I'm Using MySQL database with my Django application, but when i try to save the model it returns this error : (1241, 'Operand should contain 1 column(s)') Here is my code : Model class Proposal(models.Model): """ Model for Proposals """ status_choices = ( ("pending", _("Pending")), ("accepted", _("Accepted")), ("declined", _("Declined")), ) related_request = models.ForeignKey(Request, on_delete=models.CASCADE, verbose_name=_('Request'), help_text=_('Request')) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name=_('User'), help_text=_('User')) price = models.IntegerField(verbose_name=_('Price'), help_text=_('Price')) notes = models.TextField(verbose_name=_('Notes'), help_text=_('Notes'), null=True, blank=True) estimated_time = models.CharField(max_length=100, verbose_name=_('Estimated time'), help_text=_('Estimated time')) date_created = models.DateTimeField(verbose_name=_('Date created'), help_text=_('Date created'), auto_now_add=True) date_modified = models.DateTimeField(verbose_name=_('Date modified'), help_text=_('Date modified'), auto_now=True) status = models.CharField(max_length=100, verbose_name=_('Proposal status'), help_text=_('Proposal status'), choices=status_choices, default="pending") checked_by_admin = models.BooleanField(verbose_name=_("Checked by admins"), default=False, help_text=_( "Check this only if you are an admin and toke actions with this request")) file = models.FileField(upload_to="proposals_files", help_text='File attached with the proposal', verbose_name='Attached file', null=True, ) client_notes = models.TextField(verbose_name=_('Client Notes'), help_text=_('Client Notes'), null=True, blank=True) def __str__(self): return self.related_request.type + ' ' + self.related_request.finishing_type class Meta: verbose_name = _('Proposal') verbose_name_plural = _('Proposals') it returns the error in both stations : 1- when I try to save, edit, or create from the Admin interface. 2- when I try to save or edit using Django rest framework view. DRF View @api_view(["POST"]) @permission_classes([IsAuthenticated]) def react_to_proposal(request): … -
I am using crispy form to render the form. In my form there is one multiple checkbox field.I want to show some options as selected.How to do that
I am using django-crispy-forms. One of the form field is multiple choice checkbox. In this checkbox i wanted to show some options as checked. How to do that. -
Django query (contains, startswith, etc..) always case-insensitive
Whenever I use Django's query functions like name__contains or name__startswith it is always case-insensitive, as if they were name__icontains or name__istartswith. How could I force case-sensitivity? I'm using Django 4.1.1 and Python 3.10 -
Why an ajax query is called twice
I try to update database using ajax query I get row table id on click to send to view for updating data but as my ajax is called twice (why?), second call reverse first call <table> <tbody> {% for dcf in datacorrections %} <tr> <td data-toggle="tooltip" data-placement="top" title="">{{ dcf.ide }}</td> <td data-toggle="tooltip" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td> </tr> {% endfor %} </tbody> </table> $('body').on('click','td', function() { var _id = $(this).attr('id'); $.ajax({ type: 'POST', url: "{% url 'monitoring:deactivate_dcf' %}", data: { "id" : _id }, dataType: 'html', success: function (response) { obj = JSON.parse(response); }, }); }); @login_required @csrf_exempt def deactivate_dcf(request): if request.is_ajax() and request.method == "POST": datacorrection_id = request.POST.get("id") if DataCorrection.objects.filter(ide = datacorrection_id).exists(): if DataCorrection.objects.get(ide = datacorrection_id).deativated == False: DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=True) else: DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=False) return JsonResponse({"response": "success",}, status=200) else: return JsonResponse({"response": "failed","exist":"datacorrection not exist"}, status=404) return JsonResponse({"response":"not_ajax"}, status=200) -
How to get how many seconds are left before session expiration django
In Django I can set the expiration time for the session request.session.set_expiry(300) and after 5 minutes the session ends. When a user makes a request for a view, I want to be able to check how many seconds are left in the current session before it expires. The following method request.session.get_expiry_date() is returning 300 instead of the seconds left. Is there anyway to get the seconds left in a session before it expires? -
View dropdown by condition Django Model Forms
I have a model of categories with a title class Category(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) title = models.CharField(max_length = 20) I have another model with many to many field of categories class Product(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) Category = models.ManyToManyField(Category) title = models.CharField(max_length = 20) Both my models got a user foreign key. I created a product form using django modelforms. class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' The issue I face is that I get the category of another user also. how to show only categories of that particular user? so that one user won't see another user's category -
My API works fine when tested with Postman or ThunderClient but when i integrated swagger it's not showing any parameters
Image 1 showing no parameters in swagger UI Image 2 showing registration endpoint upon registration Image 3 showing login endpoint upon login Below are my code snippets in views.py from rest_framework.response import Response from rest_framework import status from rest_framework.generics import GenericAPIView from rest_framework.views import APIView from account.serializers import ( SendPasswordResetEmailSerializer, UserChangePasswordSerializer, UserLoginSerializer, UserPasswordResetSerializer, UserProfileSerializer, UserRegistrationSerializer, ) from django.contrib.auth import authenticate from account.renderers import UserRenderer from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import IsAuthenticated from drf_yasg.utils import swagger_auto_schema Generate Token Manually def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { "refresh": str(refresh), "access": str(refresh.access_token), } class UserRegistrationView(GenericAPIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = get_tokens_for_user(user) return Response( {"token": token, "msg": "Registration Successful"}, status=status.HTTP_201_CREATED, ) UserLoginView class UserLoginView(APIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get("email") password = serializer.data.get("password") user = authenticate(email=email, password=password) UserLoginView cont'd if user is not None: token = get_tokens_for_user(user) return Response( {"token": token, "msg": "Login Success"}, status=status.HTTP_200_OK ) else: return Response( {"errors": {"non_field_errors": ["Email or Password is not Valid"]}}, status=status.HTTP_404_NOT_FOUND, ) UserProfileView class UserProfileView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = UserProfileSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) #UserChangePasswordView class UserChangePasswordView(APIView): renderer_classes = [UserRenderer] … -
Django Razorpay: Not able to get the post data from the razorpay form
Django razorpar: Error getting the POST data. After making the razorpay payment in test session. I'm Find an error getting the POST data from the url. I am not able to figure out what the problem is My views @csrf_exempt def callback(request): if request.method == "POST": try: payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') course_id = request.POST.get("course_id", '') amount = request.POST.get('amount', '') ... except: messages.error(request, 'Error getting the post data') return redirect('home-page') else: messages.error(request, 'other than post request is made') return redirect('home-page') My payment page <form method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { key: "{{razorpay_key}}", amount: "{{amount}}", currency: "INR", name: "Buy", description: "Test Transaction", image: "https://imgur.com/NOWiBu9", order_id: "{{provider_order_id}}", callback_url: "{{callback_url}}", redirect: true, prefill: { "name": "aa", "email": "aa@gmail.com", "contact": "9898989898" }, notes: { "course_id": "{{course_id}}", "address": "Razorpay Corporate Office", "amount": "{{amount}}" }, theme: { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.open(); </script> <input type="hidden" custom="Hidden Element" name="hidden"> </form> The payments are working fine. The only error is i am not able to get the data. It would be helpful if anyone know whats wrong. -
no data is retrieved after query
I am trying to fetch specific records from the database table based on user input but getting no data in the objj. Can anybody specify the error. objects.all() is also returing no data. views.py from django.views.generic import TemplateView, ListView, DetailView from ssr.models import dinucleotides from ssr.forms import InputForm # Create your views here. def homepage(request): return render(request,'index.html') def searchpage(request): if(request.method == 'POST'): fm=InputForm(request.POST) if fm.is_valid(): print('form validated') Motiff = fm.cleaned_data['Motiff'] obj1=dinucleotides.objects.filter( SSRtype=Motiff) objj={'obj1':obj1 } return render(request,'result.html', objj) else: fm=InputForm() return render(request,'search.html',{'form':fm})``` models.py ``` from django.db import models # Create your models here. class dinucleotides(models.Model): ID = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. Chromosome = models.CharField(db_column='Chromosome', max_length=100, blank=True, null=True) # Field name made lowercase. SSRtype = models.CharField(db_column='SSRtype', max_length=100, blank=True, null=True) # Field name made lowercase. Sequence = models.CharField(db_column='SSRsequence', max_length=10000, blank=True, null=True) # Field name made lowercase. Size = models.IntegerField(db_column='Size', blank=True, null=True) # Field name made lowercase. Start = models.IntegerField(db_column='Start', blank=True, null=True) # Field name made lowercase. End = models.IntegerField(db_column='End', blank=True, null=True) # Field name made lowercase. def __str__(self): return self.dinucleotides``` -
Djoser Password reset confirmation
I have checked many resources,till now I couldn not understand how to setup password reset confirm.How do I do that?I can send email in /u/admin/register/reset_password/ endpoint but when it directs I don't know the process.It said no password reset confirm url,I set it in djoser settings but I got below error.I would like to know whole password reset process in djoser from start. after i click post below error shows up. -
Runserver not working while use_tz = true in Python - Django
I can't runserver or use any commands in terminal after I connect my model with MySQL When I try to change USE_TZ = False in settings.py It's work for me, But I still can't use DateTimeField or DateField in models.py . And I saw other people in Youtube can use models without configure USE_TZ = False and why I can't do that? $ python manage.py makemigrations Traceback (most recent call last): File "C:\Users\UserName\Desktop\MyWeb\MyWeb\manage.py", line 22, in <module> main() File "C:\Users\UserName\Desktop\MyWeb\MyWeb\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\core\management\commands\makemigrations.py", line 119, in handle loader.check_consistent_history(connection) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\migrations\loader.py", line 313, in check_consistent_history applied = recorder.applied_migrations() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\migrations\recorder.py", line 82, in applied_migrations return { File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 320, in __iter__ self._fetch_all() File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\query.py", line 87, in __iter__ for row in compiler.results_iter(results): File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\models\sql\compiler.py", line 1299, in apply_converters value = converter(value, expression, connection) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\db\backends\mysql\operations.py", line 330, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "C:\Users\UserName\Desktop\MyWeb\env\lib\site-packages\django\utils\timezone.py", …