Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Can't add project to scrapyd
The problem I had is I can't upload my .egg file to scrapyd using curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 egg=@scraper_app-0.0.1-py3.8.egg its returning an error message like this {"node_name": "Workspace", "status": "error", "message": "b'egg'"} So I'm using Django and Scrapy in the same project, and I had this folder structure my_app/ -- apps/ # django apps folder -- crawler/ -- __init__.py -- admin.py -- apps.py -- etc.. -- pages/ -- __init__.py -- admin.py -- apps.py -- etc.. -- my_app/ # django project folder -- __init__.py -- asgi.py -- settings.py -- etc.. -- scraper_app/ # scrapy dir -- scraper_app/ # scrapy project folder -- spiders/ -- abc_spider.py -- __init__.py -- middlewares.py -- pipelines.py -- settings.py -- etc.. -- scrapy.cfg -- manage.py -- scrapyd.conf -- setup.py # setuptools for creating the egg file -- etc.. and here is what my setup.py looks like from setuptools import setup, find_packages setup( name="scraper_app", version="1.0.0", author="Khrisna Gunanasurya", author_email="contact@khrisnagunanasurya.com", description="Create egg file from 'scraper_app'", packages=find_packages(where=['scraper_app']) ) my scrapyd.conf file [scrapyd] eggs_dir = eggs logs_dir = logs logs_to_keep = 5 dbs_dir = dbs max_proc = 0 max_proc_per_cpu = 4 http_port = 6800 debug = off runner = scrapyd.runner application = scrapyd.app.application and my scrapy.cfg content [settings] default = … -
iterating over dynamic content with jquery
var deneme = document.getElementsByClassName("content-holder"); var uzat = document.getElementsByClassName("uzat"); for (var i = 0; i < deneme.length; i++) { var yuksek = deneme[i].offsetHeight; if (yuksek > 250) { deneme[i].style.height = "97px"; uzat[i].style.display = "block" } }; This function finds entries in a page which are longer than 250 px and shrinks them to 97 px, also adds a button "uzat" and when this button is clicked entry gets back to the original size. Now I'm using infinite scroll to load new entries and this function doesn't work on newly loaded entries. I tryed to trigger the function everytime new content is added but it also effected the old entries. Is there anyway to change only the new entries without effecting the old ones? -
how to get value from radio button from html template
i want to access value from radio button without django from only from a html from <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="1" type="radio" checked> <label class="form-check-label" for="option1"> {{i.option1}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="2" type="radio" checked> <label class="form-check-label" for="option2"> {{i.option2}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="3" type="radio" checked> <label class="form-check-label" for="option3"> {{i.option3}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="4" type="radio" checked> <label class="form-check-label" for="option4"> {{i.option4}} </label> </div> this is views.py def answer_check(request): if request.method=="POST": print(request.POST['1']) return render(request,"index.html") return render(request,"index.html") -
Trying to load certain form if user is authenticated and preload all the information in the database with the user credentials
Trying to load certain form if a user is authenticated and preload all the information in the database but I get this error, most probably something is wrong in forms.py but the idea is that if the user is authenticated they should not go through the process of entering their name and email, they would just have to send the message. It currently works like a charm for non registered users but I never did something like this before for the registered users so I am stuck. forms.py from django import forms from django.forms import ModelForm from .models import Message class NonAuthMessage(forms.ModelForm): class Meta: model = Message fields = "__all__" class AuthMessage(forms.ModelForm): def __init__(self): self.name = user.request.username self.email = user.request.email class Meta: model = Message fields = ["message"] models.py from django.db import models from django.utils import timezone class Message(models.Model): name = models.CharField(max_length=50) email = models.EmailField() message = models.TextField(max_length=3000) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ['-date_posted',] views.py from django.shortcuts import render, redirect from .models import Message from .forms import NonAuthMessage, AuthMessage def contact(request): formAuth = AuthMessage() formNonAuth = NonAuthMessage() mess = Message.objects.all() if request.user.is_authenticated: if request.method == "POST": form = AuthMessage(request.POST) if form.is_valid(): form.save() return redirect('contact') … -
"Token contained no recognizable user identification" while creating custom django jwt token
I have created my login view which on successful login returns access token and refresh token..Then on accessing any view the user have to attach this access token as bearer token in every url.. I have manually created my access token and refresh token . But i have inherited restframework_simplejwt.views.TokenRefreshView which will return an access token for each refresh token.. All this is working fine... Now i have used permission_classes((IsAuthenticated)) above my home_api_view and when i paste the access token over the homepage url it says "Token contained no recognizable user identification" my views.py @api_view(['POST','GET',]) @permission_classes([]) def login_view(request): username = request.data.get("username") password = request.data.get("password") response = Response() user = authenticate(request,username=username,password=password) if user is not None: login(request,user) user = User.objects.filter(username=username).first() #This will return directly the username . If you dont use .first() it will return a dictionary access_token = Generate_Access_Token(user) refresh_token = Generate_Refresh_Token(user) response.data={'refresh_token':refresh_token,'access_token':access_token} return response else: return HttpResponse("USERNAME or PASSWORD ERROR!!!") utils.py` def Generate_Access_Token(user): access_token_payload = { 'token_type':'access', 'exp':datetime.datetime.utcnow()+datetime.timedelta(days=0,minutes=5), 'jti': uuid4().hex, 'user':user.username, 'id':user.id, 'iat':datetime.datetime.utcnow(), } access_token = jwt.encode(access_token_payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') return access_token def Generate_Refresh_Token(user): refresh_token_payload = { 'token_type':'refresh', 'id': user.id, 'exp' :datetime.datetime.utcnow()+datetime.timedelta(days=7), 'iat':datetime.datetime.utcnow(), 'jti': uuid4().hex } refresh_token = jwt.encode(refresh_token_payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') return refresh_token