Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Developing queryset using related models
I've got two models. Event and Usercart. class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Event(models.Model): order = models.ForeignKey(UserCart, on_delete=models.CASCADE, null=True, blank=True) start_time = models.DateTimeField() I'd like to develop a queryset of UserCart instances where there is a related event that is in the past (based on that event's start time) pastcarts = UserCart.objects.filter(????) Thanks for your help! -
Use seperate login with django jwt and vuejs
at the moment my django login view return a vuejs site with the login and the full app. The login form sends request with axios to my django obtain token url and check if the response is correct. Than my vue router let me into the app. I would like to seperate the login to my web app. For example this is the login scenario that i want: Django return a normal html page with a login form After submit the form, the django view looks if the data correct, generate the tokens and check if the user is an employee or an employer (this my two user types) If the user an employee return vuejs page 1 and if there an employer return vuejs page 2 And at this point i have a problem. I don't know how i can return and store the access and refresh jwt token with the vuejs page 1 or 2 in the same response. At the moment i store them in vuex. This is simple because the vuejs page make the login request to the server. But if the login not a part of the vuejs app it is tricky. My idea is … -
Query to get total in django
I need to find user_id with maximum fat_intake (overall fat_intake). Database: id | user_id | fat_intake 38 1 10 39 1 15 40 1 30 41 1 14 42 2 20 43 2 30 44 2 50 What will be the query to get user_id with the maximum fat intake ? The Response should be : Output: { "user_id": 1, "total_fat_count": 46 } -
Index defined on abstract class incorrectly included in migration on concrete child of concrete child
To illustrate the issue I'm facing I'll use the following example. Let's say I have the following model hierarchy in my application: class Key(models.Model): pass class AbstractThing(models.model): key = models.ForeignKey(Key) class Meta: abstract = True indexes = [ models.Index(fields=['key']) ] class Thing(AbstractThing): pass class ChildOfThing(Thing): pass Now, since I've defined an index on the abstract AbstractThing model, I would expect all inherited models' table to have the key index as well, but not if I inherit further from one of these, since they will not contain the column. When I create the migrations however, I can see that an index is added on the non-existent ChildOfThing.key column, which of course, does not exist. Since Thing is a concrete class, the key column is contained there. The migration file is generated as follows: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Key', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Thing', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='ChildOfThing', fields=[ ('thing_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='things.Thing')), ], options={ 'abstract': False, }, bases=('things.thing',), ), migrations.AddField( model_name='thing', name='key', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='things.Key'), ), migrations.AddIndex( model_name='thing', index=models.Index(fields=['key'], name='things_thin_key_id_acfd46_idx'), ), migrations.AddIndex( model_name='childofthing', … -
How to balance the investment testing in Django (TDD)
I understand all the advantages of writing tests for your code. But writing tests takes time and time is (client) money. I try to find a good 'return on investment' for writing tests. In other words a balance between: Testing everything. For example: in examples I see people testing that verbose_name equals plural. I think this is too much. If I've put the code in the Model Meta options, it is there to stay and I can't see why it would ever break. Testing only the URL's. Test all the URL's in the applications. For example: response = self.client.get('/example/create)) self.assertEqual(response.status_code, 200) I think that this way the common reasons of breaking code will be covered. But on the other hand I've the idea that this is too little. Does anyone have a 'best practice' that is balanced? Thanks in advance -
AttributeError: 'DeferredAttribute' object has no attribute 'copy'
I'm trying to create a widget that calls from my model, "DPRLog" but I'm having a hard time implementing it in my forms. Here is my forms.py: from django import forms from profiles.models import User from .models import DPRLog class DateInput (forms.DateInput): input_type = 'date' class Datefield (forms.Form): date_field=forms.DateField(widget=DateInput) class dprform(forms.Form): class Meta: model = DPRLog widgets = {'date_field':DateInput(DPRLog.reportDate)} fields = ('login','logout',) Model.py: class DPRLog(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) reportDate = models.DateField(blank=False,null=False) login = models.TimeField(blank=False, null= False) logout = models.TimeField(blank=False, null= False) def __str__(self): return f'{self.user.full_name} DPR Log' -
I want to convert text to speech in python
(base) C:\Users\LENOVO>pip install gTTS WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. ERROR: Exception: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 258, in run isolated_mode=options.isolated_mode, File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 549, in site_packages_writable test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "C:\Users\LENOVO\AppData\Roaming\Python\Python37\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'C:\Program Files\Anaconda3\Lib\site-packages\accesstest_deleteme_fishfingers_custard_tzerxu' I got this error...How to fix that? -
How to add two render in Django function views
How to add two render in single function based views. I don't know this can be done, if not please provide the alternative way of doing this. views.py def success(request): return render(request, "tools/loading.html", {}) #Raspberry pi code print("on") pin13.write(1) time.sleep(2) print("off") pin13.write(0) return render(request, "tools/booked.html", {}) Currently it won't run the raspberry pi code, it directly returns the page and skip the rest of the code down the first render. But I need to update this code so that when calling this 'success' function based view it should return the 'loading.html', after performing the Raspberry pi code it should return another page. All this should be done in backend. -
HOW TO PASS AN ID INTO THE TEMPLATE
Here is the view.py file that have a function to create a child record,and it work fine def add_child(request): form=ChildForm(request.POST) if form.is_valid(): form.save() return redirect('/child/child') else: form= ChildForm() context= { 'form':form } return render(request,'functionality/add_child.html',context) And here is models.py file by which have child details,this model it have relationship with academic model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Religion = models.CharField(max_length = 50) Date_of_birth = models.DateField() Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname This is academy models which have relationship with child_detail models from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Date = models.DateField() Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return self.Class In views.py I have this function that show child details and academy details with respective id, and everything working as fine def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) test = Clinical_test.objects.filter(child=child) result = Result.objects.filter(child=child) immunisation = Immunisation.objects.filter(child=child) medical = Medical_report.objects.filter(child=child) parent = Parent.objects.filter(child=child) academic = Academic.objects.filter(Student_name=child) context={ 'child':child, 'test':test, 'result':result, 'immunisation':immunisation, 'medical':medical, 'parent':parent, 'academic':academic, } return render(request,'functionality/more/more.html',context) After a user creating a child details,therefore he/she … -
Django text formatting in template
I am trying to format text rendered from database in django template. #models.py class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') text = models.TextField('Question', max_length=1500) def __str__(self): return self.text the text what i am entering in the text field is like a=50 b=30 c=a*b Now When I am calling this value in the template like. #template.html <p>{{ question.text }}</p> the text is printing like below in the template a=50 b=30 c=a*b I want the text to be formatted with line breaks while calling the values in template a=50 b=30 c=a*b -
Posting Objects with Pre-Existing Nested Objects in Django Rest Framework
I am working on some code that interacts with my site's API, but having some issues with Django Rest Framework. I am trying to send a post request to the server to create a new character, based on the model, serializer, and viewset below. ####################Serializer#################################### class CharacterSerializer(serializers.HyperlinkedModelSerializer): relatedTo = PlayerSerializer(); class Meta: model = Character fields = '__all__' #####################################Model############################################# class Character(models.Model): characterID = models.CharField(max_length=500); lastLogin = models.DateTimeField(); relatedTo = models.ForeignKey(Player, on_delete=models.CASCADE) shouldRun = models.BooleanField(default=True, null=True, blank=True); def __str__(self): return self.relatedTo.name + ": " + self.characterID; def save(self, *args, **kwargs): if self.relatedTo.lastLogin != None: self.relatedTo.lastLogin = self.lastLogin; else: if self.lastLogin > self.relatedTo.lastLogin: self.relatedTo.lastLogin = self.lastLogin; self.shouldRun = True; else: self.shouldRun = False; super().save(*args, **kwargs) ######################################ViewSet######################################## class CharacterViewSet(viewsets.ModelViewSet): queryset = Character.objects.all() serializer_class = CharacterSerializer def get_queryset(self): queryset = Character.objects.all(); shouldRun = self.request.query_params.get('shouldRun', None) charID = self.request.query_params.get('charID', None) name = self.request.query_params.get('name', None) if charID is not None: queryset = queryset.filter(characterID=charID); if shouldRun is not None: queryset = queryset.filter(shouldRun=shouldRun); if name is not None: queryset = queryset.filter(relatedTo__name=name); return queryset; The issue lies in the fact that I must include the Player object that a character is linked to while posting the object. I've included the Player information below as well. ####################Serializer#################################### class PlayerSerializer(serializers.HyperlinkedModelSerializer): class … -
Django perpetual 404s when visiting project directory URL
I have a very strange problem with Django and OLS. I am using the OpenLitespeed Django one click install droplet on Digital Ocean. In both my custom app and the example app in the droplet, if I visit a URL that matches the django project directory (in the example app, this is /demo/), then any subsequent page visits give a 404 error, no matter what URL you do. To reproduce, I've spun up a completely clean install of the droplet, then do the following steps: Go to / -> see "Hello world!" as expected Go to /demo/ -> also see "Hello world!" even though this should be a 404, as this URL is not specified in the urls.py or anywhere else Go back to / -> 404! It seems to be looking for /demo/demo/ which doesn't exist Trying any other URL also results in a 404. The only way to get back to the normal behavior is to restart the OLS process. Everything then functions as expected unless any URL that starts with the project directory name is visited, in which case the whole thing crashes and returns 404s again. Any help that can be provided to try and further … -
Django file read error - Filename must be 1-8 alphanumeric characters
I am trying to temporary save a file in the os and read it to convert it into ZPL format. It is working fine in jupyter notebook but when I tried to run the same in Django function it is showing the following error: zplgrf.GRFException: Filename must be 1-8 alphanumeric characters Views.py for i in items: barcode = get_barcode(value=i, width=600) a = barcode.save(formats=['PNG'], fnRoot=i) print("a ",a) with open(a, 'rb') as image: grf = GRF.from_image(image.read(), str(i)) grf.optimise_barcodes() print(grf.to_zpl()) os.remove(a) zpl = grf.to_zpl() where items = ['YNT929951321', 'YNT929951322', 'YNT929951323', 'YNT929951324'] How can I resolve this ? -
Sending Payouts in django
Hello i am working on a 3d-model selling platform. I would like to add payout functionality without using Paypal. Anyone with an idea of a workaround; kindly advice. -
How can I submit 3 forms in tabs by click of one button in django?
I have 3 forms, first one collects user's personal information, second collects users educational information and the third one has a submit button along with checkbox. My forms.py class PersonalInfoForm(ModelForm): CHOICES = [('female','female'),('male','male')] enrolment = forms.IntegerField(widget=forms.HiddenInput) date_of_birth = forms.DateField(widget=DateInput) gender = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect) class Meta: model = Personal_Info fields = [ 'enrolment', 'first_name', 'middle_name', 'last_name', 'date_of_birth', 'gender', 'address' ] class EducationalInfoForm(ModelForm): username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Educational_Info fields = [ 'ssc_marks', 'ssc_percentage', 'ssc_board', 'hsc_marks', 'hsc_percentage', 'hsc_board', 'college_name', 'university', 'semester' ] class AgreeInfoForm(ModelForm): agree = forms.BooleanField() username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Agree_Info fields = [ 'agree' ] template named 'eligible-scholarships.html' <div class="row"> <div class="col-lg-12"> <div class="card"> <!-- open the below card body for the from --> <div class="card-body"> <h4 class="header-title mb-3"></h4> <ul class="nav nav-tabs nav-bordered nav-justified" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="personal-tab-b2" data-toggle="tab" href="#personal-b2" role="tab" aria-controls="personal-b2" aria-selected="true"> <span class="d-block d-sm-none"><i class="fa fa-personal"></i></span> <span class="d-none d-sm-block">Personal</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="educational-tab-b2" data-toggle="tab" href="#educational-b2" role="tab" aria-controls="educational-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-educational"></i></span> <span class="d-none d-sm-block">Educational</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="complete-tab-b2" data-toggle="tab" href="#complete-b2" role="tab" aria-controls="complete-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-complete"></i></span> <span class="d-none d-sm-block">Complete</span> </a> </li> </ul> <div class="tab-content"> <div class="tab-pane show active" id="personal-b2" role="tabpanel" aria-labelledby="personal-tab-b2"> … -
Query to get maximum x in django
My database: id | user_id | fat_intake | item_id 38 1 10 12 39 1 15 11 40 1 30 10 41 1 14 13 42 2 20 11 43 2 30 10 44 2 50 13 What will be the query to get user_id with the maximum fat intake till, i.e the response should be : Output: - Response Code: 200 - { "user_id": 1, "total_fat_count": 46 } -
Error runnning django channels server on localhost
I am following along on this tutorial: https://codyparker.com/django-channels-with-react/2/ and am getting this strange error: File "~/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 83, in inner_run ws_protocols=getattr(settings, 'CHANNELS_WS_PROTOCOLS', None), TypeError: init() got an unexpected keyword argument 'channel_layer' I am a total beginner with django and channels, and have no idea what could be causing the issue. The command I am running is: python3 manage.py runserver 8080 I am using the same versions of django and channels as the tutorial, channels 0.17.2 and django 1.9 Thank you for your help! -
How to map docker connect's to localhost to machine's localhost
I have a Django project which needs to be containerized for deployment. Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev gcc -y COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /eitan_app WORKDIR /eitan_app COPY . /eitan_app EXPOSE 8000 RUN python manage.py makemigrations RUN python manage.py migrate # RUN python manage.py runserver 127.0.0.1:8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I am able to create an image with the command docker build . and then docker run <image id> to run Django application. Once I run this image I get this output - System check identified no issues (0 silenced). March 17, 2020 - 05:40:04 Django version 3.0, using settings 'eitan.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. We can see the Django application has started perfectly fine inside the container but I am not able to access it from my machine's 127.0.0.1:8000. -
How to autodeploy Django in EC2 and React in S3
I have an app created in Django and React, but there are few problems that I am facing :- As I will have a large database(postgres) exclusily for a single user, I am creating different AWS EC2 instance for every user. Whenever there is a new user then I have to go and manually install postgres, setup nginx and other important things and this is just for Django in EC2. Then I setup ReactJS frontend in Amazon S3. How can i automate this so that when a paid user signs up, everything happens automatically. The following should happen automatically: - Automatically create a new EC2 instance, and deploy backend (This including installing several libraries, Postgres, Redis, async task queue (We use Huey which is like Celery), making migrations and other trivial stuff) - Automatically make an S3 bucket and deploy frontend for the user. We will have to setup domains .etc for this. Would like to know your inputs on how to approach this problem. -
django throws 'Direct assignment to the forward side of a many-to-many set is prohibited
while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my models class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Meta: ordering=('user_name',) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.DurationField() status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) #Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') User_Id=models.CharField(max_length=10,blank=True,null=True) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) class Meta: ordering=('Host',) while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my viewset class SessionViewSet(viewsets.ViewSet): def create(self, request): try: Host= request.data.get('Host') Sport = request.data.get('Sport') … -
How to used python filter json string based on key that given in array form?
I have below json string: a={"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "7":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "6":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"0A", } } } ], } The key from above json string get by a.keys() is: dict_keys(['44', '49', '7']) How to filter the a so that it remain the key of 44 and 49 only if the array given is ['44', '49'], below is my expected output: {"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], } -
Can you please guide me to implement Dual Factor Authentication in Django?
I am currently working on a scenario where a user after login has the option to switch to private mode by means of flipping a switch button. Whenever a user logs in and then switches on to private mode for the first time, then the user must be verified by dual factor authentication once and then he can switch back and forth between private and public mode, without triggering 2FA Authentication every subsequent time when he switches to private mode till he logs out. That is the 2FA must be triggered every first time per session when a user switches to private mode. Can you please provide some suggestions or ideas on how to implement this functionality? I am not clear on how to implement this. I have tried reading documentations and feel that a concise approach would be better. Please do suggest. -
Using commas to separate large numbers in Django FloatField
I'm setting up an app with Django and I need to show large numbers (sometimes many billions) on my home page. Right now I have set up my model with a classic: required_number = models.FloatField() Which yields me a number similar to 126645602100.0. Naturally I find this very hard to read, and it becomes really problematic to compare this number to another one which would be in the order of millions instead of billions. Would there be a way to format this number in order to get something like 126,645,602,100 or even 126'645'602'100? I'm thinking maybe FloatField is not adequate, or maybe the answer lies in my html treatment of this variable. Thank you very much for your help! -
FileField PDF Won't Open Django
I am creating and saving a PDF as such in my views: views.py @login_required(login_url="/login") def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: ... elif 'save' in request.POST: pdf_contents = form file = ContentFile(pdf_contents) item = PackingListDocuments.objects.get(pk=1) item.PackingListDocument.save('test.pdf', file) #saving as FileField in model form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') I see that the test.pdf is saved. I can see it in my file explorer as well as in the admin, but every time that I attempt to open it, the file seems to be corrupted. What do I need to add or subtract in my code to get this working? Thanks! -
Django without Page Refresh using AJAX
When the teacher update the student behavior, There is a pop up message "Update Success", in my case when the teacher update the student behavior the page is appear blank this is the source https://www.youtube.com/watch?v=KgnPSmrQrXI <form method="POST" id="DogForm" action="/Updatestudentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="text" value="{{teacher}}" name="teacher" id="teacher"> {% for students in student %} <tr> <td colspan="2"><input type="hidden" value="{{students.id}}" >{{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname}} {{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname}}</td> {% for corevalues in studentsbehaviorgrade %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="id" id="student"> <select name="Marking" id="marking"> <option value="{{corevalues.Marking.id}}" >{{corevalues.Marking.id}}-{{corevalues.Marking.Marking}}</option> {% for behaviors in behavior %} <option value="{{behaviors.id}}">{{behaviors.id}}-{{behaviors.Marking}}</option> {% endfor %} </select> </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Update"> </form> this is my script <script type="text/javascript"> $(document).on('submit', '#DogForm', function(e)){ e.preventDefault(); $.ajax({ type:'POST', url:'/Updatestudentbehavior/' data:{ teacher:$('#teacher').val(), student:$('#student').val(), marking:$('#marking').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, succes:function(){ alert('Update Success'); } }) } </script> my views.py def Updatestudentbehavior(request): ..... return HttpResponse('') urls.py path('Updatestudentbehavior/', Homepage.views.Updatestudentbehavior, name='Updatestudentbehavior'),