Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgresql database throwing errors on connection
I am running a Postgresql database on AWS and the backend is Django. After some requests, let's say 50, it raises the error "OperationalError: terminating connection due to administrator command SSL connection has been closed unexpectedly" but the database will still remain active. At first, it was throwing "OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections" after some requests, so I have a script that closes open connections. Here is the script: export PGPASSWORD='mypassword' psql --host=dbhost.myregion.rds.amazonaws.com --port=5432 --username=user --dbname=name \ -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND state in ('idle', 'idle in transaction', 'idle in transaction (aborted)', 'disabled') AND usename != 'rdsadmin';" but the errors keep coming. I have also tried increasing the max_connections to 150, but it still doesn't help. I have also tried using AWS RDS proxy, but still no hope. Here is how I connect to the DB from django: DATABASES = { 'default': { 'ENGINE': config('DB_ENGINE'), 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), 'CONN_MAX_AGE': 0 } } -
Drf class based view how to manage method calls
I have been working on FBV in Django and am now trying out CBV. I have created a basic crud application Views.py class UserViews(APIView): permission_classes = [IsViewOnly | IsManager | IsAdmin | IsStaff] def get_objects(self, user_id): #query def post(self, request): #create code def get(self, request): #details code def put(self, request): #update code def delete(self): #code urls.py urlpatterns = [ path('add-user/', views.UserViews.as_view(), name="create-user"), path('update-user/', views.UserViews.as_view(), name="update-user"), path('delete-user/', views.UserViews.as_view(), name="delete-user"), path('list-users', views.UserSearchList.as_view(), name="list-user"), path('view-user', views.UserViews.as_view(), name="view-user"),] This code is working but, how do we prevent a situation where say a manager wants the view user details API but executes it with the delete method and the user is now deleted -
how can I update one field in Django rest framework in abstract user model
how can I update one field in the Django rest framework in the abstract user model can someone help me I want to Update device_id in my abstract user model I want to only update device_id dield without updating other field and I do not know I have to create another view or not or I should add update to serializers here is my code models.py class User(AbstractUser): is_student=models.BooleanField(default=False) is_teacher=models.BooleanField(default=False) mobile_no=models.CharField(max_length=200,blank=True) device_id=models.CharField(max_length=200,blank=True) USERNAME_FIELD = 'username' def __str__(self): return self.username class Meta: verbose_name_plural="1.User" @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False,**kwargs): if created: Token.objects.create(user=instance) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username','mobile_no','is_student','device_id'] views.py class StudentSignupView(generics.GenericAPIView): serializer_class=StudentSignupSerializer def post(self,request,*args,**kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, # "message":"account created successfully" }) class TeacherSignupView(generics.GenericAPIView): serializer_class=TeacherSignupSerializer def post(self,request,*args,**kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, # "message":"account created successfully" }) class CustomAuthToken(ObtainAuthToken): def post(self,request,*args,**kwargs): serializer=self.serializer_class(data=request.data, context={'request':request}) serializer.is_valid(raise_exception=True) user=serializer.validated_data['user'] token,created=Token.objects.get_or_create(user=user) return Response({ 'token':token.key, 'user':UserSerializer(user, context=self.get_serializer_context()).data, 'is_student':user.is_student }) -
Need for installing a server for django app deployment on various hosting sites
On finishing with a django site, do I need to install for e.g nginx and uwsgi before uploading it to heroku or pythonanywhere? If no, does it mean heroku or pythonanywhere provides the server for me? And which places do not provide the server and I therefore need to install nginx and uwsgi or gunicorn. What are the differences between those that provide the server and those that don't? Which is good? -
How to retrieve the docker image of a deployment on heroku via circleci
I have a django application running locally and i've set up the project on CircleCi with python and postgres images. If I understand correctly what is happening, CircleCi would use the images to build a container to test my application with code database. Then I'm using the job heroku/deploy-via-git to deploy it to Heroku when the tests are passed. Now I think Heroku is using some images too to run the application. I would like to get the image used by heroku to run my site locally on another machine. So pull the image then push it to Docker Hub and finally download it back to my computer to only have to use a docker compose up. Here is my CircleCi configuration's file version: 2.1 docker-auth: &docker-auth auth: username: $DOCKERHUB_USERNAME password: $DOCKERHUB_PASSWORD orbs: python: circleci/python@1.5.0 heroku: circleci/heroku@0.0.10 jobs: build-and-test: docker: - image: cimg/python:3.10.2 - image: cimg/postgres:14.1 environment: POSTGRES_USER: theophile steps: - checkout - run: command: pip install -r requirements.txt name: Install Deps - run: name: Run MIGRATE command: python manage.py migrate - run: name: Run loaddata from Json command: python manage.py loaddata datadump.json - run: name: Run tests command: pytest workflows: heroku_deploy: jobs: - build-and-test - heroku/deploy-via-git: requires: - build-and-test … -
I want only users who don't have inactive comments to post new comments
Comment matching query does not exist. inactive_comments = Comment.objects.get(active=False, profile=profile) This is my view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(user=request.user) inactive_comments = Comment.objects.get(active=False, profile=profile) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return HttpResponseRedirect(request.path_info) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags, 'inactive_comments': inactive_comments}) This is my comment models: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) and this is my template: {% if request.user.is_authenticated %} <div class="new_comment"> {% if inactive_comments %} <h4>نظر شما با موفقیت ثبت شد و در حال بررسی است.</h4> {% else %} <h4>نظر خود را اضافه کنید</h4></br> <form method="post"> <div class="row" dir="rtl"> <div class="col-sm-12 col-md-8"> {{ comment_form.body|attr:"class:form-control"|attr:"type:text" }} </div> </div> {% csrf_token %} <div class="row"><br/> <div class="col-sm-12 col-md-8"> <input type="submit" value="ارسال نظر" class="btn send btn-primary" href="#"></input> </div> … -
How to get 5 quotes from page?Bs4
there is my script: @shared_task() def parser(): flag = True url = 'https://quotes.toscrape.com' suffix = '' while flag: responce = requests.get(url + suffix) soup = BeautifulSoup(responce.text, 'html.parser') quote_l = soup.find_all('span', {'class': 'text'}) q_count = 0 for i in range(len(quote_l)): if q_count >= 5: flag = False break quote = soup.find_all('span', {'class': 'text'})[i] if not Quote.objects.filter(quote=quote.string).exists(): author = soup.find_all('small', {'class': 'author'})[i] if not Author.objects.filter(name=author.string).exists(): a = Author.objects.create(name=author.string) Quote.objects.create(quote=quote.string, author_id=a.id) q_count += 1 else: a = Author.objects.get(name=author.string) Quote.objects.create(quote=quote.string, author_id=a.id) q_count += 1 next_page = soup.find('li', {'class': 'next'}) if not next_page: flag = False break suffix = next_page.a['href'] I need to get 5 new quotes in one run of the program, but I get 5 only on the first run, and on the other 10.tried to change the nesting nothing helped.what do you advise? -
pandas set_index not working as expected for multiple columns
df = pd.DataFrame( [[21, 'Amol', 72, 67], [21, 'Amol', 78, 69], [21, 'Kiku', 74, 56], [22, 'Ajit', 54, 76]], columns=['rollno', 'name', 'physics', 'botony']) print('DataFrame with default index\n', df) Then when we do this: df = df.set_index(['rollno','name']) print('\nDataFrame with MultiIndex\n',df) The output we get is: DataFrame with MultiIndex physics botony rollno name 21 Amol 72 67 Amol 78 69 Kiku 74 56 22 Ajit 54 76 What I want is: physics botony rollno name 21 Amol 72 67 78 69 Kiku 74 56 22 Ajit 54 76 So the set_index is grouping the first column of 'rollno' but not the second column of 'name' how can I get this? Context: I'm doing this to covert pandas df to html with rowspans for first 2 columns -
Pass jquery variable to img src static in Django template
I am getting a list of file names (they are .jpg images) from a django view as an Ajax response. I want to append each image to a div (with id grid). Below is the code: success: function(response) { var state = response.state; var piclist = response.pics.toString(); var pics = piclist.split(','); // alert(pics); for (var i=0; i < pics.length; i++) { // alert(pics[i]); // var fname = state + '/' + pics[i]; // var fpath = "{% static '" + fname + "' %}"; // alert(fpath); $('#grid').append( "<div class='col-md-2 mb-2 posr'>" + "<input type='checkbox' class='custom-control-input chk pos-ab'>" + "<img src='{%static fpath %}' class='img-thumbnail'>" + "</div>" ); } } I am unable to pass the file path variable ts/pics[i] to img src static. I tried Jquery template literals too but that also didnt work. How to pass the filepath variable? -
uvicorn access denied to run django server
I'm just trying run the server via uvicorn package. installed it with pip and fire this command to run that : uvicorn my_project.asgi:application --reload but it's not working and return access denied error here is full error message : Program 'uvicorn.exe' failed to run: Access is deniedAt line:1 char:1 + uvicorn my_project.asgi:application --reload At line:1 char:1 + uvicorn my_project.asgi:application --reload + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed Note: I run this command in both vscode and git bash. the result is the same! any point? -
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile:
I'm doing a personal full-stack project just for practice but I keep getting this error for the docker commands after I try to run these docker commands as I am trying to build some microservices in separate containers. I run these commands: docker volume create tren-data docker compose build and I get this error. failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount3296053497/Dockerfile.dev: no such file or directory docker error message This is what I wrote for my docker.yaml file. I would like to know and understand where I am going wrong with this. I had already premade each of the microservices already with the django and I believe it's with how I am making my docker file. volumes: ghi: external: true tren-data: external: true services: react: image: node:lts-bullseye command: /bin/bash run.sh working_dir: /app volumes: - ./ghi:/app ports: - "3000:3000" environment: HOST_OS: ${OS} NODE_ENV: development HOST: "0.0.0.0" NUTRITION_APP_API_KEY: ${NUTRITION_APP_API_KEY} WORKOUT_APP_API_KEY: ${WORKOUT_APP_API_KEY} REACT_APP_NUTRITION_HOST: http://localhost:8091 REACT_APP_WORKOUTS_HOST: http://localhost:8080 REACT_APP_ACCOUNTS_HOST: http://localhost:8090 REACT_APP_GYMS_HOST: http://localhost:8081 database: build: context: ./relational-data dockerfile: ./Dockerfile.dev volumes: - tren-data:/var/lib/postgresql/data environment: - POSTGRES_MULTIPLE_DATABASES=accounts,gyms,nutrition,workouts - POSTGRES_PASSWORD=test-databases ports: - 15432:5432 workouts-api: build: context: ./workouts/workouts_rest dockerfile: ./Dockerfile.dev ports: - "8080:8000" volumes: - … -
Unable to get activation E-mail in django
I am trying to get an activation email from Django but have not received any email. Now less secure app access is now banned from google so I created an app password which was advised by the youtube channel but I still not get the output here are my tables: Views.py from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.shortcuts import redirect, render from django.utils import timezone from django.core.mail import send_mail, EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_encode , urlsafe_base64_decode from .tokens import generate_token def Register(request): if request.method=='POST': # username=request.POST.get('Username') username=request.POST['Username'] password=request.POST['Password'] Fname=request.POST['Fname'] Lname=request.POST['Lname'] Email=request.POST['Email'] PhoneNo =request.POST['PhoneNo'] Age=request.POST['Age'] if User.objects.filter(username=username): messages.error(request,"Username already exits! Please try some other username.") if User.objects.filter(email=Email): messages.error(request,"Email ID already exits! Please try some other Email ID.") myuser =User.objects.create_user(username,Email,password) myuser.first_name=Fname myuser.last_name=Lname myuser.save() messages.success(request,"Your Account has been successfully created. We have sent you a confirmation email, please confirm your email to activate your account.") #Welcome Email subject ="Welcome to the largest Community of art" message="Hello there!! "+ Fname+"\nWelcome to some place where you can share your art ,learn about different forms of art and teach your creative … -
how to add variable in django url in a loop so for each entry the url changes
im new to django i created a loop which lists all entries on a page. but i can't add a variable which will link the name of the entry to it's html page without having to hardcode it. index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href= "{% url "{{entry}}" %}">{{entry}}</a></li> {% endfor %} </ul> {% endblock %} my views.py from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def html(request): return render(request, "encyclopedia/html.html") def css(request): return render(request, "encyclopedia/css.html") -
Pass select element to json
How do I make it pass the selected element to javascript. I managed to make it appear to select but when saving it is not going. Appedit.html <div class="modal fade edit-modal1" id="modaledit1" tabindex="-1" role="dialog" aria-labelledby="modaledit1label" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modaledit1label">Update Appointment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="updateappointment" action=""> <div class="modal-body"> {% csrf_token %} <label for="doc" >Doctor</label> <select class="select_doctor" name="select_doctor"> {% for user in users %} <option id="form-doc" value="{{user.id}}" name="formDoc" class="form-control">{{user.username}}</option> {% endfor %} <label for="date" >Date</label> <input class="form-control" id="form-date" type="date" name="formDate"/> <label for="time">Time</label> <input class="form-control" id="form-time" type="time" name="formTime"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="saveappointment">Save</button> </div> </form> </div> </div> </div> script.js function updatepatielement(element){ element.addEventListener("click", function(event) { event.preventDefault(); $('#modaledit1').on('show.bs.modal', () => { var saveButton = document.querySelector(".modal-footer > #saveappointment"); tr_id1 = null; date = null; time = null; id = element.getAttribute("idappointment"); if (id) { tr_id1 = "#appointment" + id; doc1 = $(tr_id1).find(`#DocName${id}`); date1 = $(tr_id1).find(`#AppoiDate${id}`); time1 = $(tr_id1).find(`#AppoiTime${id}`); $('#form-doc').val(doc1); $('#form-date').val(date1); $('#form-time').val(time1); } saveButton.addEventListener("click", () => { var docselect = $('option[name="formDoc"]').val(); var dateInput = $('input[name="formDate"]').val(); var timelInput = $('input[name="formTime"]').val(); console.log(docselect) $('#modaledit1').modal('hide'); fetch('/updateappointme/'+ id, { method: "POST", body: JSON.stringify({ doctor: docselect, date: dateInput, time: timelInput, }), … -
Django : One to Many serializer attribute error
Hello i have one to many model serializer but when I try to make request on it it says attribute error. Got AttributeError when attempting to get a value for field `project` on serializer `clientserializers`. The serializer field might be named incorrectly and not match any attribute or key on the `Client` instance. Original exception text was: 'Client' object has no attribute 'projectname' My model : # client structure class Project(db.Model): project_name = db.CharField(max_length=50, unique=True) def __str__(self): return self.project_name class Reason(db.Model): reason_name = db.CharField(max_length=50, unique=True) def __str__(self): return self.reason_name class Client(db.Model): name = db.CharField(max_length=100) project = db.ForeignKey(Project, on_delete=db.CASCADE, related_name="projectname") reason = db.ForeignKey(Reason, on_delete=db.CASCADE, related_name="reasonname") timestamp = db.DateTimeField(default=timezone.now()) Serializer both for project and reason: class projectserializers(serializers.ModelSerializer): class Meta: model = Project fields =('id', 'project_name') class reasonserializers(serializers.ModelSerializer): class Meta: model = Reason fields =('id', 'reason_name') class clientserializers(serializers.ModelSerializer): project = projectserializers(source="projectname", many=True) reason = reasonserializers(source="reasonname", many=True) class Meta: model = Client fields = ('id', 'name', 'timestamp', 'project', 'reason') -
How do I merge and sort JSON objects using its counts?
I got two json objects that I need to combine together based on ID. here is the first object comments: and here is the second object: { { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, { "userId": 1, "id": 4, "title": "eum et est occaecati", "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit" }, } this is second json object: { { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": … -
How can I have a query set in the DetailView?
Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x1024f3c70>. This is the error message and class ProductDetail(DetailView): model = Product def get_context_data(self, **kwargs): context = super(ProductDetail, self).get_context_data() context['related_products'] = Product.objects.filter(category=Product.category) context['categories'] = Category.objects.all() context['no_category_post_count'] = Product.objects.filter(category=None).count return context This is my views.py. A page that shows a product and related items is what I want to present. My questions are 1. Am I not allowed to bring a query set in the DetailView? 2. Then should I use ListView to do so? -
Overwrite/replace instead of update MySql table in a Django Project
Let's say I have df1 which is pulled from a MySql database in a django project: import pandas as pd df1 = pd.DataFrame({'Name': ['John', 'Jim'] ,'City': ['A', 'B'],'Project_id': 1}) df1 Then my function within django adds two rows: line_insert = pd.DataFrame({'Name': ['Jack', 'Jill'] ,'City': ['C', 'D']}) df1 = df1.append(line_insert).reset_index(drop=True) df1 Now i would like to save this dataframe back to the table in the database. My current code updates the sql table row by row (where Project_id = 1) but i am wanting to replace the dataframe with the same Project_id My current code to update the table is (for simplistic sake i have defined some variables first): proj_id = 1 iincreament_id = 1 for index, df_series in df1.iterrows(): dict_df = df_series.to_dict() """ Insertig dataframe into dict """ dict_df['Projectid_id'] = proj_id """ updating SQL DB """ sql_db.objects.filter(id=iincreament_id,Project_id=proj_id).update(**dict_df) iincreament_id += 1 So what this does is updates row 1 & 2 values with their new values but does not replace the sql table with the new table to bring in rows 3 & 4. Is there any ideas on a replace function using the .objects functions with python/django? Thanks very much! -
Why is Django Rest Knox token don't have three sections?
I am new to JWT and integrated django-rest-knox to my project. When I test it in postman, i get a token like b0073060117223714a3405ad7c1516ba61f7216b2165a40cb44b43b2c54d8dd4, but I know that JWT must have 3 sections. Why it don't have ones? -
How do I subtract from exiting model if a request is sent from another model?
Am trying to create a withdrawal request, the request sent successfully as expected but it doesn't subtract from the existing balance. Here's my model. def withdrawals(request): if request.method == 'POST': Input_Amount = request.POST['Input_Amount'] username = request.POST['username'] input_password = request.POST['password'] total = Users_Balanc.objects.get(user=request.user) if Withdrawal_password.objects.filter(username=request.user).exists(): password = Withdrawal_password.objects.get(username=request.user) if password.password3 == input_password: if int(Input_Amount) > 100: if (total.Amount >= float(Input_Amount)): New_Request = Request.objects.create(Wallet_Address=password.Wallet_Address, Amount=Input_Amount, user = username) New_Request.save messages.success(request, 'Successful') return redirect('withdrawals') else: messages.warning(request, 'Insufficient funds') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal is below 100TRX') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal password is not correct') return redirect('withdrawals') else: messages.warning(request, 'Sorry, you haven\'t create a withdrawal password yet.') return redirect('withdrawals') else: balance = Users_Balanc.objects.filter(user=request.user) return render(request, 'withdrawals.html', {'balance': balance}) Even when I add total.Amount - Input_Amount just after if (total.Amount >= float(Input_Amount)) Please what's the way around this? -
Django - Reset all filters
I am trying to clear all filters on button click at once. This is what I have on filters.py file and filters class: class Filters(django_filters.FilterSet): id = django_filters.NumberFilter(label=_("ID")) name = django_filters.TextFilter(label=_("Name")) And in base template: <form id="filters-filters-form" action="javascript:;" onsubmit="onSubmit(this)" class="form form-inline main-filter"> {% bootstrap_form filter.form layout='inline' %} <div> <button class="btn ml-auto mr-2" onclick="resetFilters()">Clear all</button> {% trans "Apply" as button_text %} {% bootstrap_button button_text button_class="btn-primary" %} </div> </form> resetFilters() function: var resetFilters = function() { let formId = document.getElementById('filters-form') let formChildren = formId.childNodes; Array.from(formChildren).forEach(formChild => { formChild.val(null).trigger('change') }); } Is there any easy way to reset all filters? P.S: I need to reset these filters without any id of form-control because it will be reusable base template -
Forward reference must be an expression -- got 'postgresql
I am getting this error Forward reference must be an expression -- got 'postgresql Here is the complete log Traceback (most recent call last): File "/usr/local/lib/python3.9/typing.py", line 528, in __init__ code = compile(arg, '<string>', 'eval') File "<string>", line 1 postgresql+asyncpg://postgres:postgres@db:5432/blog ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/asgi.py", line 3, in <module> from api.app import create_app File "/code/api/app.py", line 2, in <module> from api.database import create_db_and_tables File "/code/api/database.py", line 3, in <module> from api.config import settings File "/code/api/config.py", line 8, in <module> class Settings(BaseSettings): File "/usr/local/lib/python3.9/site-packages/pydantic/main.py", line 179, in __new__ annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) File "/usr/local/lib/python3.9/site-packages/pydantic/typing.py", line 395, in resolve_annotations value = ForwardRef(value, is_argument=False, is_class=True) File "/usr/local/lib/python3.9/typing.py", line 530, in __init__ raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") SyntaxError: Forward reference must be an expression -- got 'postgresql+asyncpg://postgres:postgres@db:5432/blog' Here is how I am using it class Settings(BaseSettings): PROJECT_NAME: str = f"SQLModel API - {os.getenv('ENV', 'development').capitalize()}" DESCRIPTION: str = "A FastAPI + SQLModel production-ready API" ENV: str = os.getenv('ENV', 'development') VERSION: str = "1" SECRET_KEY: str = secrets.token_urlsafe(32) # DATABASE_URI: Optional[PostgresDsn] = None DATABASE_URI: os.environ.get("DATABASE_URL") # sql Where env variable is being set like … -
Html code is not working in django block content
i understand the basic tag blocks but it didn't works well on my page. i have page called base.html and home.html **base.html !DOCTYPE html> <html> <body> {% include 'component/models.html' %} {% include 'component/header.html' %} {% block content %} inside this my code is not comming {% endblock %} {% include 'component/footer.html' %} </body home.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>This code working <h1> <section> <h1>Rahul guptaa1</h1> <div> <h1>Rahul guptaa 2</h1> <div> <h1>Rahul guptaa 3</h1> <div> <h1>Rahul guptaa4</h1> </div> <div> <h1>Rahul guptaa5</h1> </div> </div> </div> <div> <h1>Rahul guptaa6</h1> </div> </section> {% endblock content %} **my output below but Rahul guptaa4 Rahul guptaa6 is not showing ... Rahul guptaa5 Learn On Your Schedule Technology Is Bringing A Massive Wave Of Evolution On Learning Things In Different Ways. ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa5 *** i am not beginner in django but i face problem here i try so many times if you want to know my folder structure below myproject -myproject -App -templates -base.html -main -home.html ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa4 Rahul guptaa5 Rahul guptaa6 ** -
Redirect non authenticated user to login page (for all views)
I am looking to redirect my user to login page, if they have not logged in. I initally looked at the decorator @login_required(login_url='/accounts/login/'). But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth. I am sure this is solvable, but I am looking for a solution that could apply to all views. I found something using authmiddleware(doc: https://pypi.org/project/django-authmiddleware/). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything. Can someone see what I am doing wrong? base.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'AuthMiddleware.middleware.AuthRequiredMiddleware', ] AUTH_SETTINGS = { "LOGIN_URL" : "login_user", "DEFAULT_REDIRECT_URL" : None, "REDIRECT_AFTER_LOGIN" : False, } views.py from django.shortcuts import render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.urls import reverse class AuthRequiredMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login_user')) return None -
django: unable to login after successful registration
login reporting wrong username or password, after a new user is registered successfully. I am sure the there is no typo! below is my code and I guess the problem is to do with the hash code related to the password setup? @csrf_exempt def api_register(request): data = json.loads(request.body) username = data['username'] password_1 = data['password_1'] password_2 = data['password_2'] # 1,check if two pw is same if password_1 != password_2: return JsonResponse({"code": 0, "msg": "pw not consistant"}) else: m = hashlib.md5() m.update(password_1.encode()) password_m = m.hexdigest() # 2 check if username exists users = User.objects.filter(username=username) if users: return JsonResponse({"error": "username already exists"}) else: try: user = User.objects.create_user(username = username, password = password_m) user.set_password(password_m) user.save() user.is_active = True user.success = True ret_data = {"username": user.username, 'uid': user.id, 'password': user.password} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code": 1, "msg": ret_data} except Exception as e: print('--create user error is %s' % e) return JsonResponse({"error": "username already exists"}) return JsonResponse(ret) below is login function @csrf_exempt def api_login(request): data = json.loads(request.body) user = authenticate(**data) #same as authenticate(username=data['username'],password=data['password'] if user: ret_data = {"username":user.username,'uid':user.id} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code":1,"msg":ret_data} print("ret ", ret) else: ret = {"code":0,"msg":"username or password wrong!" } return JsonResponse(ret)