Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add a JavaScript event to my Django HTML template?
My current logout is GET, I just redirect the user to /auth/logout However, I’ve discovered that this is unsafe and I trying to add a post to this redirection. By the way, my login is using django-allauth, so I am looking to use this concept here too. But, I need to do it with JavaScript because my front end is written in Vue.js. https://django-allauth.readthedocs.io/en/latest/views.html#logout-account-logout This is my javascript file where I use too much vue: let userNavigation = [ { name: 'Account', href: '/account/'}, { name: 'Logout', href: '/auth/logout'} ] This is my HTML using vue const menu = ` <MenuItems> <MenuItem v-for="item in userNavigation" :key="item.name"> <a :href="item.href"> [[ item.name ]] </a> </MenuItem> </MenuItems> ` This is what I am trying to do to: <script type="text/javascript"> function logoutPost() { let form = document.createElement('form'); form.setAttribute('method', 'post'); form.setAttribute('action', '/auth/logout/'); let csrf = document.createElement('input'); csrf.setAttribute('type', 'hidden'); csrf.setAttribute('name', 'csrfmiddlewaretoken'); csrf.setAttribute('value', '{{ csrf_token }}'); form.appendChild(csrf); document.body.appendChild(form); let logoutAnchor = document.getElementsByName('Logout')[0].value; form.appendChild(logoutAnchor); logoutAnchor.addEventListener('click', function (e) { e.preventDefault(); form.submit(); console.log("logout clicked"); }); } </script> But, even if I try to add JavaScript DOM, nothing changes, I do not see anything in my console log and it just redirects. Where I am making a mistake? -
My API is sending data but its not getting stored in the backend
So i was following this tutorial https://youtu.be/hISSGMafzvU, with different approach of mine ( instead of being a to do app, I'm trying to make it a clinic management system ). So the problem I'm facing is that my api is receiving data, and there is no errors plus I'm getting 200 status code from the local server which means everything is okay, but its not hence the data isn't being stored in the DB for some reason. this is the code: models.py class Employee(models.Model): fullname = models.CharField(max_length = 250) age = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=(('Male', 'Male'), ('Female', 'Female')), default='Male') usertype = models.CharField(max_length = 50, choices= (('Admin','Admin'),('Doctor','Doctor'),('Receptionist','Receptionist')), default='Receptionist') def __str__(self): return self.fullname class Patient(models.Model): fullname = models.CharField(max_length = 250) def __str__(self): return self.fullname class Appointments(models.Model): Paitent_Attending = models.ForeignKey(Patient, on_delete= models.CASCADE) Doctor_Attending = models.ForeignKey(Employee, on_delete= models.CASCADE) appointment_date = models.DateField() def __str__(self): return self.Paitent_Attending.fullname serializers.py from rest_framework import serializers from .models import Employee,Patient,Appointments class PatientSerializers(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' class EmployeeSerializers(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class AppointmentsSerializers(serializers.ModelSerializer): class Meta: model = Appointments fields = '__all__' views.py from django.shortcuts import render from rest_framework import generics from .models import * from .serializers import * from … -
Pandas read_sql_query function not working
I have configured the database connection and sql query in a pandas read sql query function, but when the function is running its throwing an error. def fetchDbTable(candidate_id): start_time = time.time() # candidate_id = 793 schema = env_config.get("DEV_DB_SCHEMA_PUBLIC") # Create Db engine engine = createEngine( user=env_config.get("DEV_DB_USER"), pwd=env_config.get("DEV_DB_PASSWORD"), host=env_config.get("DEV_DB_HOST"), db=env_config.get("DEV_DB_NAME"), ) # Create query for resume query_resume = ( """ select a.*, b.*, c.* from """ + schema + """.resume_intl_candidate_info a, """ + schema + """.resume_intl_candidate_resume b, """ + schema + """.resume_intl_candidate_work_experience c where a.c_id = b.c_id_fk_id --and a.c_id = c.c_id_fk_id and b.r_id = c.r_id_fk_id and b.active_flag = 't' and a.c_id = """ + str(candidate_id) ) # Fetch database df_resume = pd.read_sql_query(query_resume, con=engine) pandas current version- 1.5.2, numpy current version-1.23.5 in local but the version used in the server is pandas - 0.23.0, numpy = 1.16.5 I need to change the code for the latest version and run it without an error. Can you please help me fix the issue I had spent more than 2 days and i couldn't able to come to a solution. Error throwing as: Traceback (most recent call last): File "/home/vinoth/Documents/Req_Intelligence-master/Req_Intelligence-master/req_intl/resume_intl/extractedfields.py", line 483, in save_create_document meta_df = fetchDbTable(candidate_info.c_id) File "/home/vinoth/Documents/Req_Intelligence-master/Req_Intelligence-master/req_intl/resume_intl/candidate_meta_info.py", line 132, in fetchDbTable df_resume = … -
How to join 2 tables with getting all rows from left table and only matching ones in right
Table 1 Table 2 Table2.plan_selected shows what plan did the user choose. Eg: The user with user_id=4 in Table2 choose the id = 2 plan from Table1. I want to get all the rows from Table1 and only matching rows from Table2 for a particular user_id. The expected result is like this. I want to fetch all the rows of Table1 and only the selected plan from Table2 for a particular user_id lets say 4. The expected result will be like this: id name plantype plandetails requestpermonth price isdeleted planselected 1 EXECUTIVE MONTHLY {1000 MAY REQUSTS} 1000 50 0 NULL 2 BASIC MONTHLY {500 MAY REQUSTS} 1000 25 0 2 3 FREEEE MONTHLY {10 MAY REQUSTS} 1000 0 0 NULL 4 EXECUTIVE YEARLY {1000 MAY REQUSTS} 1000 500 0 NULL 5 BASIC YEARLY {500 MAY REQUSTS} 1000 250 0 NULL 6 FREEEE YEARLY {10 MAY REQUSTS} 1000 0 0 NULL What I have tried to do was use a simple left join. select plans.id, name, plan_details, plan_type, request_per_month, price,is_deleted, plan_selected from SubscriptionsPlans as plans left join SubscriptionsOrder as orders on plans.id=orders.plan_selected where orders.user_id = 4 These are my 2 models. ORM queryset or SQL query will help class SubscriptionsPlans(models.Model): id … -
Run django inside docker in airflow
Hellow I'm trying to run django inside a docker in Airflow through a Docker_Operator. The Docker_Operator remains in the Running state and does not enter the Success state. When I try to enter the IP address of the Web server, it does not show me anything. I've tried running Django in Airflow by having Django inside a Docker. Django starts up the service at address 0.0.0.0:8000 and Docker_Operator is left running without reaching the succed state. In addition to this, I cannot enter the webserver, but that may be a problem with the IP configuration since I am running it in a VM. I have configured the ALLOWED_HOSTS with the address of my VM but it does not let me enter either. Port 8000 is enabled, and I have verified it by running the container outside of Airflow and it shows me the Webserver without problems. Anyone know what might be happening? -
I created my own Memeber model in django and now I need to validate password in it with login credentials
This is My new_user model which I stores my user registration data I can save my data to database using this model its working properly. new_user model ` class new_user(models.Model): stuname = models.CharField(max_length=200) stubirthday = models.DateField() stuphoto = models.ImageField() stugemail = models.EmailField() stugrade = models.IntegerField() stuclass = models.CharField(max_length=1) sturegdate = models.DateField(auto_now_add=True) stuentrance = models.IntegerField() sturesidance = models.TextField() stuguardian = models.CharField(max_length=200) stugtele = models.IntegerField() stugemail = models.EmailField() stumother = models.CharField(max_length=200) stumothertele = models.IntegerField() stuotherskills = models.CharField(max_length=200) stucertificate = models.FileField() stuletter = models.FileField() stumedical = models.FileField() stusports = models.CharField(max_length=200) stupassword = models.CharField(max_length=200) def __str__(self): return self.stuname ` I have inherited another model named Member from this model to store my approved users. I use this model to give auto username. I inherited this class from new_users model because all my values saved in new_user are presented here. I am not sure about this decleration can someone tell me if my approach is correct Member model ` class Member(new_user): uid = models.AutoField(primary_key=True) uname = models.CharField(default=f'{super.stuname[:2]}{uid}',unique=True) password = super.stupassword office_role = models.OneToOneField(Roles.rname) mem_roles = [office_role ,'Member'] def __str__(self): return self.uname ` Since one member can have one office role and member role I created this model to store my member roles Roles model # … -
DRF Pymongo - POST Body insert_one Operation
I'm trying to use insert_one to insert a JSON document into a collection. The JSON comes from the POST body. I'm using a simple view and a serializer to validate the data and them I'm trying to insert it into the collection. However, I cannot get this thing to work at all. class Patient(APIView): def post(self, request, format=None): data = JSONParser().parse(request) print(data) # prints -> {'name': 'Jason'} serializer = PatientSerializer(data = data) if serializer.is_valid(): FHIR_Patients.insert_one(data) # throws error return Response(data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) The error that I get is: Traceback (most recent call last): File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/renderers.py", line 99, in render ret = json.dumps( File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/site-packages/rest_framework/utils/encoders.py", line 67, in default return super().default(obj) File "/opt/miniconda3/envs/oncoregistry-analytics/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of … -
DRF nested serializer is not serializing data
I am trying to serialize nested models for an API view. class Dashboard(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='dashboards') title = models.CharField(max_length=100) type = models.CharField(max_length=100) position = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) class WidgetLayout(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='widgets') dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE, related_name='widgets') type = models.ForeignKey(Widget, on_delete=models.CASCADE) position = models.IntegerField() width = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) with the following serializers class WidgetLayoutSerializer(serializers.ModelSerializer): class Meta: model = WidgetLayout fields = ['id', 'type', 'position', 'width', 'config'] class DashboardSerializer(serializers.ModelSerializer): class Meta: widgets = WidgetLayoutSerializer(many=True) model = Dashboard fields = ['id', 'title', 'position', 'config', 'type', 'widgets'] The view calls the serilizers like this: dashboards = request.user.dashboards.all() serializer = DashboardSerializer(dashboards, many=True) The expected output would be a list of Widgets in their JSON serialization for each Dashboard, however, I get only a list of Widget-IDs. I discovered that, if i remove the widgets = WidgetLayoutSerializer(many=True), the result is the same, so I suspect, the serializer is not being used or referenced properly. I went through https://www.django-rest-framework.org/api-guide/relations/#example and tried to spot any difference, but could not find it. Adding the prefetch_related for the widgets to the .all() in the view made … -
How to fix cryptography module import error?
I was trying to encrypt one field of a model with some libraries: django-encrypted-model-fields django-mirage-field encrypt-decrypt-fields After that, the project started to giving errors even though I uninstall all of the libraries and remove all the codes. I have no idea why. How can I solve it? Traceback (most recent call last): ... self.encryptor = Cipher(algorithms.AES(self.key),modes.CTR(self.nonce)).encryptor() File "/Library/Python/3.9/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 86, in __init__ backend = _get_backend(backend) File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend return default_backend() File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 14, in default_backend from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module> from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 113, in <module> from cryptography.hazmat.bindings.openssl import binding File "/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module> from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: dlopen(/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so, 0x0002): tried: '/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so' (mach-o file, but is an incompatible architecture (have (arm64), need (x886_64))) -
Django - migrate command not using latest migrations file
I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5. Any help would be great. -
VS Code - broken auto check of links for Django/Python
this is stupid question, but I used to have in Django/Python files in VS Code automatic check by yellow colour, that model, variable, view, function etc. are correctly somewhere defined and I can use them. But something broke and everything is now white. Does anybody know, where to switch on again this check for Python/Django? HTML and JavaScript files are working fine, but for Python files it was broken. Thanks a lot for any help. -
Get all the rows of a table along with matching rows of another table in django ORM using select_related
I have 2 models Model 1 class Model1(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.CharField(max_length=255) details = models.TextField(max_length=1000) price = models.FloatField() Model 2 class Model2(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE ) plan_selected = models.ForeignKey(Model1) I am trying to check whether a user has selected any plans. The field plan_selected is a foreign key for Model1 - id. I want to get all details of Model1 along with details of Model2 in a single line of the query set using Django. So far I have tried to get is : sub_details = Model1.objects.select_related('Model2').filter(user_id=id) -
How to store tran_id and val_id in database using?
My motive is to implement the payment gateway in my e-Commerce website using sslcommerz-python by clicking the buy now button. The payment gateway is working well. Now I want to store tran_id and val_id in the PurchasedItem model so that the admin can understand which product a user ordered and whether the user payment is done or not. How can I do it? I tried different ways, but these didn't work😥. Give me a relevant solution😊... views.py: def MakePayment(request,pk): mypayment = SSLCSession(sslc_is_sandbox=True, sslc_store_id=store_id, sslc_store_pass=API_key) status_url = request.build_absolute_uri(reverse('PaymentStatus')) mypayment.set_urls(success_url=status_url, fail_url=status_url, cancel_url=status_url, ipn_url=status_url ) #product information orderItem = get_object_or_404(FoodMenu, pk=pk) mypayment.set_product_integration( total_amount=Decimal(order_total), currency='BDT', product_category='Mixed', product_name=orderItem, num_of_item=orderQTY, shipping_method='Courier', product_profile='None' ) #sender info mypayment.set_customer_info( name=request.user.first_name, email=request.user.email, address1=request.user.address, address2=request.user.address, city=request.user.district, postcode=request.user.zipcode, country='Bangladesh', phone = request.user.phone_number ) #billing info mypayment.set_shipping_info( shipping_to=request.user.first_name, address=request.user.address, city=request.user.district, postcode=request.user.zipcode, country='Bangladesh' ) response_data = mypayment.init_payment() if request.method == "POST": PurchasedItem.objects.create( user = request.user, item=orderItem, address=request.POST.get('address'), ) return redirect(response_data['GatewayPageURL']) NOTE: Security purpose I did not mention value of store_id and API_key @csrf_exempt def PaymentStatus(request): if request.method == 'POST' or request.method == 'post': payment_data = request.POST status = payment_data['status'] if status == 'VALID': tran_id = payment_data['tran_id'] val_id = payment_data['val_id'] messages.info(request,"Your payment successfully done.") return HttpResponseRedirect(reverse("PurchasedProduct", kwargs={'tran_id':tran_id, 'val_id':val_id})) return render(request, 'payment_status.html') def PurchasedProduct(request,tran_id,val_id): context = … -
ERROR.. Unhandled exception during build. When running pipeline
trying to run a pipeline, my set up : GitHub Elastic Beanstalk with autoscaling and load balancer S3 Bucket for persistent static-files After running the pipeline it fails to deploy all instances with the same version. So from my logs I've found out that it fails when running the container_commands. option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files **container_commands: 10_deploy_hook_permissions: command: | sudo find .platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \;** Which it execute this : #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py collectstatic --noinput python /var/app/current/manage.py migrate NOTE: The app deploys perfectly fine when I run "eb deploy", but when deployment is triggered from pipeline than it goes in to "Degraded" status where the instance is still running but apparently no all the instances are running the same version. Error from health: over all : - Command failed on all instances. - Incorrect application version found on all instances. Expected version "app-221124_115515680871" (deployment 418). instance : - Application deployment failed at 2022-11-24T11:32:55Z with exit status 1 and error: Engine execution has encountered … -
Serializers not working on multiple levels as expected in Django
I have 4 models and 3 serializers. 1 model is a simple through table containing information about which user posted which reaction about which article. models.py class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) ... class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) author = models.ForeignKey(User, related_name='authored', on_delete=models.PROTECT) ... class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='reacted', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_details', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) class Sentiment(models.Model): like = models.IntegerField(default=1) dislike = models.IntegerField(default=-1) serializers.py class UserSerializer(serializers.ModelSerializer): authored = ArticleDetailSerializer(many=True, read_only=True) reacted = ReactedSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'username', 'authored', 'reacted', ) model = User class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Article class ReactedSerializer(serializers.ModelSerializer): article_details = ArticleDetailSerializer(many=True, read_only=True) class Meta: fields = ( 'sentiment', 'article_id', 'article_details', ) model = Reaction Currently, the output for a GET request for a User shows authored correctly. I copied the logic so reacted can be a multi-level object containing sentiment and the relevant article information. I've tried many solutions yet the result for the User field reacted never includes the article_details field. I've ensured the related_name field in in the Reacted model is article_details so what am I missing? I've … -
Django override save method with changing field value
I need some help with overriding save method with changing field value. I have such structure: models.py class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) to_categories = models.ManyToManyField(Category, blank=True, related_name='categories', ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) So I can`t find a correct sollution for save method. I can select category on the "to_category" and categories on "to_categories" field, but I need if I selected one of the categories on the "to_category" field then save the Product, this selected field must be automatically selected on the "to_categories" field. Thanks for help. -
Correct escaping to use in Django templates to avoid Unterminated string literal errors in VS Code
Consider the following in a Django .html template <button onclick="location.href='{% url 'my-route' pk %}'"> # Warns because of this -------^.......^ VS Code will warn of an unterminated string literal as it doesn't understand that inside {% %} is processed first by the template engine. It works just fine, but the VS Code warnings (complete with red highlighting) are distracting. Any way to fix this either by escaping ' or " or changing some VS Code config? -
Dynamically define model attributes / database fields in Django
I would like to define a Django Model looking like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): object_id_1 = models.UUIDField() content_type_1 = models.ForeignKey(ContentType) object_id_2 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) object_id_3 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) # etc. d1 = GenericForeignKey("content_type_1", "object_id_1") d2 = GenericForeignKey("content_type_2", "object_id_2") d3 = GenericForeignKey("content_type_3", "object_id_3") # etc. Obviously, the more dimensions (d stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example. Is there a way to dynamically define these model attributes, for instance in a for loop, without using eval? If not, what would be the cleanest and safest way to resort to eval here? I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer. -
Change DRF url query filter pattern
The default DRF url pattern for search is "?search=<...>", where you search by a field you add in view's search_fields. How can I change it to "?field_name=<...>" ? How can I change "?field_name__lte=" to "?field_name[lte]=" ? -
how can I display or return a instance of a django model by using another instance(which is primary key)
I have Wallet class. user and Walletname are the instance of this class. when a new user is registered, the Wallet class is created by signal. the thing that ı would like to do is that displyaing or returning the Walletname of the current logged user. thank you I tried filtering but ı got error which is related with id it says %s is expected integer value? However ı have never created a instance named as id -
DRF APITestCase force_authenticate make request.user return tuple instead of User object
I have a custom authentication class following the docs class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) and I used it in my APIView: class profile(APIView): permission_classes = () authentication_classes = (ExampleAuthentication,) def get(self, request, format=None): try: print('user', request.user) serializer = GetUserSerializer(request.user) return JsonResponse({'code': 200,'data': serializer.data}, status=200) except Exception as e: return JsonResponse({'code': 500,'data': "Server error"}, status=500) when I try to call it normally from the API through postman I got the following result from the print and it worked normally: user (<User: User(143)>, True) I written a test as following: class BaseUserAPITest(APITestCase): def setUp(self): # self.factory = APIRequestFactory() self.user = models.User.objects.get_or_create( username='test_user_1', uid='test_user_1', defaults={'agent_type': 1} ) def test_details(self): url = reverse("api.profile") self.client.force_authenticate(user=self.user) response = self.client.get(url) self.assertEqual(response.status_code, 200) I got server error because the print of request.user return a tuple instead of a User object, this is the print from the test log user (<User: User(143)>, True) I tried searching up and seem like there no result or explanation on why this happening My version: django==2.2.8 djangorestframework==3.10.2 -
solr search object and object_list print None
I have implemented solr in django 4+ when i hit the query it return me result but when i run a loop sqs = SearchQuerySet().models(Post).all() sqs.count() # output 3 and run a loop for result in sqs: print(request) output <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> but object or object_list give me None for x in sqs.object_list: print(x) # None output or for x in sqs: print(x.object) # None solr-9.0.0 I want to print fields like x.title and x.publich etc what i am doing wrong please let me know -
Is this login fail? or?
when click login the page no blank to home page just stay in login page the terminal show me "GET /login/?csrfmiddlewaretoken=LK82SQKdzu802NaUuXom8CWRn3S86WWK0XrzEqFCCrUmGGCe06MXoMgFtt0JLDRN&username=tim&password=tim123 HTTP/1.1" 200 3148 and the browser link this http://127.0.0.1:8000/login/?csrfmiddlewaretoken=MWNadf5CSlSmTnCFIlJ5aoJDKHL1ShJJ196HZP01ViEIxg4Zeu7Gqy3rQ7TCxYEM&username=tim&password=tim123 login.html {% extends "main/base.html" %} {% block title %} Login Here {% endblock title %} {% load crispy_forms_tags %} {% block content %} <form class="from-group" method="get"> {% csrf_token %} {{form | crispy}} <button type="submit" class="btn btn-success">Login</button> <p>Don't have an account? Create one <a href="/register">Here</a></p> </form> {% endblock content %} settings.py (i just skip to STARIC it so long STATIC_URL = 'static/' CRISPY_TEMPLATE_PACK = "bootstrap4" (add) LOGIN_REDIRECT_URL = "/" (add) urls.py from django.contrib import admin from django.urls import path, include from register import views as v urlpatterns = [ path('admin/', admin.site.urls), path('register/', v.register, name='register'), path('', include('main.urls')), path('', include('django.contrib.auth.urls')), ] -
Django - problem with adding extra variable to the context that will count matched filters?
I have a function that gives me HTML with filtered products based on several filters that users can use on the website. The filters are the list of checkboxes (multiple choice of course). I managed to pass a product title but I also want to add the number of matched options next to each product title so if the user will select 3 out of 8 checkboxes in Filter 1 and Filter 2 lists then the list of matched product titles and the number of matched filters will be updated. For now the page it looks like this: What I want is this: Where 3 means that this product matches to all 3 options I selected and second product with 1 means that only 1 option matches from Filter 1 and Filter 2. I suppose that I need to add annotate with Count method but how can I do that if my fulter1 and filter2 is a list, not a queryset. views.py def filter_data(request): filter1 = request.GET.getlist('filter1[]') filter2 = request.GET.getlist('filter2[]') product_list = Product.objects.all() if len(filter1) > 0: product_list = product_list.filter(filter1__title__in=filter1).distinct() # how to add matched_products_count in here? if len(filter2) > 0: product_list = product_list.filter(filter2__title__in=filter2).distinct() # how to add matched_products_count in … -
Python-Docx - Jinja2: Populate word document without messing the template
I am trying to populate my word template with info from database. But it keep messing up the template. Any other way to make the result exactly the same as the template? template.docx result.docx Here's my code for views.py def save_devicedemoteapplication(request): samples = DeviceDemoteApplication.objects.all()[0:10] document = DocxTemplate("template.docx") context = { 'content': [], } for sample in samples: count = 0 samp= [count, sample.device.device_name, sample.device.asset_number, sample.device.device_model, sample.device.serial_number, sample.demote_reason, sample.demote_time, sample.device.buy_time, sample.technology_administrator, sample.quality_administrator] context['content'].append(samp) document.render(context) document.save('result.docx') return redirect('/DeviceDemoteApplication/')