Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My user has permissions but does not have access to pages in django app
My user has for example the following permissions: add_client, view_client, delete_client, change_client of the Client model print(user.request.user_permissions.all()) gives <Permission: elec_meter | client | Can add client>, <Permission: elec_meter | client | Can customer change>... When I add the @permissions_required decorator as follows: @permission_required("client.add_client",login_url="/login") def add_client(request): ... @permission_required("client.view_client",login_url="/login") def view_client(request): ... The user cannot open the pages and is redirected to the login page (/login) How to solve this problem ? -
Got AttributeError when attempting to get a value for field `user_name` on serializer `UserRegistrationSerializer`
I'm trying to create a custom user model with user role but when registering users i keep getting the same error this is what i did MY USER MODEL class User(AbstractBaseUser, PermissionsMixin): class RoleType(models.TextChoices): SCHOOL = 'SCHOOL' PARENT = 'PARENT' role = models.CharField(max_length=50, choices=RoleType.choices, default=RoleType.SCHOOL) user_name = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'user_name' REQUIRED_FIELDS = ['email'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } THE PARENT MODEL class Parent(models.Model): # other fields related to student ... Parental_code = models.CharField(max_length=10, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user", null=True) THE SERIALIZER class UserRegistrationSerializer(serializers.ModelSerializer): RoleType = { 'SCHOOL': 'SCHOOL', 'PARENT' : 'PARENT' } role = serializers.ChoiceField( choices=RoleType, default=RoleType['PARENT']) class Meta: model = User fields = ['user_name', 'password', 'email', 'role'] extra_kwargs = { 'password': {'write_only': True}, 'email': {'required': True}, 'user_name': {'required': True} } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ParentSerializer(serializers.ModelSerializer): user = UserRegistrationSerializer(write_only=True) class Meta: model = Parent fields = ['Parental_code', 'user'] def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) user = Parent.objects.create(user=user, **validated_data) return user THE ERROR IM GETTING i tried cheking the spellings but … -
Best practice for intercepting error responses in Django and DRF
I have a Django app that uses the Django Rest Framework. Errors may occur on the Django side, like integrity errors in the database. The default error response will be something like: { "details": { "email": "user with this email already exists." } } Validation errors may also occur DRF side: { "detail": ... } As you can see, there is an inconsistency in the response message, as Django uses "details" and DRF uses "detail". However, I like neither format. I want to respond with a message in the following format: { "message": ... "code": ... } My question is: What is the best practice to handle both Django and DRF exceptions and respond with a custom response body? I have tried: custom exception handler in DRF, but this only handles DRF exceptions custom error messages when defining models email = models.EmailField(error_messages={"required": {"message": "", "code": 123}}) but Django can't handle a dictionary as a message Adding a DRF validator to my serializer: email = serializers.EmailField( validators=[ UniqueValidator( queryset=models.User.objects.all(), message={ "message": "a user with this email already exists", "code": status.EMAIL_EXISTS, }, ) ], ) but this does not override the response body, but instead it embeds the message as an error … -
Using Serializer waste of time while creating new record into database?
In my django Application i have a model and serializer for it as:- 1.) model:- class Requests(models.Model): a = models.AutoField(primary_key=True) b = models.CharField(max_length=20) c = models.CharField(max_length=20) 2.)serializer:- class RequestsSerializer(serializers.ModelSerializer): class Meta: model = Requests fields = '__all__' Now i am using serializers when creating a new record into DB table as:- serialized_item=RequestsSerializer(data=request.data) serialized_item.is_valid(raise_exception=True) serialized_item.save() now i had a doubt that is_valid is hitting DB and .save again hit DB, So because of Serializer we are hitting DB 2 times and if we remove that and directly create a record into database then it will hit the database only once. So here serialier is just adding overhead on database right?, So what is the use of Serializer here? -
How can I get annotate field using child model in Django?
I have problem with getting Annotate field in Django(DRF). For example, there are two models called AA, BB. class AA(models.Model): name = models.CharField() class BB(models.Model): parent = models.ForeignKey(AA, related_name="BB") name2 = models.CharField() Then, I want to get the list AA, with annotate field called status. The status condition is word(provided by client)=name2 For example, [ { name: "aaa1", status: True, // if "aaa1" in AA has the word }, { name: "aaa2", status: False, // if "aaa2" in AA doesn't have the word } ] So I coded like following code in views.py, queryset = (AA.objects.prefetch_related("BB").annotate( status=Case( When(BB__name2=word, then=Value(True)), default=Value(False), output_field=BooleanField() ) )) but the following results came out. (If the word is "bbb1") [ { name: "aaa1", status: True, // "bbb1" whose parent is "aaa1" }, { name: "aaa1", status: False, // "bbb2" whose parent is "aaa1" }, { name: "aaa1", status: False, // "bbb3" whose parent is "aaa1" }, { name: "aaa2", status: True, // "bbb1" whose parent is "aaa2" } ] I want to know if even one child model(BB) has name2 from a parent(AA)'s point of view, and it returned a list of all children. What should I do? -
Deploying Django App onto Elastic Beanstalk (mysqlclient issue)
Having a bit of a mare trying to deploy my Django app to Elasticbeanstalk AWS I'm getting issues related to the installation of mysql. See log files: ---------------------------------------- /var/log/eb-engine.log ---------------------------------------- × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module> main() File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 155, in <module> File "<string>", line 49, in get_config_posix File "<string>", line 28, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] My Python pip requirements file is: beautifulsoup4==4.12.3 bs4==0.0.2 Django==2.2 gunicorn==20.1.0 mysqlclient==2.2.4 numpy==1.24.4 pandas==2.0.3 python-dateutil==2.9.0.post0 pytz==2024.1 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 tzdata==2024.1 whitenoise==6.4.0 and I've also specified … -
Difficulty in getting the number of data
Difficulty in getting the number of data, which does not receive all the data model is : class ArchiveChat(models.Model): id = models.BigIntegerField() user_jid = models.CharField(max_length=255,primary_key=False) class Meta: db_table = 'li_archive_chat' message_count = ArchiveChat.objects.count() message_count is 77000 The number of real data is 78 thousand, but this query returns 77 -
added gml layer to openlayers does not appear on map
I recently moved from using leaflet to using openlayers. For a new project I want to display the content of a gml file on a openlayers map. But whatever I have tried nothing gets visible on the map. When I print the content of the fetch response I see the string of the gml content being printed perfectly to the console however when I print the features variable after parsing the gml I end up with an empty array. I have read the official documentation and written some javascript code according to the API discription. I use a python request in django to obtain the text content of the gml and make it accessable for the front end javascript. When I log the fetch response to the console in dev tools I see that the string of the fetch response get's printed succesfully, however when I log the features variable to the console I end up with an empty array and nothing visible on the map. The gml file that I try to add to the map can be found here: https://ruimtelijkeplannen.nl/documents/NL.IMRO.0252.GHbpkernMalden-VA01/NL.IMRO.0252.GHbpkernMalden-VA01.gml My used javascript code: import Map from '../../../node_modules/ol/Map.js'; import OSM from '../../../node_modules/ol/source/OSM.js'; import TileLayer from '../../../node_modules/ol/layer/Tile.js'; import View … -
Implementing Email Confirmation & Reminder System and WhatsApp Messaging Integration in Django
I'm developing a Django-based project that requires implementing an email confirmation and reminder system, as well as WhatsApp messaging integration. The project has specific user engagement features, such as sending confirmation emails upon survey completion and scheduling reminder emails, with an expected volume of about 50,000 emails per month. Additionally, it involves sending automated WhatsApp messages to users based on their interactions with the platform. Here are the technical challenges I'm facing: Email System Implementation: How can I efficiently manage and send a large volume of emails (approx. 50,000/month) in Django? What are the best practices for scheduling and sending reminder emails at predetermined dates? I'm particularly interested in understanding how to optimize Django's email backend for this scale and whether Django's built-in features or third-party libraries are more suited for this task. WhatsApp Messaging Integration: What is the recommended approach for integrating WhatsApp messaging into a Django application? Are there specific Django packages or tools that facilitate this integration while ensuring scalability and reliability? My main objective is to implement these features in a cost-effective and efficient manner, focusing on scalability and reliability. I'm looking for insights into the technical implementation within Django's framework that adhere to best practices. … -
Can't add value to table Django DataBase
Sorry i am beginer in django try to make app for appoiment for doctors and could not solved this problem I can't add value in to Appoiment Db in to django app this is my models.py from django.db import models models.py_ doctor_name = models.CharField(max_length=80) specialization_doctor = models.CharField(max_length=80) def __str__(self): return self.doctor_name class Appoiment(models.Model): doctor_name = models.ManyToManyField(Doctors) date_appoiment = models.DateField() time_appoiment = models.TimeField() patient_name = models.CharField(max_length=80) patient_phone = models.CharField(max_length=15) reason_for_visit = models.TextField(max_length=400) def __str__(self): return self.patient_name And this is my views.py i'm trying many ways but steal can't approch to solve it VIEWS.PY from django.shortcuts import render from .models import Doctors,Appoiment from .forms import AppoimentForm from django.http import HttpResponseRedirect def main(request): list_of_doctors = Doctors.objects.all().values('doctor_name') list_of_doctors = [item['doctor_name']for item in list_of_doctors] doctor_name='' date_appoiment='' time_appoiment='' name='' phone='' reason='' form = '' patient='' if request.method == 'POST': doctor_name = request.POST.get('doctor_name') date_appoiment = request.POST.get('date') time_appoiment = request.POST.get('time') name = request.POST.get('name') phone = request.POST.get('phone') reason = request.POST.get('reason') # doctor = Doctors() # The problem is here how to write right statement #------->> patient = Appoiment.objects.create(doctor_name=doctor_name,date_appoiment=date_appoiment,time_appoiment=time_appoiment,patient_name=name,patient_phone=phone,reason_for_visit=reason) return render(request,'main.html',{'list_of_doctors':list_of_doctors,'patient':patient})``` -
UNIQUE constraint failed: customuser.username
im trying to understand the drf. I´ve set up all the endpoints and they work, the only thing that doesnt work is when i want to post something to my database, the first Post goes well and then the second one shows an integrity error, ive been stuck now for a few days haha Could somebody help me understand what i am missing here models.py : class CustomUser(AbstractUser): name = models.CharField(max_length=30) email = models.EmailField(default ="no email") first_name = models.CharField(max_length = 25 ,default = 'No name') last_name = models.CharField(max_length = 25, default = 'No surname') password = models.CharField(max_length = 25,default = "no password") def __str__(self): return self.name views.py class CustomModelViewSet(ModelViewSet): serializer_class = UserSerializer queryset = CustomUser.objects.all() @api_view(['GET', 'POST']) def user_list(request,format =None): #get all users #serialize them #return json if request.method == 'GET': allUser = CustomUser.objects.all() serializer = UserSerializer(allUser, many=True) return Response(serializer.data) elif request.method =='POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) @api_view(['GET','PUT','DELETE']) def user_detail(request,id,format =None): try: user = CustomUser.objects.get(pk=id) except CustomUser.DoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': user.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py class … -
Django-cte gives: 'QuerySet' object has no attribute 'with_cte'
I have records in below format: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| |5 | B |2024-02-01T02:49:47.327583-07:00| Model: class Model1(model.Models): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I want to perform a group by in django with month from field created and get latest record from that month. Expected output: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| I am using django-cte to perform the above action from django.db.models.functions import ExtractMonth m = Model1.objects.get(id=1) cte = With( Model1.objects.filter(name=m.name) rank=Window( expression=DenseRank(), partition_by=[ExtractMonth("created")], order_by=F("created").desc(), ) ) qs = cte.queryset().with_cte(cte).filter(rank=1) But the above give error: qs = cte.queryset().with_cte(cte).filter(rank=1) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'QuerySet' object has no attribute 'with_cte' Please help! -
Django test_get_chat_list
I have a really strange problem because my ...chat_list test returns every time different result, test is waiting for the order [2 3 1] but is's every time different. Here my test: def test_get_chat_list(self): # Create 3 users with whom we will have chats. user_1 = UserFactory() user_2 = UserFactory() user_3 = UserFactory() # Create chats with them chat_1 = ChatFactory(user_1=self.user, user_2=user_1) chat_2 = ChatFactory(user_1=self.user, user_2=user_2) # Let our user be in the role of user_2 in the third chat. chat_3 = ChatFactory(user_1=user_3, user_2=self.user) # Create one message in each chat. # To test the correctness of sorting chats # we intentionally create a message first in the third chat, # and then in the second. mes_1 = MessageFactory(author=self.user, chat=chat_1) mes_3 = MessageFactory(author=self.user, chat=chat_3) # Also create one message from the interlocutor. mes_2 = MessageFactory(author=user_2, chat=chat_2) # Create a batch of foreign messages in foreign chats. # They are needed to make sure # that we only receive our chats and messages. MessageFactory.create_batch(10) with self.assertNumQueries(2): response = self.client.get(self.url, and here my view function: def get_queryset(self): user = self.request.user last_message_subquery = Message.objects.filter( chat=OuterRef('pk') ).order_by('-created_at').values('created_at')[:1] last_message_content_subquery = Message.objects.filter( chat=OuterRef('pk') ).order_by('-created_at').values('content')[:1] qs = Chat.objects.filter( Q(user_1=user) | Q(user_2=user), messages__isnull=False, ).annotate( last_message_datetime=Subquery(last_message_subquery), last_message_content=Subquery(last_message_content_subquery), ).select_related( "user_1", … -
Bug that requires a lot of "Djongo migrate"
I'm using djongo. I don't know what the cause is, but a message asking me to run python manage migrate appears from time to time. Does anyone know the cause? please. requirement.txt django==4.1.13 django-cors-headers django-mongoengine pytz beautifulsoup4 lxml requests selenium djongo==1.3.6 mongoengine==0.27.0 graphene-django graphene_mongo pymongo==3.12.3 pytesseract pyftpdlib openai==0.28 Nothing in particular was done. -
Stop isort reordering specific imports
When I run isort on this init.py file it reorders the imports alphabetically, moving instruments into the correct alphabetical position. from .administration_model import Administration # noqa from .administration_model import AdministrationSummary, administration_data # noqa from .instrument_model import Instrument # noqa from .benchmark import Benchmark # noqa from .demographic import Demographic # noqa from .instrument_family import InstrumentFamily # noqa from .instrument_score import InstrumentScore # noqa from .ip_address import ip_address # noqa from .measure import Measure # noqa from .payment_code import PaymentCode # noqa from .researcher_model import Researcher # noqa from .study_model import Study # noqa from .summary_data import SummaryData # noqa But Benchmark.py is dependent upon it and needs importing first. How do I prevent the reordering in this file only? -
Data Is not being sent to the django endpoint
I am trying to send data to my django endpoint. Which will then be used to compare against the entries made in the database. The data is not being sent to the endpoint, therefore I am getting a Invalid request error on my browser console when calling the api/login endpoint.Here is my frontend code import React, { useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import '../css/login.css'; import axios from 'axios'; function Login() { const [formData, setFormData] = useState({ username: '', password: '' }); const navigate = useNavigate(); const handleChange = (e) => { const { name, value } = e.target; setFormData(prevState => ({ ...prevState, [name]: value })); }; const handleSubmit = async (event) => { event.preventDefault(); try { const response = await axios.post('http://127.0.0.1:8000/api/login/', formData); if (response.data.message) { switch (response.data.role) { case 'Business Development Partner': navigate('/bdpdashboard'); break; case 'Recruiter': navigate('/employeedashboard'); break; case 'Manager': navigate('/managerdashboard'); break; case 'Business Development Partner Manager': navigate('/bdpmdashboard'); break; case 'Account Manager': navigate('/amanagerdashboard'); break; default: console.error('Invalid role:', response.data.role); } } else { console.error('Login failed:', response.data.error); } } catch (error) { console.error('Login failed:', error); } }; return ( <div className="login-container"> <h2>Login</h2> <form onSubmit={handleSubmit}> <div className="input-group"> <label htmlFor="username">Username</label> <input type="text" id="username" name="username" value={formData.username} onChange={handleChange} required /> … -
Model.objects.get not returning anything
So I am trying to retrieve data from the database so that I can compare those values with the values entered by the user and show then the appropriate page I have made sure that the database table linked to the view has data. Here is the view @csrf_exempt def verify_login(request): if request.method == 'POST': data = request.POST user = data.get('username') # Retrieve stored login details stored_login = LoginDetails.objects.get(username__iexact=user) print(stored_login.username) if stored_login: # Compare the passwords directly if data.get('password') == stored_login.password: # Authentication successful user_role = stored_login.user_data.role if stored_login.user_data and stored_login.user_data.role else None print(user_role) return JsonResponse({'message': 'Login successful', 'role': user_role}) else: # Password does not match return JsonResponse({'error': 'Invalid password'}, status=401) else: # Username not found return JsonResponse({'error': 'Invalid username'}, status=401) return JsonResponse({'error': 'Invalid request method'}, status=405) And printing the stored_login print None on the python terminal running the django server. I get the following error on the console <h1>DoesNotExist at /api/login/</h1> <pre class="exception_value">LoginDetails matching query does not exist.</pre> To check whether the data exists in the LoginDetails model, I ran the following commands python3 manage.py shell from backend_app.models import LoginDetails LoginDetails.objects.all() I get the following output <QuerySet [<LoginDetails: qwerty>]> I am also posting the frontend page which gets the … -
how to load image from user side
I am working on real estate website. so, user can upload their property. i can upload from admin side. But when user try to upload it is not working. below is my code. My settings.py: import os MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py: from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My models.py: media = models.ImageField(upload_to='images') my rent.html: <a href=""><img class="img-fluid" src="{{i.image.url}}" alt=""></a> -
Seeking Recommendations for Email and WhatsApp Integration in Django Project
I'm currently developing a Django-based project with a couple of key features focused on user engagement and reminders. Here's an overview: Email Confirmation & Reminder System: Upon completion of specific surveys by users, the system should automatically send confirmation emails. It should also be capable of scheduling and sending reminder emails to users on predetermined dates. The expected volume of emails is around 50,000 per month. WhatsApp Messaging Integration: Similar to the email system, I aim to implement automated WhatsApp messages that will be sent to users who interact with our platform in a specific manner. Given the outlined requirements, I have a few questions: For Email Automation: Are there any free services available that can handle the email volume mentioned above? If free options are limited or unavailable, could you suggest any cost-effective, reliable API providers for this purpose? For WhatsApp Integration: What are the typical costs associated with integrating WhatsApp messaging in such a manner? Are there any free or low-cost services available for automating WhatsApp messages? I'm looking for recommendations on tools or services that integrate well with Django and can efficiently manage the described functionality. Cost-effectiveness and reliability are my primary considerations. Thank you in advance … -
how to sort django query result on a string field including software version x.y.z
I am write a web site using Django framework. I have a model that stores software and its version number in the format "x.y.z" (or "x", "x.y"), where x, y, and z are integer numbers. How can I sort the query results by the version number in ascending order? The default sorting behavior is based on string alphabet order, but not what I want. Thank you! -
Websocket jwt authentification keeps handshaking and disconnecting
I have this custom jwt auth-middleware in django: class JWTAuthMiddleware: def __init__(self, inner): self.inner = inner async def __call__(self, scope, receive, send): print(": Middleware called") headers = dict(scope['headers']) if b'authorization' in headers: print(": Authorization header found") try: token_name, token_key = headers[b'authorization'].split() if token_name == b'Bearer': print(": Bearer token found") user = await self.authenticate(token_key.decode()) if user is not None: print(": User authenticated") scope['user'] = user except InvalidTokenError: print(": Invalid token") await self.inner(dict(scope, user=None), receive, send) return except KeyError: print(": Invalid token format") await self.send_error(send, "Invalid token format") return else: print(": No authorization header found") await self.inner(dict(scope, user=None), receive, send) async def authenticate(self, token_key): print(": Authenticating user") try: secret_key = settings.SECRET_KEY decoded_token = decode(token_key, secret_key, algorithms=['HS256']) user_id = decoded_token['user_id'] user = await self.get_user(user_id) if user is not None and user.is_authenticated: print(": User authenticated successfully") return user except (InvalidTokenError, KeyError): print(": Authentication failed") pass return None @database_sync_to_async def get_user(self, user_id): print(": Retrieving user from database") try: return User.objects.get(user_id=user_id) except User.DoesNotExist: print(": User not found") return None When i make a request through postman or flutter,after a user logs in and selects a group to access its chat_screen : void _initializeWebSocket() async { print("_initializeWebSocket called"); SharedPreferences prefs = await SharedPreferences.getInstance(); String? accessToken = prefs.getString('accessToken'); … -
Model Form Data is not Visible When i try to update the model in django
so this is the view : def update_ticket(response,ticket_title): ticket = get_object_or_404(TicketsModel, title=ticket_title) ticket_form = AddTicketsForm(response.POST or None,instance=ticket,assigned_by=response.user) if 'return' in response.POST: return redirect('home', type_user=response.session.get('type_user')) if ticket_form.is_valid(): ticket.ticket_creation_date = datetime.now() ticket_form.save() return redirect('home', type_user=response.session.get('type_user')) return render(response, "template/testapp/update_ticket.html", {'ticket_title': ticket.title, 'ticket_form': ticket_form}) the problem is , when i render the form , i dont see the data inside of the inputs , but if i delete the 'response.POST' in the AddTicketsForm() , i can see the data but i cant update nothing here is the html content <h2>Update Ticket</h2> <form action="{% url 'update_ticket' ticket_title=ticket_title %}" method="post"> {% csrf_token %} {{ ticket_form.as_p }} <button type="submit" name="save" id="regDirect" >Save</button> <button type="submit" name="return">Return</button> <form/> -
Can't get id_token with Auth0 backend
I'm currently implementing the Auth0 OAuth2 backend in python-social-auth and social-app-django. At the start of the social-core pipeline, after I log into Auth0, I get an error during Auth0OAuth2.get_user_details() at jwt.decode(): DecodeError at /complete/auth0/: Invalid token type. Token must be a <class 'bytes'>. I've pasted that code below: def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get("id_token") jwks = self.get_json(self.api_path(".well-known/jwks.json")) issuer = self.api_path() audience = self.setting("KEY") # CLIENT_ID ... signature_error = None for key in keys: try: payload = jwt.decode( id_token, key.key, algorithms=["RS256"], audience=audience, issuer=issuer, ) I assume the error is because response.get("id_token") is always None; the response argument only has keys for access_token, expires_at, and token_type. I must be missing something in my setup, but there's no documentation for the Auth0 backend in python-social-auth, so I'm not sure what could be wrong. I have the following environment vars set: SOCIAL_AUTH_AUTH0_KEY SOCIAL_AUTH_AUTH0_SECRET SOCIAL_AUTH_AUTH0_DOMAIN My Auth0 app is a Regular Web App on a developer account, and changing the app's grant types and authentication method hasn't fixed the error. -
How to create Gravis visualization in webpages using Django?
I want to display an interactive network graph on my webpage (similar to the ones shown here), and I am using Networkx, Gravis, and Django. The image does not show up, and neither does it thow any errors. I would like suggestions or corrections to my code (given below) so that I can get the thing working... Suggestions for using alternative packages are also welcome, as long as the packages are easy to work with from within a Django project/app. My end goal is to make the nodes in the interactive plot clickable, so that I can get the names of the nodes the user clicks...but I guess that comes later. First I need to get the basic network graph to at least show up on the webpage. Here are my codes: views.py from django.shortcuts import render import pandas as pd import networkx as nx import gravis as gv from django.http import HttpResponse def merge(list1, list2): merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))] return merged_list def plot_netx_gravis(topic_string,request): nx_csv=pd.read_csv('NetworkXNodes/'+topic_string+'_NetworkX_Edgelist.csv', index_col=None) connection_tuples=merge(nx_csv['Child'].to_list(),nx_csv['Parent'].to_list()) G1=nx.DiGraph() G1.add_edges_from(connection_tuples) image=gv.d3(G1) template = 'topics4node_2.html' return render(request, template, {'image':image.to_html()}) topics4node_2.html {% extends 'base.html'%} {% block title %}Gravis Graph{% endblock %} {% load crispy_forms_tags %} {% block content … -
database and django merging problem data is not showing in my html pages
i made database and insert data through pop sql and now i want to display inserted data in my html in django project what steps should i follow???..and the data is not shown in the html pages after doing so many things in setting i changes the database name but it is not working. i write py manage.py migrate but the data in my database is not showing