Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UWSGI - Launch script with manage.py
I need to run a script into my Django project. I'm using this approach, that works, but I'm looking for more valid alternatives. uwsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") application = get_wsgi_application() __import__('myapp.script') import os os.environ = {'DJANGO_SETTINGS_MODULE': 'MyApp.settings'} import django django.setup() def main(): # some script using django db pass main() I've already look on uwsgi documentation and django, but can't find a way to run the manage.py. I don't like to use this approach because every time I need to set DJANGO_SETTINGS_MODULE, because I also want to run it locally. I prefere using the runscript. So, there is a way to call the manage.py from the wsgi module in order to use the runscript to run the script.py? Or, do you know another approach like the uwsgi.ini or something else? -
Is it possible to get a list of all deleted items in a django model without the use of safedelete or softdelete?
I'd like to have a record for all deleted items presented to the user. I've used safedelete but I want to change. -
Testing with Django's TestCase and async don't work with Database
So I'm using django_channels to handle some WebSocket stuff and since (Django 3.1)[https://docs.djangoproject.com/en/dev/topics/testing/tools/#testing-asynchronous-code] you can create unittest-like tests for testing async and decided to go with that. It happens to be that for some reason when accessing the Consumer can't reach the data. I'm using model_bakery (but also tried with plain Django ORM) and have a very simple test. class TestChatConsumer(TestCase): url = '/ws/chat/' def setUp(self): self.user = baker.make_recipe('registration.user') self.chat = baker.make_recipe('chat.chat') async def test_setup_channel_layer_ok(self): consummer = WebsocketCommunicator( application=AuthMiddlewareStack(ChatConsumer.as_asgi()), path=self.url, ) consummer.scope['user'] = self.user await consummer.connect() await consummer.send_json_to({ 'type': 'setup_channel_layer', 'chat': self.chat.pk, }) response = await consummer.receive_json_from() self.assertEqual(response['type'], 'info') self.assertEqual(response['content']['message'], 'Chat connected!') The problem is that on the test the entry is created but when accessing consumers the entry seems to be off. Do you know if there's any desync between test database or something? -
Getting values from queryset in Django
Facing troubles with getting values from foreign key models. I have one model, where included all foreign key relations. class UserAccount(models.Model): name= models.CharField(max_length=100) surname = models.CharField(max_length=100) category= models.ManyToManyField(Category) account = models.ForeignKey(Account) country = models.ForeignKey(Country) permissions = models.ForeignKey(Permissions) class Country(models.Model): iso_code = models.CharField(max_length=6) zip_code = models.CharField(max_length=10) I'm using this to get all fields related to model UserAccount: user_account_data = UserAccount.objects.all() name = user_account_data.values_list('name', flat=True))) surname = user_account_data.values_list('surname', flat=True))) But when trying this, its giving me: 'QuerySet' object has no attribute 'country' countries = user_account_data.country.values('iso_code') -
Django - uwsgi.py to run a python script
I need to run a script into my Django project. I'm using this approach, that works, but I'm looking for more valid alternatives. uwsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") application = get_wsgi_application() __import__('myapp.script') import os os.environ = {'DJANGO_SETTINGS_MODULE': 'MyApp.settings'} import django django.setup() def main(): # some script using django db pass main() I don't like to use this approach because every time I need to set DJANGO_SETTINGS_MODULE, because I also want to run it locally. I prefere using the runscript. So, there is a way to call the manage.py from the wsgi module in order to use the runscript to run the script.py? Or, do you know another approach like the uwsgi.ini or something else? -
Django channels send message stuck in for loop
I am calculating the task progress using for loop and trying to send the calculated value via sockets using async_to_sync but the process gets stuck and nothing happens. I am facing this issue only in loop but outside of loop I am able to send the message. consumers.py file import asyncio from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json import time class ProgressConsumer(WebsocketConsumer): def connect(self): self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(text_data=json.dumps({'status' : 'connected'})) def receive(self, text_data): print(text_data) for i in range(10): time.sleep(1) msg_dict = { "msg" : "msg "+str(i)+" sent from loop" } self.send(text_data=json.dumps(msg_dict)) def disconnect(self, *args, **kwargs): self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) print("disconnected") def send_progress(self, event): print("send progress") data = json.loads(event.get('value')) print("data :", data) self.send(text_data=json.dumps({"payload" : data})) print('send progress') Loop in which I am calling send progress function for line in loglines: cur_frame = int(line) prog = calulate_progress(int(n_frames),cur_frame) print("Progress is : "+str(prog)+"%") data = {"progress from loop" : prog} channel_layer = get_channel_layer() prog = prog async_to_sync(channel_layer.group_send)( "test_consumer_group", { "type": "send_progress", "value": json.dumps(data) } ) if prog == 100.0: break -
How do I link two views to one template file in Django
I'm trying to build a very basic messaging app where someone types into a text input, presses send then see's the message on the screen. And I want to do all of this on the same URL. Here is what I have right now: views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from message import models # Create your views here. class ViewMessages(ListView): model = models.Messages context_object_name = 'messages' class WriteMessages(CreateView): fields = ('message',) model = models.Messages models.py: from django.db import models from django import forms from django.core.urlresolvers import reverse # Create your models here. class Messages(models.Model): message = models.CharField(max_length=300) def __str__(self): return self.message def get_absolute_url(self): return reverse("view") project urls.py: from django.conf.urls import url from django.contrib import admin from message import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^view/', views.ViewMessages.as_view(), name="view"), url(r'^create/', views.WriteMessages.as_view(), name="create"), ] messages_form.html {% extends "message/base.html" %} {% block head_block %} <title>Create Message</title> {% endblock %} {% block body_block %} {% for message in messages %} <h3><div class="text-center"><span class="label label-default">{{ message.message }}</span></div></h3> {% endfor %} <form method="POST" class="form-horizontal"> {% csrf_token %} <div class="text-center" style="position: fixed; top: 500px;"> <span style="margin: 10px;">{{ form }}</span> <br> <input type="submit" value="Send" class="btn btn-primary btn-group btn-group-lg" > </div> </form> {% endblock %} … -
(IntegrityError at /Hod/Student/Add/ NOT NULL constraint failed: apps_customuser.username)
My data are not posted to the database (each fields are going but not the username) #my models class CustomUser(AbstractUser): USER = ( (1,'HOD'), (2, 'STAFF'), (3, 'STUDENT'), ) user_type = models.CharField(choices=USER,max_length=50,default=1) profile_pic = models.ImageField(upload_to='media/profile_pic') class Course(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Session_Year(models.Model): session_start = models.CharField(max_length=100) session_end = models.CharField(max_length=100) def __str__(self) : return self.session_start + " To " + self.session_end class Student(models.Model): admin = models.OneToOneField(CustomUser,on_delete=models.CASCADE) address = models.TextField() gender = models.CharField(max_length=100) roll = models.IntegerField() course_id = models.ForeignKey(Course,on_delete=models.DO_NOTHING) session_year_id = models.ForeignKey(Session_Year,on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) #my views @login_required(login_url='/') def Add_Student(request): course = Course.objects.all() session_year = Session_Year.objects.all() if request.method == 'POST': profile_pic = request.FILES.get('profile_pic') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') address = request.POST.get('password') roll = request.POST.get('roll') gender = request.POST.get('gender') course_id = request.POST.get('course_id') session_year_id = request.POST.get('session_year_id') if CustomUser.objects.filter(email=email).exists(): messages.warning(request,'Email is Already Taken') return redirect('add_student') if CustomUser.objects.filter(username=username).exists(): messages.warning(request, 'UserName is Already Taken') return redirect('add_student') else: user = CustomUser( first_name = first_name, last_name = last_name, username = username, email = email, profile_pic = profile_pic, user_type = 3 ) user.set_password(password) user.save() course = Course.objects.get(id=course_id) session_year = Session_Year.objects.get(id=session_year_id) student = Student( admin = user, address = address, … -
django disable button until file is uploaded
I would like to disable my button until a file is uploaded, how can I do this? my html code {% extends 'base.html' %} {% block content %} <center> <h1>Upload your file</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label class="custom-file-upload"> <input type="file" name="document"><br/> </label> <button class="button button1" type="submit">Upload file</button> </form> {% if url %} <p>Uploaded file: <a href="{{ url }}">{{ url }}</a></p> {% endif %} {{ return_value }} </center> {% endblock %} -
Fetching data from local storage and save it in sqlite 3 using django
Am trying to fetch data from local storage and save it in SQlite3 but i dont know what to do.....anyone with an idea please by use of python django I dont know where to start anyone with idea please -
Django Graphene return data from multiple models under the same nest
I am trying to use Python Graphene GraphQL to implement a search endpoint return all products based on name. However, in my database I have three product tables that respectfully contains different product types - Cards, Tokens, Sealed Products. I want to return the data under a single nest in the Json response. The relay connection I am using is from https://github.com/saltycrane/graphene-relay-pagination-example/blob/artsy-example/README.md. Something along the lines of: Code: class MagicCards(DjangoObjectType): id = graphene.ID(source='pk', required=True) mana_cost_list = graphene.List(graphene.String) class Meta: model = magic_sets_cards interfaces = (relay.Node,) filter_fields = {'name': ['icontains']} connection_class = ArtsyConnection class MagicTokens(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = magic_sets_tokens interfaces = (relay.Node,) filter_fields = {'name': ['icontains']} connection_class = ArtsyConnection class SearchQuery(ObjectType): magic_cards = ArtsyConnectionField(MagicCards) magic_tokens = ArtsyConnectionField(MagicTokens) # pseudo code: all_products = combine(magic_cards, magic_tokens) @staticmethod def resolve_all_products(self, info, **kwargs): return @staticmethod def resolve_magic_cards(self, info, **kwargs): sql_number_to_int = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" excluded_sides = ['b', 'c', 'd', 'e'] return magic_sets_cards.objects.exclude(side__in=excluded_sides).extra(select={'int': sql_number_to_int}).order_by('-set_id__release_date', 'set_id__name', 'int', 'number').all() @staticmethod def resolve_magic_tokens(self, info, **kwargs): sql_number_to_int = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" excluded_sides = ['b', 'c', 'd', 'e'] return magic_sets_tokens.objects.exclude(side__in=excluded_sides).extra(select={'int': sql_number_to_int}).order_by('-set_id__release_date', 'set_id__name', 'int', 'number').all() searchSchema = graphene.Schema(query=SearchQuery) Query: { allProducts(name_Icontains: "Spellbook", first: 12, after: "") { pageCursors { previous { cursor } first { … -
Django Directory was not same in VSCode
from django.utils.translation import ugettext_lazy I got problem in this line for last 2 hours I try every method but failed, but when I checked the directory of django.utils.translation is someone else and directory of ugettext_lazy has someone else meanwhile django.utils.translation search ugettext_lazy in C:\Users\admin\AppData\Local\Programs\Python\Python310\Lib\site-packages\django\utils\translation_init_.py but the ugettext_lazy directory has in C:\Users\admin\.vscode\extensions\ms-python.python-2022.4.0\pythonFiles\lib\jedilsp\jedi\third_party\django-stubs\django-stubs\utils_init_.py How to make it same directory -
How to create a model in django that is not linked to any table in database mysql?
I have a table in firestore, and I try to create model from firestore database using firebase-orm and use admin.register(modelFireStore) in Admin django but it seems Django doesn't support register modelFirstore in admin. I need to create a model without linking to any table in mysql and I can override django's CRUD to CRUD table in firestore. Is this possible -
'Q' object has no attribute 'append'
def fetch_all_shifts_by_entity_airport(entity, airport, department): query=Q(entity=entity, airport=airport, is_delete=0) if department: query=Q(department=department,entity=entity, airport=airport, is_delete=0) return list(ShiftMaster.objects.filter(query).values()) Instead of that, how do I append above entity airport to department query I was trying this, if department: query.append(Q(department=department)) Shift_master=ShiftMaster.objects.filter(reduce(operator.and_, query, Q())) Shift_master_values= Shift_master.values() return Shift_master_values #list(ShiftMaster.objects.filter(query).values()) It gives me 'Q' object has no attribute 'append' -
debuggin drf in vscode, breakpoint not working at serializer create method
I have a nested serializer with custom create, update method. I've put multiple break points in the create method to see how things work when a Post request is made. Maybe I'm new to vscode but does the debugging work with post request? Like does it trace my localhost post method to the api? Since it never reaches the create method breakpoint I'm suspecting im doing something wrong, am new to vscode. -
How to display error message if SQL query display 0 results in django
how do i display the error message for 'ratenotfound' if my sql query for 'check' returns nothing. def rate_success(request): if request.method == "POST": error={} rater = request.session['your-email'] being_rated = request.POST['rate-email'] score = request.POST['rating'] check = "SELECT * FROM users WHERE your_email = '" + being_rated + "';" c = connection.cursor() c.execute(check) if being_rated == rater: error['rateyourself'] = 'You cannot rate yourself' return render(request, 'ratings.html', error) if check == '': error['ratenotfound'] = 'The email of the person you are trying to rate is not found in our database' return render(request, 'ratings.html', error) return render(request, 'rate success.html') Basically i am trying to display the error message when someone try to rate an invalid email that is not in the database. -
Generalize search criterion django and drf
I have ListView where i display some results on my website and i have search parameter which gives the result based on title and number here i should ignore the exact spelling and show the results for both i.e search criterion to be able to ignore "." "et al." and similar terms so that when searching titles the name doesn't have to be exact. I.E. "Toaster v fridge" will still bring up "Toaster, et al. v. Fridge" class MyListAPIView(ListAPIView): def get_filters(self, request): filters = [] id_list = request.query_params.getlist('id[]', []) if id_list: filters.append(Q(id__in=id_list)) return filters search = request.query_params.get('search', '') if search: filters.append(Q(c_number__icontains=search) | Q(title__icontains=search)) return filters -
How to have a different models.ForeignKey related_name for each linked objects of same model?
I’m working with Django Rest to have multiple “text block” objects linked with the document object. I’ve accomplished this with a simple models.ForeignKey feature so far. However, I’m rendering all of these text blocks in multiple columns in the front end. Since each block will always stay in certain columns, I figured the easiest way is to let DRF return something like the following: { "name": "Comparing Two Characters", "column_A": [ { "title": "Text Block", "body": "lorem ipsum blah blah" } ], "column_B": [ { "title": "Text Block 2", "body": "lorem ipsum blah blah" }, { "title": "Text Block 3", "body": "lorem ipsum blah blah" } ] } How would I be able to implement something like this? I’m not sure if using related fields is even ideal for such cases. I would appreciate any help! Here’s my current models.py code for reference: class Document(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) # other fields def __str__(self): return self.name class TextBlock(models.Model): id = models.AutoField(primary_key=True) document = models.ForeignKey(Document, related_name='blocks', on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.CharField(max_length=100) -
Django student here: I'm I getting a ValueError when creating a superuser using a custom made User class
I am working on a project that requires one to only create an account if their other details such as username are already in the database. For this I created a custom user class named Account and linked the username field through a OneToOne relationship to the Reg No in the Student class. I manually prepopulated the database with a single record so as to be able to create a superuser, because the creation of an account would require an existing Student record. But I am getting a value error on the terminal like so: (djangoenv) myMachine:~/Django9/eschool$ python3 manage.py createsuperuser Email: ********@**.me Username (Student.School_ID): 1 Password: Password (again): Traceback (most recent call last): File "/home/biketi21/Django9/eschool/manage.py", line 22, in <module> main() File "/home/biketi21/Django9/eschool/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 157, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 310, in __set__ super().__set__(instance, value) File "/home/biketi21/anaconda3/envs/djangoenv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__ raise … -
raise UnrecognizedImageError docx.image.exceptions.UnrecognizedImageError
` ` if pattern.search(para.text): if para.text.find(str("#i.aadhaarfront_image|height:200|width:200")) > -1: para._element.clear_content() path = f"media/images/{(self.userdetails).email.split('@')[0]}/{self.adharfront}" para.add_run().add_picture(path, width=Inches(6.5), height=Inches(5)) elif para.text.find(str("#i.aadhaarback_image|height:200|width:200")) > -1: para._element.clear_content() path = f"media/images/{(self.userdetails).email.split('@')[0]}/{self.adharback}" para.add_run().add_picture(path, width=Inches(6.5), height=Inches(5)) elif para.text.find(str("#i.pan_image|height:200|width:200")) > -1: para._element.clear_content() path = f"media/images/{(self.userdetails).email.split('@')[0]}/{self.panimage}" para.add_run().add_picture(path, width=Inches(6.5), height=Inches(5)) self.document.save("kyc_edited.docx")` ` how to solve this type of error while updating image in documents with help of module DOCX ,in the function add_picture. raise UnrecognizedImageError docx.image.exceptions.UnrecognizedImageError -
In this image we are using transaction.atomic and i wanna know what is ( F ) in line 44
In this image we are using transaction.atomic and i wanna know what is ( F ) in line 44 -
Update method does not support writable dotted source error when updating user profile
Getting the error The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `signup.serializers.UpdateUserSerializer`, or set `read_only=True` on dotted-source serializer fields. I would like to enable users to update their profile info. I extended the custom user class in my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() here is my urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) and my serializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city') country = serializers.CharField(source='profile.country') class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name','city','country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) … -
I'm trying to set geo coordinates through address using mapquest. but it give me an error[ django.contrib.gis.gdal.error.GDALException: OGR failure. ]
I'm trying to set geo coordinates through address using mapquest, gdal, gis. but it give me an error. I never used gdal and gis so i can't figue out the problem but i think there is problem on models.py. please help me to figue out the [OGR failure] error Any help would be appreciated! - Let me know if I should update this question with my settings.py or other relevant files. Here is me Logs. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/job/job/add/ Django Version: 4.0.3 Python Version: 3.10.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django_filters', 'job.apps.JobConfig', 'django.contrib.gis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\Django\Jobbee\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Django\Jobbee\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\sites.py", line 242, in inner return view(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\options.py", line 1885, in add_view return self.changeform_view(request, None, form_url, extra_context) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 133, … -
File download using React Django? able to download file but content is missing getting file correpted error
Backend @api_view(['POST']) def download_attachment(request): body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) file_name = body_data['file_name'] migration_typeid = body_data['migration_typeid'] attach_type = body_data['AttachmentType'] object_type = body_data['object_type'] featurename = body_data['fname'] fid = body_data['feature_id'] filter_files = Attachments.objects.filter( Feature_Id=fid, AttachmentType=attach_type, filename=file_name) filter_values = list(filter_files.values_list()) file_path = filter_values[0] fl = open(file_path[4], 'rb') mime_type, _ = mimetypes.guess_type(file_path[4]) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % file_name return response Frontend(React) const handleDownload = (att_Type, migtypeid, id, obj_type, att_name, fid) => { let body = { file_name: att_name, migration_typeid: migtypeid, object_type: obj_type, AttachmentType: att_Type, id: id, fname: detaildata.Feature_Name, feature_id: fid, responseType: "blob", }; let conf = { headers: { Authorization: "Bearer " + config.ACCESS_TOKEN(), "Content-Type": "application/json", }, }; // console.log(conf.headers); axios .post(`${config.API_BASE_URL()}/api/download_att`, body, conf) .then((res) => { fileDownload(res.data, att_name); }) .catch((err) => { }); }; i am able to download the file but content is not coming in the file for txt files it is working but other than txt not supporting getting corrupted error can you anyone tell me the solution how it works? -
'bool' object has no attribute 'id',how can i fix this error in my django project [closed]
@api_view(['POST']) @permission_classes((permissions.AllowAny,)) def login(req): email = req.data.get('email') username = req.data.get('username') password = req.data.get('password') user = TokenObtainPairSerializer( data=req.data).is_valid(raise_exception=True) if user is not None: try: token = RefreshToken.for_user(user) print(token, "Token") except Exception as e: return Response({'message': "Login Failed " + str(e)}) else: pass return Response({'message': "Login Successful"}) I was trying to make a custom simple jwt authentication with rest_framework_simplejwt but getting the error "'bool' object has no attribute 'id',can anyone explain me why this is happenning.