Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
offset and limit in django rest framework
I've set the offset and limit in the query. like this. queryset = Comments.objects.filter(language_post_id=post_in_lang_id, is_post_comment=True).order_by("-created_on")[offset:offset+limit] # 2 : 2 + 2 It is working fine, but in the pagination response, I'm getting the wrong count of the query. { "response": true, "return_code": "success", "result": [ { "id": 36, "user_id": 3, "language_post_id": 16, "is_post_comment": false, "parent_post_comment_id": 20, "description": "Comment on post in English!!!!", "created_on": "2022-09-12T07:44:33", " ... " }, { "id": 35, "user_id": 4, "language_post_id": 16, "is_post_comment": false, "parent_post_comment_id": 20, "description": "Comment on post in English!!!!", "created_on": "2022-09-12T07:44:32", " ... " } ], "message": "Success", "next": null, "previous": null, "count": 2 } but I got the "count": 2 it should be the number of all rows. and also one more doubt. I'm trying to do like whenever we are getting data query_set every time the database should fire the query according to limit and offset. So I made it possible through costume [offset:limit]. it looks hardcoded. Is there any better way to make it soft? Dose DRF pagination work the same as I'm trying to do? -
I am trying to register new user from Django to PostgreSQL from the app which I created but it is not getting updated in database
I am trying to register new user from Django to PostgreSQL from the app which I created but it is not getting updated in database, but logs are getting generated in PostgreSQL for my each attempts from Django framework and the database table screenshot has been attached here. I also noticed Django.contrib import error but I think it is not problem because rest all codes working fine like I am able to upload photos from admin panel and it is reflecting in my web portal and database as well. .............................................. #accounts\views.py. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect("/") else: messages.info(request,'invalid creds') return redirect('login') else: return render(request,'login.html') def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email taken') return redirect('register') else: user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() messages.info(request,'User created') return redirect('login') else: messages.info(request,'Password not matching') return redirect('register') return redirect('/') else: return render(request,'register.html') … -
How to annotate integer as a ForeignKey in django?
I have this model: class Order(Model): sale_address = ForeignKey(Address) purchase_address = ForeignKey(Address) and want to conditionally annotate one address or another depending on some condition, as a ForeignKey: order = Order.objects.annotate( address=... # sale_address if current user is seller ).first() assert isinstance(order.address, Address) # True How can I do that? I've tried this: annotate( address_id=Case( When( user_role='SELLER', then=F('sale_address'), ), When( user_role='BUYER', then=F('purchase_address'), ), ), ) but in this case address_id is just an integer and I get N+1 issues when making list of orders with address.region. -
Extract body values from Django request in Django middleware
I want to extract the body part from the request in middleware. The body contains some user-related variables and the second thing file that which the user has uploaded. Code : class DSCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): body_value = request.body resulting_param_value = #some got on values which i am getting from body if "True" in resulting_param_value: return HttpResponse("Please Provide Valid Input!!!") else: response = self.get_response(request) return response I have tried to extract with request.data but it doesn't work in middleware. I have also tried with request.body it works but partially. It gives me values in bytes and the format looks like the below. b'------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="user_name"\r\n\r\na\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="dataset_name"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="project_name"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="description"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="dataset_description"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="model_type"\r\n\r\nRegression\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="visibility"\r\n\r\nprivate\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="inputfile"; filename="CarPrice_Assignment.zip"\r\nContent-Type: application/octet-stream\r\n\r\nPK\x03\x04\n\x00\x08\x00\x08\x00\xbap)U\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00\x00\x00CarPrice_Assignment.csv\xbd]Ko\xe3\xc6\xb2\xde\x07\xc8\x7f\xe02\x018F\xbf\x1f\xebs6gq\x0ep\x17\xf7\xe2\xee.h\x89\x96\x19\xd3\xa2@R\xf6x~\xfd\xad\xaa\xe6\xab%J$\x95I\x80$\xf0Ll}_WWW\xd7\xb3\xbd\xcb\xea\xff\xfb\xd7?\xd3\xe6\xeb\xfd\xb9*\x8b\xe3!\xfdGV\xff\'{\xcf\xd3\x97s^\xb6_\xa7<\xcd\x9aSQgmQ\x1d\xd3}U\xd5\xc7\xf3\xfbs^\xa7\xbb\xac~\xae\xf6_\xe9\xbe.>\xf2\xcf\xd7</\xd3\xfcx(\x8eyY\xed\xc27\xd3_>gM\x8e\xdf[\xc2\xffl_\xf1\xab\xcfb\x1f\xbex\xcd\x8b\xc3k\x9b\xee\xce\xf5\xf3g\xf82|\x00\x81\xee\xbe\x80\xcc>\xef\xd1\xc2\xffi\x8a\x1f\x81W\xf3\xd5\xb4\xf9{\xfa\\\xd591K\x9b\xb6\xae\xde\xe0\xa7\xaa\xf7S\x9d7\r\xc0\x87\xbf\x7f\xad\xea&?U\x9f\xf0\x11\xa7<{\xabO\xef\xe9\xaeh\xbf\xdeO\x87\xf4\x15 ?3\xfa\xf2T\x17\xbb\xfc\xd7_x*\xd3\xac|\xc9\xbe\xd5\xd5{^W\xc9\xa18\x97E\x96\x1e\xb2\x06>\x7f\x9f\xb6\x9f\x15\x00\x1c?\xf2\xba-\x9e\xcb<\xad?\xf7\xe9K]\x1d\xdb\xd4\xb9\'\x93r\xe3\x9e\\j\xd4\x13O\x15~%\xb4r \xb0\xd7]\xfaR\x9d\xeb\x94K\x96\xbe\x9f^\x8aT>)\x9b\x8a\'\xe3R\x9fr\xceS\xcd\x18K\x05O\x85\x85\xefQ^\xff\xfa\x8b\xb8\xe0\x01k-?' I have also tried to convert it using JSON but it give error like 'utf-8' codec can't decode byte 0xe7 in position 894: invalid continuation byte -
How do I call this function on a button press?
problem here is I want Student to be deleted everytime this delete button is pressed and refresh page/stay on current page, I am stuck with this problem, any solution? <div class="content"> {% for student in students %} <p class= 'my-2 text-center'> {{student.name}} | {{student.bio}} <button type="button" class="btn btn-danger">Delete</button> </p> {% endfor %} </div> -
Setting an option that can only be viewed by users in a certain group
I am quite new to django and am building a project using django and python predominantly. I have two user groups in djangos admin panel created and defined there with user added through this admin panel; Diving_Officers and Club_Members In my webpage, i have an option that i want to only be visible or even clickable to the users in one group, the Diving_Officers group. I cannot find any specific information for how to call a group that exists in django admin and assign it permissions or how to limit a view to it. -
Django/Wagtail Model Admin fields not showing in API
I am using wagtail and I have a ModelAdmin called sorting. I have a PageChooserPanel inside the ModelAdmin. I have exposed these in API but it's showing only id of the table but not showing full details. But in my database, I can view them. API Response Models screenshot Here is my `views.py class FeaturedList(APIView): def get(self, request): featured =Featured.objects.all() serializer= FeaturedSerializer(featured, many = True) return Response(serializer.data) serializers.py class FeaturedSerializer(serializers.ModelSerializer): class Meta: model = Featured fields = ("featured_name","featured_pages",) models.py from django.db import models from wagtail.models import Page, Orderable from modelcluster.fields import ParentalKey from blog.models import * from wagtail.models import Page from wagtail.admin.panels import PageChooserPanel, FieldPanel, InlinePanel from django.utils.translation import gettext_lazy as _ from modelcluster.models import ClusterableModel from modelcluster.fields import ParentalManyToManyField class IDChoice(models.IntegerChoices): Featured1 = 0, _('Featured1') Featured2 = 1, _('Featured2') Featured3 = 2, _('Featured3') Featured4 = 3, _('Featured4') Featured5 = 4, _('Featured5') class Featured(ClusterableModel): featured_name = models.IntegerField(default=IDChoice.Featured1,choices=IDChoice.choices, blank=True, null=False, help_text='Featured ID', unique=True) panels = [ InlinePanel('featured_pages', label="Featured pages"), FieldPanel('featured_name'), ] class FeaturedPages(Orderable, models.Model): """ Orderable helper class, and what amounts to a ForeignKey link to the model we want to add featured pages to (Featured) """ featured_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) featured_item = ParentalKey( Featured, related_name='featured_pages', … -
How to properly set up custom User model and multiple databases with Django?
I created a custom application to authenticate users and have hard times to make everything work with multiple databases. Help would be much appreciated. Basically, I create multiple Django projects and want a unique database for authentication and a custom AUTH_USER_MODEL. The databases are declared in settings.py with two routers, one for the auth, contenttypes, and authentication application, and the other router for the rest of the applications. I successfuly migrated the custom User model and created createsuperuser with the option --database=auth_db but then, when I work in the admin section with Celery beat Django throws an error : IntegrityError at /admin/django_celery_beat/crontabschedule/add/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_authentication_user_id" DETAIL: Key (user_id)=(1) is not present in table "authentication_user". As you can see, it says the user with ID 1 isn't created, but I'm logged with it and I'm 100% sure the custom User model was created in the authentication app: root@ec00652b9b9a:/app# python manage.py migrate authentication --database=auth_db Operations to perform: Apply all migrations: authentication Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying authentication.0001_initial... OK root@ec00652b9b9a:/app# python manage.py migrate contenttypes --database=auth_db Operations to perform: Apply all migrations: contenttypes Running migrations: No migrations to apply. root@ec00652b9b9a:/app# python manage.py … -
Django Is the server running on host "localhost" (127.0.0.1) and accepting web | TCP/IP connections on port 5432?
I am trying to dockerize my Django application. My configs are the following: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', 'PORT': '5432', } } .env file POSTGRES_USER='DB_USER' POSTGRES_PASSWORD='DB_PASSWORD' POSTGRES_DB='DB_NAME' POSTGRES_HOST='localhost' POSTGRES_PORT='5432' Dockerfile.web FROM python:3.9-bullseye WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY csgo . RUN apt-get update -y \ && apt-get upgrade -y pip \ && pip install --upgrade pip \ && pip install -r requirements.txt CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3' services: web: container_name: web build: context: . dockerfile: Dockerfile.web env_file: - .env volumes: - .:/code ports: - '8000:8000' depends_on: - db db: image: postgres:13 restart: always ports: - '5432:5432' env_file: - .env volumes: postgres_data: Now, when I docker-compose up all appear to be working fine besides connection to the database. I get this error: django.db.utils.OperationalError: could not connect to server: Connection refused web | Is the server running on host "localhost" (127.0.0.1) and accepting web | TCP/IP connections on port 5432? web | could not connect to server: Cannot assign requested address web | Is the server running on host "localhost" (::1) and accepting web | TCP/IP connections on port 5432? Can you please help me solve this problem? Additionally, … -
DJANGO URL TAGS LINKING
Please i'm new into django, I created a project named marketbook, it has a main templates directory and an app called users. Inside my app (users) i have templates folder as well with a file called login.html (templates/users/login.html. I want to link this login.html in my app to a link in my file (navbar.html) in my main templates director folder. what should be the url tag to use kindly help. <a href="{% url 'users:login' %}" class="btn" style="color: white; background-color: #fd5e14; margin-left: 10px; "type="submit" id="header-links">Log In -
django model linking with another model to create a form
I am trying to develop a scoring sheet app for my club. I have models for Player, Scoresheet, Season ,etc. What I would like to achieve is basically when a game takes place, the scoresheet model will have a form where the person can capture the total score of the team and also the goals of each player. My issue is how do I link the players stats to the scoresheet in a form, for example the player model has goals scored, freekicks taken, red cards, yellow cards. I want the scoresheet model form to be able to fill out that stats for each player. I am aware that something is missing or I am doing something wrong. I am not sure what it is. my Models are as follows class Player(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="playeruser") Player_name = models.CharField(max_length=40) Player_surname = models.CharField(max_length=40) Player_ID = models.CharField(max_length=40) Player_Email = models.CharField(max_length=40) Player_Contact = models.CharField(max_length=40) category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name="pcategory") Player_preferred = models.CharField(choices=Roles,default="default",max_length=16) def __str__(self): return self.Player_name + " " + self.Player_surname class Score_sheet(models.Model): season = models.ForeignKey(Season,on_delete=models.CASCADE,related_name="season") category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name="sscategory") players = models.ManyToManyField(Player,related_name="players") captain = models.ForeignKey(Player,on_delete=models.CASCADE,related_name="captain") Date = models.DateField() Venue= models.CharField(max_length=40,null=True,blank=True) description = models.TextField(null=True,blank=True) goals= models.IntegerField(null=True,blank=True) freekicks = models.IntegerField(null=True,blank=True) redcards = models.IntegerField(null=True,blank=True) yellowcards = models.IntegerField(null=True,blank=True) def __str__(self): … -
Invalid value of type 'datetime.date' received for the 'name' property of frame and Received value: datetime.date(2022, 8, 15)
I am trying to plot an animated scatter plot using plotly. Using a date-wise animation frame, but I am getting an error Invalid value of type 'datetime.date'. fig = px.scatter(df1,x=df1['MeterReading_DateTime'], y=df1['ACT_IMP_TOT'], color=df1['MeterReading_DateTime'],animation_group=df1['MeterReading_DateTime'],animation_frame=df1['MeterReading_DateTime'],size=df1['ACT_IMP_TOT'],size_max=55,title='') Here I am sharing the data frame. -
Django ulr does not accept query string
I have a view in Django that redirects a user to some url with aditional query string: return redirect('search/?print_id='+str(pk)) In my urls.py, the url pattern looks like this: path('search/', views.search, name='search'), And the problem is when Django tries to redirect, I get the following error: Reverse for 'search/?print_id=36' not found. 'search/?print_id=36' is not a valid view function or pattern name. How can I modify the url pattern to accept a query string? -
Django PDF admin
I tried to find a solution like Export django model as pdf from admin model to add PDF from the admin page in the specific object(articles) and display it in these objects and also be able to download them Thanks!!! -
when creating django project via docker container it says sh: django-admin: not found
I created a docker python image on top of alpine the problem is that when I want to start a django app it can not find django and it is right bcz when I type pip list, it does not have django and other packages. ps: when creating the images it shows that it is collecting django and other packages this is my Dockerfile: FROM python:3.9-alpine3.13 LABEL maintainer="siavash" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH = "/py/bin:$PATH" USER django-user and this is docker-compose.yml version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" and this is the command that I use: docker-compose run --rm app sh -c "django-admin startproject app . " BTW the image is created successfully -
Posts are not showing on Djangohomepage while adding pagination in posts and categories
I did mistake somewhere and i didn't get it. before pagination my allposts and categories were working properly. after doing pagination my all previous posts are not displaying. I am sharing my codes so plz help me to solve it. views.py: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from blog.models import Post from blog.models import Category from .forms import ContactForm from django.shortcuts import get_object_or_404 from django.views.generic.list import ListView #from django.views import generic from django.core.paginator import Paginator from django.views import View # Create your views here. ''' # this is my older working code before pagination def allpost(request): #post = Post.objects.all() post = Post.objects.all().order_by('-public_date') # 'public_date' taken from 'ordering = ['-public_date']' from class meta in models.py return render(request,'posts.html',{'posts':post}) ''' def allpost(request): PostData = Post.objects.all().order_by('-public_date') paginator = Paginator(PostData, 5) page_number = request.GET.get('page') PostDataFinal = paginator.get_page(page_number) totalpage = PostDataFinal.paginator.num_pages data = { #'Post': PostDataFinal, 'PostData': PostDataFinal, 'lastpage': totalpage, 'totalpagelist': [n + 1 for n in range(totalpage)] } return render(request, 'posts.html', data) def CategoryView(request, page): # here cats is same which mentioned in dynamic url. category_posts = Post.objects.filter(category__title=cats) paginator = Paginator(article_list, 2) page_number = request.GET.get('page') totalpages = paginator.get_page(page) context = { 'category_posts':category_posts, 'lastpage':totalpages, 'articlespageslist':[n + 1 for n in range(totalpages)] } … -
Ensuring uniqueness across multiple models Django
I have three models: Account, Employee and Company. An account can be of the type employee or company and a OneToOne Field relates an account to either an employee or company record. See models below: class Account(auth_models.AbstractBaseUser): username = models.CharField(max_length=40, unique=True) ACCOUNT_TYPE_CHOICES = ( ("company", "Company"), ("employee", "Employee"), ) account_type = models.CharField( choices=ACCOUNT_TYPE_CHOICES, default="EMPLOYEE", blank=False, null=False, max_length=10, ) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["account_type"] I then have the Company model: class Company(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, unique=True) name = models.CharField(max_length=75, blank=False, null=False, unique=True) Then I have the Employee model, where an Employee is also related to the company it is employed by: class Employee(models.Model): user = models.OneToOneField(Account, on_delete=models.CASCADE, unique=True) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) date_of_birth = models.DateField(null=False, blank=False) employer = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="employees" ) employment_start_date = models.DateField(null=False, blank=False) employment_end_date = models.DateField(blank=True, null=True) I want to make sure usernames are unique within the company, but not unique within the whole web app. So there can be multiple users with the same username, but not within the same company. For example: Suppose a user created an account with the username John Smith with the company … -
Django,duration calculation between 2 fields using timestamp
I have this model table. In this table,in stay column ,I have fields as stay and on move I need to calculate whole time taken duaration for consecutive stays and on_move . my function for stay column field value updates : def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude lat2 = rowpairs[1].latitude long1 = rowpairs[0].longitude long2 = rowpairs[1].longitude lat = abs(lat2 - lat1) long = abs(long2 - long1) earth_radius = 6373.0 a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = earth_radius * c * 1000 for rowpair in rowpairs: row_id = rowpair.id po = TestLocation.objects.filter(id=row_id) if lat < 0.0009 or long < 0.0009: po.update(stay="stay") po.update(processed=True) else: po.update(stay="on_move") po.update(processed=True) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) my approach was adding empty list before i range for loop and append timestamps into it based on if condition take first and last items from list and get difference in minutes and save that duration in last stay field before on_move field.same process goes to on_move field time duaration calculation. -
Why textarea doesnt send data with this form?
I have a form that looks like I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> <textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') -
Django: error trying to validate an email verification otp
I'm sending an email to the user on register and getting the otp together with the email, I have a separate verify model that looks like below the error I'm facing is {"message": "This OTP is invalid"} which has something to do with peace of code in the verifyEmail view(down below) class Verify(models.Model): email = models.EmailField( _("Email"), max_length=254, unique=True, default=None, blank=True, null=True) otp = IntegerRangeField( min_value=111111, max_value=999999, blank=True, null=True) created_at = models.DateTimeField( _("created at"), auto_now=False, auto_now_add=True, blank=False) expires_at = models.DateTimeField(null=True) def __str__(self) -> str: return self.email how I'm sending the email def send_opt_email(email, firstname, lastname): otp = random.randint(100000, 999999) subject = 'Email verification' message = 'Email verification' html_message = loader.render_to_string( 'email_verify.html', { 'firstname': firstname, 'lastname': lastname, 'otp': otp, } ) email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [ email], fail_silently=True, html_message=html_message) otp = Verify.objects.create( email=email, otp=otp, created_at=datetime.now(), expires_at=datetime.now() + timedelta(minutes=30) ) otp.save() this is the view I use to validate the otp class Verify_Email(APIView): """ Verify registered emails """ def post(self, request): try: data = request.data serializer = VerifySerializerBase(data=data) if serializer.is_valid(): email = serializer.data['email'] otp = serializer.data['otp'] verify = Verify.objects.get(email=email) user = User.objects.get(email=email) try: if user.is_active: return Response({ 'message': "This email has already been verified" }, status=status.HTTP_400_BAD_REQUEST) elif verify: print(verify.email) print(verify.otp) … -
Please resolve PS C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts> python Potentiostat_GUI.py
PS C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts> python Potentiostat_GUI.py Measurement frequency: 500.02083420142503 Hz Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Avinash\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_GUI.py", line 228, in Send_CV_Settings self.user.set_Scan_rate(_scan_rate) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_userinput.py", line 46, in set_Scan_rate self.comm.usb_write(scan_rate_formatted) # Send command File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_communication.py", line 76, in usb_write self.ep_out.write(message) AttributeError: 'NoneType' object has no attribute 'write' Plot title is stored. Plot legend is stored. Cyclic Voltammetry initialization has started. Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Avinash\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_GUI.py", line 273, in Start_CV_scan self.user.run_CyclicVoltammetry() File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_userinput.py", line 113, in run_CyclicVoltammetry self.comm.usb_write("R") File "C:\Users\Avinash\OneDrive - hyderabad.bits-pilani.ac.in\Documents\Python Scripts\Potentiostat_communication.py", line 76, in usb_write self.ep_out.write(message) AttributeError: 'NoneType' object has no attribute 'write' -
Apple M1 run Django display symbol not found in flat namespace '_PQbackendPID'
I am use django to build the project, when I run python manage.py makemigrations it get the error message: Traceback (most recent call last): File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/psycopg2/_psycopg.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mingzhe/Desktop/webapp/electric/electric/manage.py", line 22, in <module> main() File "/Users/mingzhe/Desktop/webapp/electric/electric/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/Users/mingzhe/Desktop/webapp/electric/env/lib/python3.10/site-packages/django/db/models/base.py", line 141, in __new__ new_class.add_to_class("_meta", Options(meta, … -
Django/Wagtail Type error 'ModelBase' object is not iterable
I have a project with wagtail. I have created a custom model Admin named sorting. I want to show this model's data in API. Here is the view in the database Here is models.py from django.db import models from wagtail.models import Page, Orderable from modelcluster.fields import ParentalKey from blog.models import * from wagtail.models import Page from wagtail.admin.panels import PageChooserPanel, FieldPanel, InlinePanel from django.utils.translation import gettext_lazy as _ from modelcluster.models import ClusterableModel from modelcluster.fields import ParentalManyToManyField class IDChoice(models.IntegerChoices): Featured1 = 0, _('Featured1') Featured2 = 1, _('Featured2') Featured3 = 2, _('Featured3') Featured4 = 3, _('Featured4') Featured5 = 4, _('Featured5') class Featured(ClusterableModel): featured_name = models.IntegerField(default=IDChoice.Featured1,choices=IDChoice.choices, blank=True, null=False, help_text='Featured ID', unique=True) panels = [ InlinePanel('featured_pages', label="Featured pages"), FieldPanel('featured_name'), ] class FeaturedPages(Orderable, models.Model): """ Orderable helper class, and what amounts to a ForeignKey link to the model we want to add featured pages to (Featured) """ featured_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) featured_item = ParentalKey( Featured, related_name='featured_pages', null=True, on_delete=models.CASCADE, ) panels = [ FieldPanel('featured_page'), ] def __str__(self): """String repr of this class.""" return self.featured_page class Meta: # noqa verbose_name = "Featured" verbose_name_plural = "Featured Stories" admin.py from .models import * from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register,) class SortingAdmin(ModelAdmin): model = Featured menu_lebel= "Sorting" … -
Displaying the history of the child object in the history of the parent object in Django admin
I have a problem in showing a child object in parent history in django admin , as you can see in following screenshot when I create or make a change in child object(comment) from inlines it doesn't display in parent object(ticket) history . This mode is only for the mode where I use inlines, if I create an object separately through the child model itself, it will not even be displayed as an empty space. I would be very grateful if somebody can tell me how I can display child history in parent history, for example I want to display what happened to child (comment) in blank spaces. here is my code in admin: @admin.register(models.Ticket) class TicketAdmin(SimpleHistoryAdmin): actions = ['change_status_to_close'] autocomplete_fields = ['member'] list_display = ['id','owner','title','create_time','last_update','status','comments_count','history'] list_select_related = ['member'] list_editable = ['status'] list_filter = ['status',('create_time',DateTimeRangeFilter), ('last_update',DateTimeRangeFilter)] list_per_page = 20 history_list_display = ['changed_fields_with_values','status'] search_fields = ['id'] sortable_by = ['create_time','last_update','id','status'] def changed_fields_with_values(self, obj): fields = "" if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: fields += str("{} changed from {} to {}".format(change.field, change.old, change.new)) return fields return None @admin.display() def history(self,ticket:models.Ticket): url = reverse('admin:ticketing_ticket_history',args=[str(ticket.id)]) return format_html('<a href="{}">History</a>', url) -
Run a python function depends on the checkbox
I'm working on a python project and I want to call a function if a checkbox was checked. For expample if the yes checkbox was checked the first function will be called. I made this code, but it always calls the second function even if I checked the yes checkbox. I don't know what the issue. Any help is highly appreciated. this is my html : <input type="checkbox" id="vehicle1" name="mycheckboxname" value="yes"> <label for="vehicle1"> Without comments</label><br> <input type="checkbox" id="vehicle2" name="mycheckboxname" value="no"> <label for="vehicle2"> With comments</label><br> And this is my view.py def datatable_view(request): if request.method =='POST': form = Scraping(request.POST) if form.is_valid(): mylist=request.POST.getlist('mycheckboxname') if 'yes' in mylist: subject=form.cleaned_data['subject'] scrap(subject) client = pymongo.MongoClient("mongodb://localhost:27017/") db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) else: subject=form.cleaned_data['subject'] hello(subject) client = pymongo.MongoClient("mongodb://localhost:27017/") # use variable names for db and collection reference db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} #open datatable html and display all the data from database return render(request,'datatable.html', context) return