Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : insert form data to the sessions to hold the data values without import models or forms
So here are my approach where I wanted to add the information from the user to add those values to my screening and vetting form but the form has multiple steps that are processing while he giving the information. The problem is I didn't see that form data on my server. Can someone guide me through this? here is my code: views.py page def personalData(request): if request.method == 'POST': g = request.POST['gender'] s = request.POST['salutation'] fN = request.POST['forename'] midName = request.POST['midname'] midName1 = request.POST['middleName1'] midName2 = request.POST['middleName2'] midName3 = request.POST['middleName3'] surN = request.POST['surname'] bir = request.POST['birthday'] visa = request.POST['work-visa'] nation = request.POST['nation'] biometric = request.POST['Biometric-ID'] visa_ex = request.POST['visa-expireDate'] nation_o = request.POST['nation-o'] passport = request.POST['passport'] passport_N = request.POST['passport-number'] passport_I = request.POST['passport-Issue'] passport_E = request.POST['passport-Expire'] country = request.POST['country'] birth_op = request.POST['birth-certification-o'] birth_ID = request.POST['birth-certificate-ID'] dri_op = request.POST['dri-type'] drive_op = request.POST['drive-lic-type'] veh_Id = request.POST['driving-licence-Id'] veh_Issue = request.POST['veh-issue-date'] veh_ex = request.POST['veh-expiry-date'] veh_detail = request.POST['vehicle-detail'] nation_op = request.POST['insurance-o'] nation_insure = request.POST['National-Insurance-NO.'] m_status = request.POST['marital-status'] dependent = request.POST['d-quantity'] disability = request.POST['disability'] # Sessions ses = [ {'gender': g, 'initial': s, 'forename': fN, 'middleName1': midName1, 'middleName2': midName2, 'middleName3': midName3, 'surname': surN, 'birthday': bir, 'Visa': visa, 'Nation': nation, 'biometric': biometric, 'visaExpire': visa_ex, 'where': nation_o, 'passportNum': passport_N, 'passportIssue': passport_I, … -
how to make 2 step approval system django?
I was trying to make a 2 step approval system in Django project where if a student applies for a leave it should be approved/rejected by the teacher (step 1) if rejected then admin won't be able to see the application if approved by the teacher then only the approvals approved by teachers will be shown in admin for final approval (step2) Now Admin can see the teachers and students leave then approve or reject it Please help -
models.py", line 287, in __init__ raise ValueError('ModelForm has no model class specified.') ValueError: ModelForm has no model class specified
class PostForm(forms.ModelForm): def init(self, *arg, **kwargs): super(PostForm, self).init(*arg, **kwargs) self.helper = FormHelper self.helper.add_input(Submit( 'post','Post', css_class='btn-primary')) self.helper.form_method = 'POST' class Meta: fields = ('__all__') ///////////////////////////////////////// if I remove def init_ function I am getting another error. Please check my https://github.com/m0nst3rm3/Instaclone link and help me get over this problem -
Hide columns of table on smaller screens breaking format of table
I have a table that is quite large and I would like to hide columns based on screen size. However when I add class="d-none d-xl-block" to my column header it breaks the formatting of the table when using xl wide screens. code: <table class="table table-hover table-sm"> <thead> <tr class=""> <th scope="col" class="">ID</th> <th scope="col" class="">Set Code</th> <th scope="col" class="">Set Name</th> <th scope="col" class="d-none d-xl-block">Set Type</th> <th scope="col" class="text-right">Release Date</th> <th scope="col" class="text-right d-none d-xl-block">Card Count</th> <th scope="col" class="text-right d-none d-xl-block">Digital Only</th> <th scope="col" class="text-right d-none d-xl-block">Foil Only</th> <th scope="col" class="text-right d-none d-xl-block">Nonfoil Only</th> <th scope="col" class="" style="text-align:center">Status</th> </tr> </thead> <tbody> {% for set in Sets %} <tr class=""> <th>{{ set.id }}</th> <td>{{ set.code }}</td> <td>{{ set.name }}</td> <td>{{ set.set_type }}</td> <td>{{ set.release_date }}</td> <td>{{ set.card_count }}</td> <td>{% if set.digital_only %} <span style="color: green">&#x2714;</span> {% endif %}</td> <td>{% if set.foil_only %} <span style="color: green">&#x2714;</span> {% endif %} </td> <td>{% if set.nonfoil_only %} <span style="color: green">&#x2714;</span> {% endif %} </td> <td>{% if set.status %} <label class="switch"><input type="checkbox"><span class="slider round"></span></label> {% else %} <label class="switch"><input type="checkbox"><span class="slider round"></span></label> {% endif %}</td> </tr> {% endfor %} </tbody> </table> Screenshot: -
Django signup: set username to provided email address and save?
Short question (no actual need to read the rest): I have read multiple threads/tutorials (e.g. this one) on how to let users login via email. And I was wondering: why can't I just keep things simple and ask for an email address upon signup and then set the username to that email address and save the user? Long part: I would create a form that is very similar to the UserCreationForm of Django 1.8. I'm not sure why I cannot find the same code for 3.1 (which makes me wonder even more whether my idea might be bad practice for some reason) but basically I would do this: create a ModelForm for the default user model, set fields = ["email"], render it manually as {{form.email}} in the template and then, in the view, I'll call form.save(commit=False) to get the object, set the username of that object to the given email address and save it. Orrrr don't I? :-) -
How to call Django restful api endpoint [closed]
I have an a Django endpoint http://127.0.0.1:8000/app/ and I want to call this endpoint and do something with it. How do I call the endpoint..? Your answers are highly appreciated. Here is My app model.py file class MyVideo(models.Model): name= models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to='videos/%Y/%m/%d/', null=True, verbose_name="") # mod = models.FilePathField def __str__(self): return self.name + ": " + str(self.videofile) Here is my View.py file class MyVideoView(viewsets.ModelViewSet): queryset = MyVideo.objects.all() serializer_class = MyVideoSerializer Here is my serializer.py file class MyVideoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyVideo fields = fields = ['id', 'url', 'name', 'created', 'videofile'] Here is my app urls.py file from django.urls import path, include from .views import MyVideoView from rest_framework import routers router = routers.DefaultRouter() router.register(r'app', MyVideoView) urlpatterns = [ path('', include(router.urls)), ] -
why couldn't I find the python module uwsgi after pip install uwsgi?
After I have installed the uwsgi, I add the following code: import uwsgi But the IDE is warning that uwsgi module not exist. the command I used to install the uwsgi is: pip install uwsgi the installed uwsgi package is: pip freeze | grep -i uwsgi uWSGI==2.0.19.1 but in the site-packages dir there is not any uwsgi subdir. -
Nginx directory forbidden 403 django
I am trying to deploy django in centos 8 . I am getting 403 directory forbidden error. I have applied chmod 755 var/www/ still i am getting this error I have also applied sudo chown myusername:psaserv /var/www/vhosts/aaa.com but still i am getting this error . This is the error i am getting inside the server logs 2020/10/22 08:15:14 [error] 78481#0: *398 directory index of "/var/www/vhosts/aaa.com/httpdocs/djangoProject/" is forbidden, client: 162.158.167.71, server: aaa.com, request: "GET / HTTP/1.1", host: "aaa.com" this is my nginx configuration file #user nginx; worker_processes 1; #error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; #pid /var/run/nginx.pid; include /etc/nginx/modules.conf.d/*.conf; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #tcp_nodelay on; #gzip on; #gzip_disable "MSIE [1-6]\.(?!.*SV1)"; server_tokens off; include /etc/nginx/conf.d/*.conf; } # override global parameters e.g. worker_rlimit_nofile include /etc/nginx/*global_params; -
I want use snippets in terminal
I wrote "makemigrations": { "prefix": "makemigrations", "body": [ "python manage.py makemigrations", " ${1:pass}" ], "description": "makemigrations" }, and,I've tried makemigrations in terminal,but this didin't work. please tell me how to solve it. -
Django - How to download the byta data in csv file format
I am new to Django, I am developing an application where the BA will upload the CSV data into the database during the requirement phase and the tester need to download the CSV file and compare the source and target results in system testing. I am able to upload the file to the table. However, Not able to download the same from the PostgresSQL database which is stored in the drawing_data field.(field type bytea) My ask is: I would like to download the file data which is stored in drawing_data. Thanks in advance Attaching my code. Could you please help me with this.. I am not able to download the file. from HTML 1 -DataBase: postgreSQL 2- Table Name: prj_details 3- model name: prj_details 4- filed/column details: file_extension = models.CharField(max_length=500) drawing_data = models.BinaryField() class Meta: db_table = 'prj_details' View.py: def download(request, drawing_data): # this url is for download try: obj = prj_details.objects.get(drawing_data) except prj_details.DoesNotExist as exc: return JsonResponse({'status_message': 'No Resource Found'}) get_binary = obj.csv if get_binary is None: return JsonResponse({'status_message': 'Resource does not contian csv'}) if isinstance(get_binary, memoryview): binary_io = io.BytesIO(get_binary.tobytes()) else: binary_io = io.BytesIO(get_binary) response = FileResponse(binary_io) response['Content-Type'] = 'application/x-binary' response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format( drawing_data) return response url.py path('App_csv_diff/<drawing_data>/', … -
Django Admin pagination not working properly
In my Django admin I want to apply pagination. but pagination is not working properly as when I am going on second page or any other page the 2 is not highlighted in the pagination or for any number. Further if I am having 2 pages i am not being able to go on second page and in URL it shows e=1 but if I am having 3 pages it leaves the second page and goes on 3rd page on clicking 2 and on clicking 3 it goes on 1st page again and in URL it shows e=1. Please let me know how to fix this My pagination.html {% load admin_list %} {% load i18n %} {% if pagination_required %} <ul class="pagination"> {% if cl.has_previous %} <li><a href="?p={{ cl.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in cl.paginator.page_range %} {% if cl.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?p={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if cl.has_next %} <li><a href="?p={{ cl.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> <p style="float:right; margin:10px;">{{ cl.paginator.count }} Projects</p> {% endif %} -
Is there a way to have multiple instances of a model embedded into a single model field in Django?
I know the foreign key concept,Djongo Array field , however is there an alternative? The issue with the foreign key concept is that I would need to make multiple hits to the database and the issue with Array field is the lack of information and the errors emerging without a known solution. What I would like to do basically is in fact add multiple instances of a model say comments to a single field in another model but I would like to embed it rather than creating a new table for comments which I tried using an abstract model however it did not work out. I would like to know any alternative solution. -
Cannot delete entries from database on django
On admin page , I created a delete entries button . I clicked and it asked me yes or no .I click yes but no effect . (The whole system designed with Django ) How to solve ? On A.html <button class="btn btn-danger btn-sm" style = "padding: 2px 4px;" id="delete"onclick = "Del('{{i.id}}')">Delete</button> <script> function Del(id){ console.log("delet*********") swal({ title: "Are you sure?", text: "To Delete this Entry!", icon: "warning", buttons: ["No", "Yes"], closeOnClickOutside: false, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $.ajax({ method : "POST", url : "/delete_lost_item/", data : { 'id':id, }, success : function(response){ if (response == "success"){ swal("Entry has been Deleted..!", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.reload(); }); } } }) } }); } </script> on Table Lost_Item class Lost_Item_table(admin.ModelAdmin): list_display = ['id','lebal','title','brand','species'...] URL.PY url(r'^delete_lost_item/$',delete_lost_item, name='delete_lost_item'), -
Django calling URL from a webserver [duplicate]
I am a beginner to Django and flask here I am creating a URL using POST method in Flask now my need is to invoke that URL in my Django project flask.py from flask import Flask, jsonify, request import math app = Flask(__name__) @app.route("/index", methods=["POST"]) def index(): data = request.get_json() n = data["n"] a = [] r = [] d = [] b = int(a1) c = int(a1) + 1 for i in range(c): r.append(i) com = math.factorial(b) / (math.factorial(r[i]) * math.factorial(b - r[i])) a.append(com) for i in enumerate(a): d.append(i) return jsonify({"out": d}) if __name__ == "__main__": app.run(debug=True) Is there any I can call this URL in Django project. -
How would i filter out approvals and display them under the concerned department?
I am trying to display the approvals under HOD which was made by its department employee For example: when an accounts department HOD login logs in under the approval section only the approval request is made by an employee of the accounts department only. My models : class HOD(models.Model): id = models.AutoField(primary_key=True) # hod_name = models.CharField(max_length=100) emp_no = models.CharField(max_length=50,unique=True,default=0) dept_id = models.ForeignKey(Department, on_delete=models.DO_NOTHING, default=1) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Employee(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) emp_no = models.CharField(max_length=50,unique=True,default='NULL') dept_id = models.ForeignKey(Department, on_delete=models.DO_NOTHING, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class ApprovalReportEmployee(models.Model): id = models.AutoField(primary_key=True) employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) approval_date = models.CharField(max_length=255) approval_message = models.TextField() approval_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() Under admin login, I am able to see all the details of approval made by anyone let it be an employee or hod Please Help Someone I am new to Django. is it possible with the Django ORM or we have to use raw SQL -
How can I handle the "Django - Database error: no such table" error?
I'm pretty new to django and I'm stuck at the problem with models. Here is my users app's models file: from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse from PIL import Image class Schedule(models.Model): title = models.CharField(max_length=150) context = models.TextField() class Input(models.Model): DAYS_OF_FITNESS = [ ('month', '30'), ('month_2', '60'), ('month_3', '90'), ] weight = models.PositiveIntegerField(validators=[MinValueValidator(40)]) age = models.PositiveIntegerField(validators=[MinValueValidator(12)]) days = models.CharField( max_length=20, choices=DAYS_OF_FITNESS, default='30') athlete = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) I'm trying to link each user with its input using OneToOneField and Schedule is linked as a foreign key to Input model But when I'm trying to migrate models, I'm getting this error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: users_input I checked that Both models are in django settings, and I migrated them. BTW, I'm using signals to save inputs automatically, (just for note if it helps) -
How to order by a non-model remote field like this?
I have a table like this: class SystemPushLog(models.Model): push_channel = models.CharField(choices=PUSH_CHANNEL_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, default=SystemPushStatus.WAITING.name, max_length=10) failure_reason = models.CharField(max_length=50) times = models.SmallIntegerField(default=0) create_at = models.DateTimeField(auto_now_add=True) msg_id = models.CharField(max_length=20, unique=True, null=True) user_id = models.IntegerField(null=True) user_phone = models.CharField(max_length=15, null=True) As u can see in the model above, user_id is a Integer field, not a foreign key. Cuz user infos in out system are retrieved from gRPC calls. Now, I wanna to order the queryset by last_login which is a field in user info. I have tried with annotate like this in get_queryset: def get_queryset(self): queryset = super().get_queryset().annotate( last_login=self.__class__.get_user_last_login(F('user_id')) ) And below is get_user_last_login: @staticmethod def get_user_last_login(user_id): print('user_id', user_id) # <<< user_id F(user_id) print('type of user_id', type(user_id)) # <<< type of user_id <class 'django.db.models.expressions.F'> # retrieving user info from rpc call. user = do_user_actions({'id': user_id}) return user.last_login As u can see, F('user_id') passed to the func is a type of django.db.models.expressions.F instead of a actual user_id. Maybe annotate can just take some simple expressions like annotate(off_price=F('original_price') - F('discount_price')). So, how should I implement this remote field ordering? -
How to add new serializer field along with the all model fields?
Here I have a model which has so many fields. So I want to use __all__ to return all the fields. But now I needed to add new field image_url so I customize a serializer like this but now with this I need to put all the model fields in the Meta class like this fields=['name','..', 'image_url'] in order to return the image_url. Is there any way to return image_url without specifying it in the Meta.fields ? I mean I don't want to write all the model fields in the Meta.fields (since the fields are too many) and want to return the image_url also. serializers.py class MySerializer(ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') class Meta: model = News fields = '__all__' def get_image_url(self, obj): return obj.image.url -
Remove results with field==0 from serializer response
I use ModelSerializer to return serialized data of a model: class LepAppDzialWithBazaSerializer(serializers.ModelSerializer): dzial_liczba_pytan = serializers.SerializerMethodField('_dzial_liczba_pytan') def _dzial_liczba_pytan(self, obj): pytania_count = LepAppPytanie.objects.filter(dzial=dzial_obj).count() return pytania_count class Meta: model = LepAppDzial fields = ["id", "dzial", "dzial_liczba_pytan"] What I get write now is here: [{ "dzial": "orzecznictwo lekarskie", "dzial_liczba_pytan": 0, "id": 9 }, { "dzial": "zdrowie publiczne", "dzial_liczba_pytan": 1, "id": 10 } ] I want to remove objects with dzial_liczba_pytan == 0 from serialization [ { "dzial": "zdrowie publiczne", "dzial_liczba_pytan": 1, "id": 10 } ] Thank you for your help. -
Create nested/cascading dropdown using django
I am trying to create multiple cascading dropdowns in django. I referred to this DJANGO_2WAY_NESTED_DROPDOWNS but when I tested the code for more than 2 dropdown the code does not works. Any suggestion would help. Cascading Dropdown Image -
UpdateView in django
i am trying to have attendance for student by the teacher, everything is working fine until i want to edit(update) this Student_Attendence model, i am not able to update this model. what if teacher want to update that attendance again, so need to have that i have list of subject and i can check who were(student) in that class(subject). models.py class Subject_Attendence(models.Model): # i am able to update this one, which i dont want to update lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) department = models.ForeignKey(to='sis.Department', on_delete=models.SET_NULL, blank=True, null=True) semester =models.ForeignKey(to='sis.Semester', on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(to='sis.Subject', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) def __str__(self): return str(self.subject) def get_absolute_url(self): return reverse('lecturer:student_attendance', kwargs={ 'pk': self.pk }) def get_update_url(self): return reverse('lecturer:subject_attendance_edit', kwargs={ 'pk': self.pk }) class Student_Attendence(models.Model): # want to update this model by the teacher lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(Subject_Attendence, related_name='subject_attendance', on_delete=models.SET_NULL, blank=True, null=True) student = models.ForeignKey(to='sis.Student', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) attend = models.BooleanField(default=False) def __str__(self): return str(self.student) def get_absolute_url(self): return reverse('lecturer:student_attendence_detail', kwargs={ 'pk': self.pk }) def get_update_url(self): return reverse('lecturer:student_attendance_edit', kwargs={ 'pk': self.pk }) views.py class Student_Attendance(generic.ListView): model = Subject_Attendence template_name = 'attendence.html' context_object_name = 'queryset' def get_context_data(self, *args, **kwargs): profile = Lecturer.objects.all() semester_course … -
How can I make my ReportLab table data wrap when data is sent from Django views?
I've been trying to get my cell strings to wrap, the table gets too wide and out of screen. I know that using Paragraph automatically wraps text, but the problem is that I'm sending my data from multiple views so the table width and number of columns varies. I've gotten errors like 'list' object has no attribute 'split', 'tuple' object has no attribute 'split' and even 'Paragraph' object is not iterable. class ComprasPDF(View): def get(self, request, *args, **kwargs): arr= [( o.unidad_inventario.control_stock.almacen, o.unidad_inventario.control_stock.producto, o.proveedor, o.cantidad, o.costo_unidad, ) for o in CompraProducto.objects.all()] data = { 'nombre':'COMPRAS', 'headings':('ALMACEN', 'PRODUCTO', 'PROVEEDOR','CANTIDAD','COSTO POR UNIDAD'), 'query': arr } pdf = generar_pdf(request,data) return HttpResponse(pdf, content_type='application/pdf') And using it on ReportLab like this. As you see, I'm using the data I'm sending directly and I don't know how to apply paragraphs styles to the query data. buff = BytesIO() doc = SimpleDocTemplate(buff,pagesize=A4) story = [] headings = data['headings'] alldata = data['query'] t = Table([headings] + alldata*10) t.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ] )) story = [Spacer(0,25),t] doc.build(story, onFirstPage=primera_pagina, onLaterPages=add_numero, ) And the table looks like this. Not even assigning colWidths make them wrap, they just overlap. I need … -
'mod_wsgi-express' is not recognized as an internal or external command, operable program or batch file
I am trying to host the django 3.1(python3.8) app on window 10 with WAMP64 and mod_wsgi API.(Yes its nightmare) Am able to preform the following command sucessfully. 1- set "MOD_WSGI_APACHE_ROOTDIR=C:\wamp64\bin\apache\apache2.4.46" 2- pip install mod_wsgi And the next command which is "mod_wsgi-express module-config" is throwing below error. 'mod_wsgi-express' is not recognized as an internal or external command, operable program or batch file. Please help me with, what am doing wrong or am using mod_wsgi is not the right choice for deploying django app. -
Displaying drop down values based on selection of another drop down using django
class UnassignedShiftForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') super(UnassignedForm, self).__init__(*args, **kwargs) self.fields['booked_with'].queryset = Company.objects.filter(client=self.client) self.fields['location'].queryset = ProjectIdentities.objects.filter(client=self.client, is_deleted=False) self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) ward_list =[] location = ProjectIdentities.objects.filter(client=self.client, is_deleted=False) wards = Ward.objects.filter(corporate_identity__client=self.client) for identity in location: if identity.id in wards: ward = identity.id for q in wards: ward_list.append({"identity":q.corporate_identity,"ward":q}) class Meta: model = Unassigned fields = ['date','additional_days', 'positions', 'start_time', 'banding', 'qualification_speciality', 'location','ward', 'charge_rate'] DJANGO VIEW: class UnAssignedShiftCreateView(CreateView): template_name = 'unassigned_form.django.html' form_class = UnassignedShiftForm context_object_name = "shift" model = UnassignedShift def get_form_kwargs(self): kwargs = super(UnAssignedShiftCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client return kwargs def form_valid(self, form): self.client = self.request.user.client try: shift_order = UnassignedShift.objects.filter(client=self.client).\ order_by('-id')[0].booking_order_number order_number = int(shift_order.split('-')[1]) order_number = 'US-'+str(order_number + 1) except: order_number = 'US-1' self.object = form.save(commit=False) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booking_order_number = order_number addtional_days = form.cleaned_data['additional_days'] date = form.cleaned_data['date'] for i in range(0, int(addtional_days) + 1): try: shift_order = UnassignedShift.objects.filter(client=self.client).\ order_by('-id')[0].shift_number shift_number = int(shift_order.split('-')[1]) shift_number = 'UNS-'+str(shift_number + 1) except: shift_number = 'UNS-1' self.object.pk = None if i == 0: days = 0 else: days = 1 date = date + datetime.timedelta(days=days) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booking_order_number = order_number self.object.shift_number = shift_number self.object.date = date try: … -
Can I use Django and Django Rest Framework together?
I am pretty new to Django and I have a question which I can't find an answer and feel confused about it. I have web based system where only admin can create users. I need to use JSON Web Token for Cross Login but the only way I found to implement this is with Django REST Framework. My current app is only Django based right now. My question is can I use both Django and Django REST Framework together so I can make my JWT for this part, but stayed with Django where is possible?