Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Include sensitive environment variables to AWS EB Django app
I am deploying a django app to AWS Elastic Beanstalk and initially I am defining my environment variable in .ebextensions/django.config Some of those variable are sensitive and I don't want to push them to Git, so I want to encapsulate those variables in a single file (for example: .env) that will not be pushed to Git. Plan A: A way to include .env in my config file, but I didn't find a way to do it supposedly like: option_settings: aws:elasticbeanstalk:application:environment: include .env aws:elasticbeanstalk:container:python: WSGIPath: mydjangoapp.wsgi:application Cons: The environment variables are shown as plain text in AWS console at Elastic Beanstalk > Environments > my-environment > Configuration > Environment properties, although I know the fact that they are only readable by the authorised AWS users who have permission to it. Pros: Ability to update only and directly the environment variables from AWS console without requiring new deployment. Plan B: Remove the sensitive variables at all from my config file and load the .env file from my django app itself. Cons: If I want to update any of those variables, I have to deploy a new version of my application. Although .env file will not pushed to Git and it can be … -
AWS access key is showing up in browser url when accessing the s3 content from heroku
I have deployed my django app to heroku and using Amazon s3 bucket to store the static files and I see there is no issues in getting the data from the s3 to the heroku. But, when I'm testing to see the content storage location i'm getting the url path in addition with the AccesskeyID https://myapp.s3.amazonaws.com/img/front_cover.JPG?AWSAccessKeyId=AKIAXPKPZLYKLRB7DR4N&Signature=JzTU0DpmbGSBRpYHwV8Dvt0p1QQ%3D&Expires=1590936351 So I'm concerned up showing up access id in the browser URl, do we have an option to disable this in heroku or django settings or in AWS -
create or edit models and tables dynamically based on user input from a form outside admin panel
I am new to python django and I wanted to ask if there is a suggested way to create an app with ui for the users to be able to create tables on database with models dynamically. So basically I want the user to fill in the table name and desired column names with types on a form and create them dynamically when they hit submit button. this is for an internal application where we do not want to use the admin panel for implementing it as admin panel will have other elements needed. any advise or examples shared to take a look and learn along the road building would be a huge help. Thank you so much for all the support. -
Django model's save method is not called when creating objects in test
I am trying to test one of my application's model Book that has a slug field. I have a custom save function for it, like below. models.py class Book(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def save(self, *args, **kwargs): if not self.slug: slug = slugify(self.title, allow_unicode=True) return super(Book, self).save(*args, **kwargs) To test this, I created the following test.py class BookModelTests(TestCase): @classmethod def setUpTestData(cls): Book.objects.create(title="Book One") def test_get_absolute_url(self): book = Book.objects.get(pk=1) self.assertEquals(book.get_absolute_url(), '/books/book-one/') But when I run the test, it fails with django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']. Why is slug empty? Why is the save method not called? What am I missing? -
GridView with actions column in django
I need to display list of books title and authors in a table with actions column in a django project. Would you suggest some packages for this purpose? Thank you. -
JQuery date django.core.exceptions.ValidationError: must be YYYY-MM-DD
I'm trying to create an edit jQuery ajax call. The code are the following: function editUser(id) { if (id) { tr_id = $("#element-" + id); data_pagamento_saldo = $(tr_id).find(".elementDatapagamentosaldo").text().replace(/\./g, "/"); $('#form-data_pagamento_saldo').val(data_pagamento_saldo); } } $("form#updateUser").submit(function() { var data_pagamento_saldoInput = $('input[name="formDatapagamentosaldo"]').val(); if (data_pagamento_saldoInput) { $.ajax({ url: '{% url "crud_ajax_update" %}', data: {'data_pagamento_saldo': data_pagamento_saldoInput, }, But django give me the following error: django.core.exceptions.ValidationError: ["The value '31/05/2020' hhas an invalid date format. It must be in YYYY-MM-DD format] How could I overcome the problem? For more information this is my html template: <td class="elementDatapagamentosaldo userData" name="data_pagamento_saldo">{{element.data_pagamento_saldo|date:"d.m.Y"}}</td> ... <label for="data_pagamento_saldo">Data pagamento saldo</label> <input class="form-control" id="form-data_pagamento_saldo" type="text" name="formDatapagamentosaldo" /> and this my models: class Materiale(models.Model): data_pagamento_saldo=models.DateField('Data pagamento Saldo', default="GG/MM/YYYY") -
Django nested transactions and exceptions
For simplicity I have a nested atomic transaction in my code, basically if adding people to the movie fails (see first for loop) I'd like to display an exception specifically saying that this action failed and also roll back movie.save(), same for studios (see second for loop). But for some reason when either one fails movie.save() doesn't roll back, I get a movie saved in my database without any people or studios attached to it. people = ['Mark', 'John', 'Mark'] studios = ['Universal Studios', 'Longcross Studios'] try: with transaction.atomic(): movie = Movie(title=title, description=summary, pub_date=pub_date) movie.save() # iterate through people list, get the pk from database and add it to the movie try: with transaction.atomic(): for p in people: person = Person.objects.get(name=p) movie.people.add(person) except Person.DoesNotExist: self.stdout.write(self.style.ERROR('One or more performers from %s does not ' 'exist in database, please add them and ' 'rerun the command.' % str(people))) continue # iterate through studio list, get the pk from database and add it to the movie try: with transaction.atomic(): for s in studios: studio = Studio.objects.get(name=s) scene.studios.add(studio) except Studio.DoesNotExist: self.stdout.write(self.style.ERROR('One or more studios from %s does not ' 'exist in database, please add them and ' 'rerun the command.' % str(studios))) continue scene.save() … -
Django to heroku migrate broken
Trying to migrate my django app (sqlite) to a postgres heroku app. After i commit, I try to migrate on heroku but it gives me this error: Applying store.0002_auto_20200523_1502...Traceback (most recent call last): .... ValueError: Related model 'users.Profile' cannot be resolved It seems an old migration that used a model that no longer exists is breaking the app on heroku. Any ideas? -
How to get server permission config to default without deleting anything?
I messed up my ubuntu server by going into the base directory and then I ran this command :( "chmod -R g+w *" which I didn't even knew what it meant so my server just logged out itself and then I tried to login again but got a connection refused error,so i launched my server console and I tried using sudo but got an error like this sudo: error in /etc/sudo.conf, line 0 while loading plugin 'sudoers_policy' sudo: /usr/lib/sudo/sudoers.so must only be writable by owner sudo: fatal error, unable to load plugins All because of that previous devil commandI just ran so I put my server into rescue mode and tried to fix it by using this $ mount -o remount,rw / $ chmod 644 /usr/lib/sudo/sudoers.so But it didn't work out,my question to you is how can I reset my permissions settings for my server like going back in time and getting this back to the point of working,I don'T have any backup? how can I get my server to default without deleting my configuration and other files or packages that I had installed! -
Change empty list returned by values_list to None without QS evaluation, Django orm
I have a question about query optimization. I the serializer specified bellow, in to_representation method I add extra data to representation. In this string: data['slave_accounts_ids'] = instance.slaves.all().values_list('pk', flat=True) or None I add secondary model instances pks in form of list, but it might be no any secondary model instances attached to the primary model(User model), so that I get empty list []. Thing is that in this case I need to return to FE None instead of [] and becouse of that I filter [] by condition expression : instance.slaves.all().values_list('pk', flat=True) or None which seems to evaluate queryset to find out whether or not first value is empty or not, at least if compare instance.slaves.all().values_list('pk', flat=True) and instance.slaves.all().values_list('pk', flat=True) or None, later makes +1 number of queries in DB. Question is - is it possible somehow change emty list returned by values_list to None without evaluating queryset and making extra query to DB? Or provide some default maybe... Thank you class CustomUserSerializer( serializer_mixins.ReadOnlyRaisesException, djoser_serializers.UserSerializer ): class Meta(djoser_serializers.UserSerializer.Meta): fields = djoser_serializers.UserSerializer.Meta.fields + ('user_country', 'master', ) read_only_fields = djoser_serializers.UserSerializer.Meta.read_only_fields + ('master', ) def to_representation(self, instance): data = super().to_representation(instance) if self.context['view'].action != 'list': data['slave_accounts_ids'] = instance.slaves.all().values_list('pk', flat=True) or None return data -
How to maintain django session after update user email?
I have the. django server with graphql and postgress. I have a problem that whenever I update user email the django session updated and due to this I lost the session on the frontend. So how can I maintain the session for that user after update an email? -
How can I get the console output in Angular webpage?
I have a Django project which is using Angular as frontend. I have a button which on clicking is scanning the tables in the database. I have some print statements views.py file which is printing the scanned results constantly in the IDE console. I want that output in the webpage. I want that live printing of the console output in the frontend. Can any one know how i can achieve this? -
Why am i getting "detail": "Not found." in http patch?
I am trying to patch the existing article but i get "detail": "Not found." error. Here are my codes: Views.py class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def patch(self, request, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs.get('id')) serializer = ArticleCreateSerializer(data=request.data, partial=True) if serializer.is_valid(): article = serializer.save() return Response(ArticleCreateSerializer(article).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs.get('id')) article.delete() return Response("Article deleted", status=status.HTTP_204_NO_CONTENT) I am getting this error both in patch and delete functions.Anybody has an idea why it happens? -
Creating model instances while creating a another instance in Django
I'm trying to do a Recipe app in Django. My main goal is allow to add multiple ingredients to a Recipe while I create it. So I have Basic Recipe model class Ingredient(models.Model): name = models.CharField(max_length=64, unique=True) def __str__(self): return self.name and also IngredientDetail model for Recipe model class IngredientDetail(models.Model): UNITS = ( ('G', 'gram'), ('L', 'liter'), ('KG', 'kilogram'), ('DG', 'ounce'), ('TPS', 'teaspoon'), ('TBS', 'tablespoon'), ('GL', 'glass'), ('PCS', 'pieces') ) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) amount = models.DecimalField( blank=True, null=True, max_digits=5, decimal_places=2 ) unit = models.CharField( max_length=3, blank=True, null=True, choices=UNITS, default=UNITS[0][0] ) and my Recipe Model class Recipe(models.Model): title = models.CharField(max_length=64) image = models.ImageField(blank=True) prep_time = models.IntegerField() description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ingredients = models.ForeignKey(IngredientDetail, on_delete=models.CASCADE) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.title} - by {self.author}' So I'm not sure if my relationships between models are good, and how would the view look like. I'm using Django Rest Framework -
Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
My url.py from django.contrib import admin from django.urls import path,include from .views import * app_name="posts" urlpatterns= [ path('',IndexView.as_view(),name="index"), path('detail/<int:pk>',PostDetail.as_view(),name="detail"), ] views.py from django.shortcuts import render from django.views.generic import ListView,TemplateView,DetailView # Create your views here. from .models import Post class IndexView(ListView): template_name="posts/index.html" model=Post context_object_name="posts" def get_context_data(self,*,object_list=None ,**kwargs): context=super(IndexView,self).get_context_data(**kwargs) return context class PostDetail(DetailView): template_name='posts/detail.html' model=Post context_object_name='single' def get_context_data(self,**kwargs): context=super(PostDetail,self).get_context_data(**kwargs) return context index.html {% for post in posts %} <article class="blog_style1"> <div class="blog_img"> <img class="img-fluid" src="{{post.image.url}}" alt=""> </div> <div class="blog_text"> <div class="blog_text_inner"> <a class="cat" href="#">Gadgets</a> <a href="{% url 'detail' pk=post.id %}"><h4>{{post.title}}</h4></a> <p>{{post.content | truncatechars:175}}</p> <div class="date"> <a href=""><i class="fa fa-calendar" aria-hidden="true"></i> {{post.publishing_date}}</a> <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a> </div> </div> </div> </article> {% endfor %} i got this error WHY ?????????? NoReverseMatch at / Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Exception Location: C:\Users\TAHA\Anaconda3\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 660 Python Executable: C:\Users\TAHA\Anaconda3\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\TAHA\Desktop\Blog-Site\Fantom', 'C:\Users\TAHA\Anaconda3\python37.zip', 'C:\Users\TAHA\Anaconda3\DLLs', 'C:\Users\TAHA\Anaconda3\lib', 'C:\Users\TAHA\Anaconda3', 'C:\Users\TAHA\Anaconda3\lib\site-packages', 'C:\Users\TAHA\Anaconda3\lib\site-packages\win32', 'C:\Users\TAHA\Anaconda3\lib\site-packages\win32\lib', 'C:\Users\TAHA\Anaconda3\lib\site-packages\Pythonwin'] Server time: Sun, 31 May 2020 12:20:08 +0000 -
Django/PostgreSQL: How to get PostgreSQL hint using django.db.connections and the cursor() function
I am using Django for my app backend. Due to a legacy database, I had to write custom helper functions that execute raw SQL queries. I have this particular rollback function that I wrote and I want to be able to get the RAISE EXCEPTION USING HINT that was generated by the supplied query. When the RAISE clause in the query is encountered, the HttpResponse throws error 400 which is what I wanted. I get the HINT via the console when I print out the connection cursor. What I want now is to be able to get and store that to a variable or pass it to the HttpResponse so I can prompt it in the frontend. DRF API FUNCTION def post(self, request): try: text = request.data.get("text") query = (""" START TRANSACTION; DO $$ DECLARE psid INT4; BEGIN SELECT personid INTO psid FROM profile.systemid WHERE id=%s; IF psid IS NOT NULL THEN INSERT INTO test (text) VALUES (%s) ELSE RAISE EXCEPTION USING HINT = 'Please check that you have filled your PDS Basic Personal info first'; END IF; END; $$; """) unformatted_query_result = raw_sql_insert(query, "default", ( text )) if unformatted_query_result: res = raw_sql_commit_with_notices("default") print(res) return Response({ "success": True, "message": "A … -
Cannot assign "<QuerySet [<Child: Name>]>": "Mark.MarkOwner" must be a "Child" instance
this is my another dumb question. Im really new at django and I dont know what I need to do. Can someone pls help me? Or send some pages in documantation? The goal is to make mark selector assigned to child that it displays for. There is some of my code. My HTML {% if child %} {% for c in child %} <tr> <th> {{c.ChildName}}<br> </th> <th> <form action="{% url 'marks:addmark' class.id sc.id %}" method="POST"> {% csrf_token %} <select required name="sub"> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> <option value=11>11</option> <option value=12>12</option> </select> <button type="submit">готово</button> </form> </th> </tr> {% endfor %} {% endif %} views.py def mlat(request, classid, subjectid): a = Class.objects.get( id = classid ) b = SubjectClas.objects.get( id = subjectid ) d = Child.objects.filter(ChildClass = a) c = Mark.objects.filter(MarkSubjet = b) return render(request, 'marks/mlat.html', {'class':a, 'sc':b, 'subjectsyes':c, 'child':d}) def addmark(request, classid, subjectid): a = Class.objects.get( id = classid ) b = SubjectClas.objects.get( id = subjectid ) d = Child.objects.filter(ChildClass = a) c = Mark.objects.filter(MarkSubjet = b) Mark.objects.create(Markd = request.POST['sub'], MarkSubjet = a, MarkOwner = d) return HttpResponseRedirect(reverse('marks:mlat', args=[b.id, a.id,])) models.py class SubjectClas(models.Model): subject = … -
Getting an value error from extended user model
I am trying to create a form that allows me to update an extended user model, see my views below def employee(request, pk): employee= Employee.objects.get(id=pk) user = User.objects.get(id=pk) user_form = UserForm(instance=user) Employee = EmployeeProfileForm(instance=employee) if 'edit_employee' in request.POST: if request.method == 'POST': user_form = UserForm(request.POST,instance=user) employee_form = EmployeeProfileForm(request.POST,instance=user.employee) if user_form.is_valid() and employee_form.is_valid(): user = user_form.save() employee = employee_form.save(commit=False) employee.user = user employee.save() return redirect('/') return render(request, 'accounts/new_employee_profile.html', {'user_form': user_form,'employee_form':employee_form}) models.py class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def … -
Django ListView click event
Good day guys, I create already a ListView, I just want that if that record is click or select it will display its data. for example i click the < td > 1, all record in < td > 1 will display at the top of the table, what should i use? jquery? or django? this is my views.py class ArticleListView(ListView): model = StudentsEnrollmentRecord paginate_by = 100 # if pagination is desired searchable_fields = ["Student_Users", "id", "Section"] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context my html <table> <tr> <td>Control #</td> <td><input type="text" ></td> </tr> <tr> <td>Name: </td> <td><input type="text" ></td> <td>Course/Track</td> <td><input type="text" ></td> </tr> <tr> <td>Education Level: </td> <td><input type="text" ></td> <td>Strand: </td> <td><input type="text" ></td> </tr> <tr> <td>Section: </td> <td><input type="text" ></td> <td>Payment Type: </td> <td><input type="text" ></td> </tr> </table> <h1>Student Enrollment</h1> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"> <table id="myTable"> <tr> <th>Control #</th> <th>Name</th> <th>Education Level</th> <th>Section</th> <th>Course/Track</th> <th>Strand</th> <th>Payment Type</th> <th>Date</th> </tr> {% for article in object_list %} <tr> <td>{{ article.id }}</td> <td>{{ article.Student_Users }}</td> <td>{{article.Education_Levels}}</td> <td>{{article.Section}}</td> <td>{{article.Courses}}</td> <td>{{article.strands}}</td> <td>{{article.Payment_Type}}</td> <td>{{article.Date_Time}}</td> </tr> {% empty %} <tr> <td>No articles yet.</td> </tr> {% endfor %} </table> -
Unable to send a message as the user who logged in through sign in with slack integrated in my django project?
I am trying to integrate slack messaging in django project so for that I had integrated sign in with slack option in my project and created a new slack app and I had added chat:write and users:read scopes to my User Token Scopes of my slack app and in my django views.py I wrote and api call for posting a message views.py: def index2(request): url = 'https://slack.com/api/users.list' headers = {'Authorization' : 'Bearer {}'.format(SECRET)} r = requests.get(url, headers=headers) response = json.loads(r.text) print(response) all_ids = [member['id'] for member in response['members'] if not member['deleted']] all_names = [member['name'] for member in response['members'] if not member['deleted']] my_list=zip(all_ids,all_names) value1 = request.GET.get('id') value2 = request.GET.get('msg') print(value1,value2) client = WebClient(token=SECRET) try: response = client.chat_postMessage( channel=value1,text=value2) assert response["message"]["text"] == value2 except SlackApiError as e: assert e.response["ok"] is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}") Here the problem the user who logged in with signinslack is not able to message to his desired slack users every time whoever logs in it is posting messages to desired ones as me who is the creator of the slack app in api.slack.com Can anyone help me I am totally confused what is happening Thanks in advance! for example … -
How to override Django Admin Panel authentication with Google SSO?
What I want is to create some users in the standard Users table and add a Sign in with Google button on the Django Admin Panel login screen. When the user completes the sign-in process, then I should receive its details (e.g. email address) which then I will verify from the database, e.g. if a Users record with given email address exists. If yes, then I will sign-in the user on the Django Admin Panel. Is there a way to do this? -
How can I make connection between python database to hiedsql data tables
I want to create students table in python programming language along with hiedsql -
REACTJS - Websocket - Conection error: KeyError: 'method' -
I am completely blocked, I have followed the documentation and everything works with the browser pointing to the endpoint. I can send a msg to the consumer. But when I do it from ReactJS I have this problem: (venv) developer@W10_Vbx_Everest_D1:~/Kentron$ daphne -b 0.0.0.0 -p 8001 Kentron.asgi:application 2020-05-31 10:48:57,012 INFO Starting server at tcp:port=8001:interface=0.0.0.0 2020-05-31 10:48:57,013 INFO HTTP/2 support enabled 2020-05-31 10:48:57,015 INFO Configuring endpoint tcp:port=8001:interface=0.0.0.0 2020-05-31 10:48:57,021 INFO Listening on TCP address 0.0.0.0:8001 192.168.196.64:62372 - - [31/May/2020:10:39:12] "WSDISCONNECT /events/" - - 192.168.196.64:62374 - - [31/May/2020:10:39:12] "WSCONNECTING /events/" - - 192.168.196.64:62374 - - [31/May/2020:10:39:13] "WSDISCONNECT /events/" - - 2020-05-31 10:39:13,133 ERROR Exception inside application: 'method' Traceback (most recent call last): File "/home/developer/venv/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/developer/venv/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/home/developer/venv/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/developer/venv/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/home/developer/venv/lib/python3.6/site-packages/django_eventstream/consumers.py", line 108, in __call__ await self.handle(b"".join(body)) File "/home/developer/venv/lib/python3.6/site-packages/django_eventstream/consumers.py", line 134, in handle request = AsgiRequest(self.scope, body) File "/home/developer/venv/lib/python3.6/site-packages/channels/http.py", line 56, in __init__ self.method = self.scope["method"].upper()`enter code here` KeyError: 'method' I am using in DEBUG MODE with my django con the backend. This is my setup: Frontend: REACTJS Backend: Django==2.2.9 django-eventstream==3.1.0 daphne==2.5.0 … -
Django get URL from address bar
I am a begginer with django and I am stuck in getting this to work, practically what I want is that the user types in the address bar http://website.com/example and then in Django i want to make a dynamic view where it checks the address and then redirects user to the correct page otherwise gives an error. this is what I was trying but it might not be working.. urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.example, name="example") ] and then in the views.py i want the following: def example(request, name): return render(request, "website/<name> here i want for it to insert what the user typed in the address bar", { "name": util.get_entry(name) <-- this is a function which checks if there is that name in the database otherwise will return an error. }) Hope I was clear with the question and thank you for the help :) -
Django reset password doesn't load correct templates
i have 4 custom templates but two of them are loading the default templates and i don't know why. This is my url paths: #works fine path('reset_password/', auth_views.PasswordResetView.as_view(template_name="myapp/password_reset.html"), name="reset_password"), #doesn't work path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="myapp/password_reset_sent.html"), name="password_reset_done"), #works fine path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="myapp/password_reset_form.html"), name="password_reset_confirm"), #doesn't work path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="myapp/password_reset_done.html"), name="password_reset_complete"), However if i write the url directly in the browser they load correctly. Any ideas? Thanks!