Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which Is best method to display a dynamic html table using Django and want to export data to excel after filter?
I'm new to python and Django, already I know basics of Django and I developed a website using it. The website contains html table and now a new requirement pop up, ask is to add pagination and add filters to all the column and add export option that exports filtered data to excel/csv format. I don't know, can we filter table without refreshing the webpage just using Django? or do we need Ajax & Jquery for it? or is their any better method?, Note: provide me best and latest solution that I can adopt with Django, don't like to have many dependencies and it should work across browsers and platforms. I'm using Django version 3.2.16 and don't want to use django-tables2 module -
django view list of items making them editable
I am listing the rows of a table (fields: Name, Emails, Category, Expiry) via a template: <table border="1" style="width:100%"> <tr> <th style="width:20%">Name</th> <th style="width:40%">Emails</th> <th>Category</th> <th>Expiry </th> <th>Action</th> </tr> {% for obj in expiredlist %} <tr> <td>{{obj.name}}</td> <td>{{obj.emails}}</td> <td>{{obj.category}}</td> <td>{{obj.expiry}}</td> </tr> {% endfor %} </table> Now I want to allow users to edit one of the fields on the fly (like how we do it in datatable). I tried to add a new column by adding: <td><form method="post"> {{form.expiry}} </form> <input type="submit" value="Submit"></td> Thinking that the above will allow users to edit expiry field on the fly. I know I am not passing any info about each row (not able to connect with id). Can someone guide me how can I do this? -
Django: Pass data from template button click to views.py and update template
How can I pass data from my template to views.py and update template with new context data. Preferable a clean update without refreshing the browser would be preferable, but refreshing the site would also be ok. Hope you can help. home.html: <body> <div> <button id="lemon" onclick="passFruit(this)" name="lemon">Lemon</button> <button id="Apple" onclick="passFruit(this)" name="Apple">Apple</button> <button id="Orange" onclick="passFruit(this)" name="Orange">Orange</button> </div> <p>Fruit is: {{ fruit }}</p> </body> <script> function passFruit(fruit) { // Pass fruit to views.py } </script> views.py: class home(TemplateView): template_name = 'home.html' // Get data here from template def get_context_data(self, **kwargs): context = super(home, self).get_context_data(**kwargs) // Update data here and return new context context["fruit"] = fruit return context -
How to persist data when no file is selected with django?
I have a form and I can uplaod a file and return the data of that file. But how to persist the data from the uploaded file when a user has not selected a file and triggers the upload function. What I mean with that is when the data is returned and a user will select again the upload function without selected a file then the returned data will be erased. this is the template: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{form}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> </form> </div> </span> </div> </body> </html> {% endblock content %} and the views.py: def post(self, *args, **kwargs): filter_text = FilterText() types_of_encoding = ["utf8", "cp1252"] submitted_form = UploadFileForm(self.request.POST, self.request.FILES) content = '' if self.request.POST.get('form_pdf') is not … -
django import-export adding _x000D_ when importing content in RichTextField
I am using django-import-export library to handle import and export in my app. The problem is that in my body field I am using CKEditor RichTextField and every time I want to import the content from xlsx, yaml or json I see a lot of _x000D_ instead of empty lines. I've read in the documentation that I could use post_import signal to add some custom login when importing but I am not sure how to add regex that will delete all instances of _x000D_ from my content. How can I fix this issue? -
How to print all value with same name attribute in django and html?
I have django application. With form: <label for="new_chapther" class="plus_crapther_sign">New chapther</label> <button class="actual_plus" id="new_chapther" onclick="createNewChapther()">+</button> <form method="post"> {% csrf_token %} <br> <input type="text" placeholder="title"> <br> <input type="text" placeholder="description"> <br> <div id="chapter"></div> <br> <button type="submit">Submit</button> </form> When I click new chapter button, I trigger createNewChapter function in javascirpt: chapters = 0 function createNewChapther(){ if (chapters >= 100){ } else{ let chapter = document.getElementById('chapter') chapter.innerHTML += ` <br> <div class="added_chapter"> <input type="text" placeholder="chapter title" name="chapter_title"> </div> ` } chapters += 1 } This function adds content in chapter div. I can repeat that 100 times. You see I gave name attribute chapter_title to input. When I click submit in this html form, my view comes into play: def create_chapter(request): if request.method == 'POST': chapter_titles = request.POST.get('chapter_title') for t in chapter_titles: print(t) return render(request, 'quiz_create_form.html') In this view, I get chapter_titles with request.POST.get method. I want to print all value of input with name="chapter_title" in terminal, but when I run this it prints every letter in new line and only takes letters from last input with that name. How can I fix that and get all values printed in terminal? -
How i make api for terms and condition in python?
i have to send terms and conditions data to the user in mobile application but i dont know how to make the models structure for terms and condition in python i try tiny to post the data with the help of tiny editor -
Azure redis cache and Django setup
Am using django-redis in Django to add Azure redis cache, but I am getting issues with the connection, I added the keys password and the hostname and the port but no luck , I get this error : django_redis.exceptions.ConnectionInterrupted: Redis ConnectionError: Error while reading from myhostname.net:6380 : (104, 'Connection reset by peer') I tried reading existing answers but no luck. This is what I have in my Django settings.py : CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.getenv('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'SSL': True, "PASSWORD": os.getenv('REDIS_PASSWORD'), } } } Where REDIS_URL is like this : REDIS_URL=rediss://myhostname.net:6380 and as well as REDIS_PASSWORD the password provided. What could I be missing, am testing this on Digitalocean, I have an SSL activated. -
making auto field Django in certain format in model.py
I'm trying to make auto field like that for invoice which is either part of customers table or invoice table it is okay in the 2 sitautions the format I want like this Year-Month-auto depends on the number before it for example : 202201-001 the first one , 202205-504 like that and it's auto generted once I create new customer model.py class enquiry(models.Model): enq_id = models.AutoField(auto_created = True, primary_key=True) name = models.CharField(max_length=100) Parent_name = models.CharField(max_length=100) Phone1 = models.IntegerField(unique=True) Phone2 = models.IntegerField() email = models.EmailField() place = models.CharField(max_length=50) DOB = models.DateField() # age = models.IntegerField(null=True) def __str__(self): return self.name I'm trying to make full auto id for my invoices so I can use in my view -
Django viewflow running queries in a custom node
I am trying to adapt the Viewflow Dynamicsplit example The objective is to split approvals of an Order based on OrderLines and to assign them to the appropriate approver. It seems that this should be possible as there seems to be a possibility described in this answer - Assign user to tasks automatically (Viewflow, Django) The issue is that whenever I try to grab the current order pk in the DynamicSplitActivation - the queryset comes back empty. Not sure where I am going wrong. The queryset works fine if I set the pk manually, but as soon as I try to use a dynamic variable it stops working. I have listed the flow and models etc. at the end of the post, however, I am guessing the issue is quite basic. Any help would be appreciated! nodes.py ... class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._order = self.flow_task._order_callback(self.process) order_id = self._order.pk # order_id = 28 order_lines = models.OrderLine.objects.filter(order_id=order_id) project_lines = project_models.ProjectLine.objects.filter(orderline__in=order_lines) users = User.objects.filter(projectline__in=project_lines).distinct() self._approvers = users ... class DynamicSplit(...): ... def __init__(self, callback): super(DynamicSplit, self).__init__() self._order_callback = callback self._ifnone_next_node = None ... flows.py ... approval_split = ( nodes.DynamicSplit(lambda act: act.order) .IfNone(this.end) .Next(this.split_approval_budget) ) models.py ... class ProjectLine(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description … -
Django Sites Framework __str__ representation
I'm experimenting with the Django Site framework. In an UpdateView form, the Site model _str_ representation is self.domain, but I want to use self.name. For example, instead of 'www.test.com', I'd like 'Test, Inc.' to appear. I guess I could change the Django Site model code itself (shown below), but I don't really want to do that. I'd rather overwrite the setting in my app or the form view, but I can't figure out how to do either. class Site(models.Model): domain = models.CharField( _('domain name'), max_length=100, validators=[_simple_domain_name_validator], unique=True, ) name = models.CharField(_('display name'), max_length=50) objects = SiteManager() class Meta: db_table = 'django_site' verbose_name = _('site') verbose_name_plural = _('sites') ordering = ['domain'] def __str__(self): return self.domain def natural_key(self): return (self.domain,) When I subclass the Site model, my CustomSite tries to do a join with the Site model and causes complications, so it seems like that approach isn't ideal. class CustomSite(Site): objects = SiteManager() def __str__(self): return self.name class Meta: db_table = 'django_customsite' A simplified version of the form I was testing with is below. The form works. It updates the object with the right site, but I'd still like to know how to use the name as the representation instead of the … -
from sql to Django... i don't understand
i have 3 models (protocollo_pratica, protocollo_soggetto and protocollo_anaprat) and i need extract for each protocollo_pratica a list of soggetti with a specific "tipo" but i don't understand how to make this in django views. Thank you so much for your help. ` this is my models.py : ` from django.db import models # Create your models here. class Soggetto(models.Model): cognome = models.CharField(max_length=100, null=True) nome = models.CharField(max_length=100, null=True) comune_nascita = models.CharField(max_length=100, null=True) data_nascita = models.DateField(null=True) codice_fiscale = models.CharField(max_length=16, null=True) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.nome class Pratica(models.Model): oggetto = models.CharField(max_length=100) anagrafe = models.ManyToManyField(Soggetto, through='Anaprat', through_fields=('pratica', 'soggetto'),) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.oggetto class Anaprat(models.Model): tipo=models.CharField( max_length=50) pratica=models.ForeignKey("Pratica", related_name='pratiche', on_delete=models.CASCADE) soggetto=models.ForeignKey("Soggetto", related_name='soggetti', on_delete=models.CASCADE) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return f"{self.tipo, self.soggetto}"` and this is my sql query : `SELECT p.id, pa.tipo tipo, ps.cognome, ps.nome, ps.data_nascita, ps.comune_nascita from (SELECT id id from protocollo_pratica pp ) p, protocollo_anaprat pa left JOIN protocollo_soggetto ps on ps.id=pa.soggetto_id where p.id=pa.pratica_id` -
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")