Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when deleting a post with file stored on AWS S3 - NotImplementedError: This backend doesn't support absolute paths
I've deployed a small application to Heroku with AWS S3 configured to store post images. I've added two functions to delete image files whenever a post object is deleted. The functions work fine in a local dev environment. the images files get deleted if I delete a post from the admin screen. But after deployment, when I go to delete a post from admin, I get this error message in the logs: NotImplementedError: This backend doesn't support absolute paths After I search SO, I think this issue is caused by the last two lines in this function but not sure why. when I remove .path the function doesn't work in local development @receiver(models.signals.post_delete, sender=Post) def delete_image(sender, instance, **kwargs): """ Deletes image on post_delete. """ if instance.image: if os.path.isfile(instance.image.path): os.remove(instance.image.path) Here is the other function to delete image file if the post is updated: @receiver(models.signals.pre_save, sender=Post) def delete_image_on_change(sender, instance, **kwargs): """ Deletes old image file when Image object is updated with new file. """ if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).image except sender.DoesNotExist: return False new_file = instance.image if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) This is the model: class Post(TimeStampedUUIDModel): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") title = … -
More elegant way to replace all field equal to Null by the default value in django model objects
I'am looking on a more elegant way to replace all field of my model objects which are equals to Null by the default value defined in the model. Here is my current code : for buy in Buy.objects.all(): for f in Buy._meta.get_fields(): field = eval("buy." + f.name) if field is None: field = Buy._meta.get_field(f.name).get_default() buy.save() But i find the use of eval not elegant. If anyone have better way to do that Regards -
Django edit profile not saving
I have pre-filled forms for my user (the django user + my profile one with more informations) that just doesn't want to be saved. No error message, no redirection, I press the button "edit", and then... same page, with the modifications already written. But the database isn't changed. So, here is the code : forms.py : class UpdateUser(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('email', 'username') def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('Cette adresse email est déjà utilisée, veuillez en indiquer une autre') return email class UpdateProfil(forms.ModelForm): class Meta: model = Profil fields = ("society", "thingA", "thingB", "thingC", "thingD", "thingE") views.py : @login_required def edit_profile(request): user = User.objects.get(username = request.user) profile = Profil.objects.get(user = user) if request.method == 'POST': form1 = UpdateUser(request.POST, instance=user) form2 = UpdateProfil(request.POST, instance=profile) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return HttpResponseRedirect('Register/view_profile.html') else: form1 = UpdateUser(initial={"email": user.email, "username": user.username}) form2 = UpdateProfil(initial={"society": profile.society, "thingA": profile.thingA, "thingB": profile.thingB, "thingC": profile.thingC, "thingD": profile.thingD, "thingE": profile.thingE}) return render(request, 'Register/edit_profile.html', locals()) and the template: <form action="" method="post"> {% csrf_token %} <p>Email : </p>{{ form1.email }} <p>Nom d'utilisateur : </p>{{ form1.username }} <p>Société (entreprise, association, établissement...") :</p> {{ form2.society }} <p>Si … -
Is it possible to add a Button to a Wagtail Settings page?
I am trying to customize a settings page so it has a button that I will assign to a certain action. (Let's assume for now I just want to log something into the console). Ideally it would be of something like this: @register_setting class ActionTriggeringSetting(BaseSetting): button = models.ButtonField( action=myLoggingFunc, help_text='Click here to log "Hello World" to the console' ) I tried looking into the site settings but found nothing really helpful there. Does anybody know if something of the sort exists? Thank you -
search form always called
There is an error in def search : The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. Only when I call a create new Page. I don't understand why? My layout template with search bar: <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'new' %}">Create New Page</a> </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> My new template: {% extends "encyclopedia/layout.html" %} {% block title %} New Entry {% endblock %} {% block body %} <h1>New entry</h1> <form action="{% url 'new' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit"> </form> {% endblock %} views.py: def search(request): if request.method == "POST": title = request.POST['q'] if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) if util.get_partial_entry(title): return render(request, "encyclopedia/search.html", { "entries": util.get_partial_entry(title) }) return render(request, "encyclopedia/404.html", { "entry": title}) def new(request, method="GET"): return render(request, "encyclopedia/new.html", { "form": NewForm() }) I don t understand why I have only the error on new page … -
Django JsonResponse converts numbers to string
I'm using JsonResponse(status=200, data=<python_dict_with_data>) to return from my Django backend API. However, upon inspecting the result of this, all numbers get converted to strings. This creates a problem in the frontend receiving this response because now I have to parse them as integers to do formatting and lightweight calculations. Is there a way to prevent this conversion when returned from Django? Or is there a way the response is parsed correctly in the frontend? I'm using Axios library in React in the frontend. -
Im getting a 'NoReverseMatch' error during template rendering
Currently reading the Python Crash Course by Eric Matthes and im trying to code a simple learning lo using python and django , but i keep getting an error when i try to enter the topics url . The error seems to come from the base.html(the template) , it says that learning_logs is not a registered namespace , even tho i have written it as a variable named app_name and have included it in the urls. Heres the code: main urls.py: from django.contrib import admin from django.urls import path , include , re_path app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('' , include(("learning_logs.urls", app_name ) )) ] urls.py: from django.urls import path , re_path from . import views app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic'), re_path(r'^new_entry/(?P<topic_id>\d+)/$' , views.new_entry , name = 'new_entry'), ] base.html: <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %} {% endblock content %} Error: Pic -
Django Taggit "Similar Objects" additional filter
My website is going to have data that has expiration date in the model field, my view will only show the active one by using filter list = Model.objects.filter(deadline__gte =timezone.now()) in the detail views of the model, i'm going to show the related post using django taggit with taggable manager for the models field and 'similar_objects' from the API detail = Model.objects.get(slug=slug, pk=pk) related = detail.tags.similar_objects()[:5] the only problem is that the 'related' will return a list instead of queryset (i can't filter it using django) and it's going to show the expired post too. My question is if there is a way i can show my related post and filter it so that it only shows the one that aren't expired -
What role does Redis serve in Django Channels
Recently I've been using django channels makes its support websocket protocol, I use a microservice way, other components through connection django channels, but I have to write a Consumer class for each connection for receiving and handling, for example class Consumer(AsyncWebsocketConsumer):, which still use the redis, pointed out that this part is the official document as a channel layer storage, so it is as a message queue, the cache or other commonly used functions exist? I write to find out if there is a Consumer for each connection, and whether I can think of it as acting as a message queue. However, I have not found relevant materials to support my point of view. Could you please tell me whether my understanding is correct or not? I sincerely hope that you can provide relevant materials for reference whether it is correct or not. -
Anyone who knows Navbar&Bootstrap?
I have no idea with this problem.. Navbar's Dropdown doesn't work! with this message enter image description here this is my code <head> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{%url 'home'%}">Portfolio</a> <a class="dropdown-item" href="{%url 'signup'%}">회원가입</a> <a class="dropdown-item" href="{%url 'login'%}">로그인</a> <a class="dropdown-item" href="#">로그아웃</a> </div> </li> </ul> </div> </nav> {%block contents%} {%endblock%} -
How to change my models.TextField to models.JSONField?
I'm using django as my backend and it was working very fine, but after I tried to replaced text = models.TextField(blank=True, null=True) text = models.JSONField(blank=True, null=True) but I got the text field is shown as string with slashes \ "text": "{\"name\": [\"test\", \"test2\"]}", while styles field look as json "style": { "borderRadius": "5px", "backgroundColor": "orange" }, despite they both are jsonfield. models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) # it was # text = models.TextField(blank=True, null=True) # now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() also after a run python manage.py makemigrations then python manage.py migrate I got an error DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... the full error Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, myapp, sessions, sites Running migrations: Applying myapp.0006_auto_20200905_1410...Traceback (most recent call last): File "/Users/apple/Desktop/learning web stack from clonning notion.so/backend/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type json DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... The above exception … -
Django cache and page part that depends on login
Suppose I have some page at example.com/page If a user is not logged in, then I show Log in button. If the user is logged in, then I show menu. The problem is that it doesn't work with cache. If I render page and save it in cache, then it is always with login button. How to avoid this? -
Extending User model when users haven't created accounts yet
I am building a system for a startup where customers can book small home repair services with the service providers. Everything so far was done manually by a human, using a large spreadsheet that stores contact information of the service providers, like name, e-mail, location, phone, etc. As the customers reach the company's website asking for repairs, a person go though the spreadsheet, looking for a suitable service provider, contact the provider and checks availability and books a time/date that works for both provider and customer. The idea now is to automate this process, sending sms and whatsapp messages to both parties, instead of a person having to deal with this process, by using Trello. The startup owners want to avoid the trouble of having to ask for all service providers to create accounts for now, but I think it's a good idea to extend the Django's User model, as later on it would be easy to transition to a system where the providers has their own accounts with username and password, and easily connect with all the services that have been done. But right now I can't use the User model, as I don't have any accounts yet. Should … -
django ajax post without csrftoken in post ajax
html {% load static %} <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" multiple> <input type = "button"id = "btn_upload"value = "submit"></input>```` javascript $(document).ready(function(){ $('#btn_upload').click(function(){ console.log("is it working?"); const formdata = new FormData(); const inputfile = $('input[name="avatar"]'); const files = inputfile[0].files.val(); for(let i = 0; i<files.length; i++){ formdata.append('images',files[i]); } formdata.append('CSRFToken',csrf); $.ajax({ contentType : false, processData : false, data : formdata, url : '', type : 'POST', success : function(result){ console.log("succeed") } }); }); }); I want to give over the data by POST method without using form But in django setting {% csrf_token %} is needed when using POST method How can I give data without using form and {% csrf_token %}? -
Why is wrong url being returned after image is uploaded
I uploaded image and it gets save in correct location and url uploaded to db. But response is wrong. "http://127.0.0.1:8000/media/media/img.jpg" is being returned instead of "http://127.0.0.1:8000/media/img.jpg" where its being saved. Why is extra media/ being added? api.js def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() if request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) profile = UserDetail() profile.user = user profile.profile_pic = uploaded_file_url profile.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) url.js urlpatterns = [ path('api/auth', include('knox.urls')), path('api/auth/register', RegisterAPI.as_view()), path('api/auth/login', LoginAPI.as_view()), path('api/auth/user', UserAPI.as_view()), path('api/auth/logout', knox_views.LogoutView.as_view(),name='knox-logout'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.js STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images') serializer class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = UserDetail fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile_pic = ProfilePicSerializer(source='user_detail', read_only=True) class Meta: model = User fields = ('id', 'username', 'email','profile_pic') -
Raspberry Pi camera stream to django website
I have been experementing in python django, and got the idea to make my raspberry pi camera stream to the website. The only tutorials I could find were about showing youtube videos on the website. Is there any way to do it from the raspberry pi camera? -
Djnago causing errors with StreamingHttp Response
I created a django app to stream coordinates of ISS on a map, here is the view which generates the streaming http response def IssnowCoordinatesStream(request): def IssDataStream(sleep_time = 1): while True: streamData = GenerateIssData() yield 'data:{0}\n'.format(streamData.decode()) time.sleep(sleep_time) response = StreamingHttpResponse( IssDataStream(), status = 200, content_type = "text/event-stream" ) response['Cache-Control'] = 'no-cache' return response This is the output from the view at [localhost/stream] data:{"issnow_satid": 2447, "key": "e622c32c-b949-4abe-b3d8-ca75dbd8039e", "timestamp": "2020-09-05 13:23:36.018709", "message": "Success", "longitude": -29.8005, "latitude": -28.4975, "speed": 27554, "altitude": 428} And from my index view i am trying to access the stream using javascript var source = new EventSource('/stream') source.addEventListener('message', (e) => { obj = JSON.parse(e.data) console.log(obj); }, false); But it's not able to parse the data and the following error comes up on the terminal Traceback (most recent call last): File "C:\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python37\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python37\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\Python37\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Python37\lib\socketserver.py", line 799, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [05/Sep/2020 18:45:52] "GET /streams/issnow HTTP/1.1" 500 59 Can anyone help in solving this error. Note I browsed the … -
Django ajax: show comment's replies div
i have a comment section with replies in my app and I would like to show and hide replies by clicking on button. This is what I done: ajax $(document).ready(function () { $("#showReplies").click(function () { $.ajax({ type: 'get', success: function (data) { console.log(data.comment); $('.replies').load("http://127.0.0.1:8000/comment_replies/" + data.comment.id); } }) }); }); post_comments.html <h3>Comments:</h3> {% for comment in post.comment_set.all %} <p>{{ comment.content }}</p> <small>{{ comment.author }} / {{ comment.date_of_create|date:"d E Y" }}</small> <button type="button" id="showReplies">Show replies</button> {% endfor %} comment_replies.html {% for reply in replies %} <p>{{ reply.content }}</p> <small>{{ reply.author }} / {{ reply.date_of_create|date:"d E Y" }}</small> {% endfor %} urls.py path('comment_replies/<int:comment_id>/', comment_replies, name='comment_replies'), views.py def comment_replies(request, comment_id): comment = Comment.objects.get(id=comment_id) #replies = Reply.objects.filter(comment=comment) # context = {'replies': replies} # return render(request, 'blog/comment_replies.html', context) return JsonResponse({'comment': model_to_dict(comment)}, status=200) How can I get appropriate url in ajax? Data logs whole template in console after clicking button instead of comment object. When I go to url http://127.0.0.1:8000/comment_replies/4/ I get {"comment": {"id": 4, "author": 1, "content": "test", "date_of_create": "2020-09-05T09:56:05.218Z", "post": 9, "topic": null}} Data.comment gives undefined. -
Django Like Syste --> RedirectView not redirecting to post
I ran into a problem while trying to figure out how to implement a liking system for my Django blog. I have a post Detail View and a PostRedirectView. I want the redirect view to get the absolute URL for the Post I look at and toggle a like/unlike as my liking system is a ManyToManyField linked in my models.py for the post. Here is the related code: views.py class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments_connected = Comment.objects.filter(post_connected=self.get_object()).order_by('-date_posted') data['comments'] = comments_connected data['form'] = NewCommentForm(instance=self.request.user) return data def post(self, request, *args, **kwargs): new_comment = Comment(content=request.POST.get('content'), author=self.request.user, post_connected=self.get_object()) new_comment.save() return self.get(self, request, *args, **kwargs) class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=self.kwargs.get('id')) return obj.get_absolute_url() urls.py path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/like', PostLikeRedirect.as_view(), name='post-like'), models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_who_authored") like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users_who_liked") def __str__(self): return f'{self.author} posts: {self.content[:8]}' @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() def __str__(self): return f'{self.author} posted' The error I get is 404 page not found when I go to post/id(e.g. 2)/like and the error message No Post matches the given query. I know what the error means I just … -
The code of an HTML dropdown button seems fine, but it doesn't work [closed]
I am following a book to learn Django. One of the dropdown buttons is not working, the code is the same as the one provided by the book. I tried to find reason on my own, but it heavily involves bootstrap or something. Anyone can take a look at the snippet below. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> {% if user.is_authenticated %} <ul class="navbar-nav mr-auto"> <li class="nav-item"><a href="{% url 'article_new' %}">+ New</a></li> </ul> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-lg-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign up</a> </form> {% endif %} </div> </nav> -
hi I have django problem, Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
I want to see http://127.0.0.1:8000/bookmark/ page. But I go there, there is an error in website. error message is NoReverseMatch at /bookmark/ 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/bookmark/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.3 and my code is [base.html] <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}django web programming {% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- 하위 html 파일에서 이 부분에 style 태그를 추가할 가능성이 있으므로 block 태그를 기입. 블록태그이름은 extra-style로 지정함 변경가능 --> {% block extra-style %}{% endblock %} <style> .nav-link{ font-size: 18px; font-weight: 500; } </style> </head> <body style = "padding-top:90px;"> <!-- home.html (4) 참고 --> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top"> <span class="navbar-brand mx-5 mb-0 font-weight-bold font-italic"> Motdongsan</span> <!-- <a class="navbar-brand" href="#">Navbar</a> --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item mx-3 btn btn-light"> <a class="nav-link" href="{% url 'home'%}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item mx-3 btn btn-light"> <a class="nav-link" href="{% url 'bookmark:index'%}">Bookmark</a> </li> … -
How to change the redirect_uri in moziila_django_oidc?
I want to integrate Keycloak into a Django project and I am using mozilla_django_oidc to do so. The problem I have is that when I send a request to the authorization endpoint of keycloak the redirect_uri is being set as: redirect_uri=http%3A%2F%2Fdjango%3A8000%2Foidc%2Fcallback%2F, but instead of django there should be the IP of my application. I don't know why it uses django as the domain name. My configuration in the settings.py looks like this: OIDC_RP_CLIENT_ID = os.environ['OIDC_RP_CLIENT_ID'] OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/auth' OIDC_OP_TOKEN_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/token' OIDC_OP_USER_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/userinfo' OIDC_OP_JWKS_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/certs' LOGIN_REDIRECT_URL = 'http://172.20.159.83/test' LOGOUT_REDIRECT_URL = 'http://172.20.159.83/' And in the urls.py it is: path('oidc/', include('mozilla_django_oidc.urls')), The request to the authorization endpoint with all parameters: http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/auth?response_type=code&scope=openid+email&client_id=MyApplication&redirect_uri=http%3A%2F%2Fdjango%3A8000%2Foidc%2Fcallback%2F&state=3YxLAg8kX1bC1yTDMqKh8L05bIP5z9cB&nonce=jZ6KEZhk9tWOwdXRSqTUoF8lzg7aLU70 So, as the title says, how can I change the django part of the redirect uri to point to the IP of my application? How is this parameter being set? -
Django Rest Framework 'list' object has no attribute values
I have the code and error stacktrace below. I am trying to access localhost:8000/fundamentals/ but I get the error 'list' object has no attribute 'values' error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response web_1 | response = response.render() web_1 | File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render web_1 | self.content = self.rendered_content web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/response.py", line 70, in rendered_content web_1 | ret = renderer.render(self.data, accepted_media_type, context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 724, in render web_1 | context = self.get_context(data, accepted_media_type, renderer_context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 655, in get_context web_1 | raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form web_1 | data = serializer.data.copy() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 562, in data web_1 | ret = super().data web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 264, in data web_1 | self._data = self.get_initial() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 413, in <listcomp> web_1 | if not field.read_only web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | … -
Session key failed
i am creating todo app. After login when i add any task. It show error: failed 'SESSION_KEY'. When i debug the code it show SESSION_KEY. after removing the request.seesion from post method in TODOlist class it works. I don't know how to fix this issue. class Login(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: username = self.request.POST.get('username').strip() password = self.request.POST.get('password').strip() if username is None or password is None: return HttpResponse('Invalid User', 500) user = authenticate(request, username=username, password=password) if not user: return HttpResponse('User Doest exist', 500) else: login(request, user) if SESSION_KEY in request.session: return redirect('todolist') except Exception as e: return HttpResponse({'failed {}'.format(e, 200)}) class Todolist(TemplateView): template_name = 'todo_page.html' def get(self, request, *args, **kwargs): if SESSION_KEY in request.session: return render(request, self.template_name) def post(self, request): if SESSION_KEY in request.session: try: data = self.request.POST.get task_list = Task( user_id=request.session["SESSION_KEY"], task=data('task') ) task_list.save() return redirect('todolist') except Exception as e: return HttpResponse('failed {}'.format(e), 500) -
Django -- Forbidden (CSRF token missing or incorrect.): /vote/
I have a website with an AJAX upvote or downvote option on a post. The problem I am having is that the voting works on my Post detail page but not on my index page. I am getting the error Forbidden (CSRF token missing or incorrect.): /vote/ Both pages call the same view and URL pattern. index.html: {% for post in posts %} <span id="post_{{forloop.counter}}" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> {% endfor %} <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ {% for post in posts %} $('.vote_action').click(function(e) { var postid = document.getElementById('post_{{forloop.counter}}').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" %}', data: { postid: postid, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'postvote', button: button, }, success: function(json){ if (json.length < 1 || json == undefined) { //empty } document.getElementById("votes").innerHTML = json['result'] }, error: function(xhr, errmsg, err) {} }) }) {% endfor %} }) </script> post_detail.html: <span id="vote_id" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ $('.vote_action').click(function(e) { var postid = document.getElementById('vote_id').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" …