Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a custom action function using Django DRF viewset.Viewsets?
I have a viewset that I created an @action decorated function. class StoreOffersViewSet(viewsets.ViewSet): """Viewset for yoga stuff.""" @action(detail=False, methods=['put'], name='yoga update') def update_yoga(self, request): # Get Kwargs passed params = self.kwargs In my urls, I have: router = DefaultRouter(trailing_slash=True) router.register(r'yoga', views.StoreOffersViewSet, basename='yoga') urlpatterns = router.urls I would like that when a user has a PUT request to site.com/yoga, my update_yoga function is called. As it stands now, I get the following error: { "detail": "Method \"PUT\" not allowed." } My guess is that this is because for the default router, GET and POST already have the url style from the docs, https://www.django-rest-framework.org/api-guide/routers/#defaultrouter. So I am not too sure how to proceed. I am on django 3.8> -
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field
I am working on a django application. In the application there exists a contribution form. I created the form with django models and django forms. But when I try to run the application, I get the following error. crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field I am not sure what I am doing wrong. django models.py CONTRIBUTE_CHOICE = ( ('Books', 'Books'), ('Renovation', 'Renovation'), ('Other', 'Other'), ) class Contribute(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) email = models.EmailField(max_length=100) contribution = models.CharField(max_length=100, choices=CONTRIBUTE_CHOICE) def publish(self): self.save() def __str__(self): return self.firstName django forms.py from .models import Contribute CONTRIBUTE_CHOICE = ( ('Books', 'Books'), ('Renovation', 'Renovation'), ('Other', 'Other'), ) class ContributeForm(forms.ModelForm): contribution = forms.ChoiceField(choices=CONTRIBUTE_CHOICE, required=True ) class Meta: model = Contribute widgets = { 'firstName': forms.TextInput(attrs={'placeholder': 'First Name'}), 'lastName': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={'placeholder': 'Email'}), } fields = ('firstName', 'lastName', 'email', 'contribution') django views.py from .forms import ContributeForm def donate(request): if request.method == "POST": contributeForm = ContributeForm(request.POST) if contributeForm.is_valid(): post = contributeForm.save(commit=False) post.save() return redirect('home') else: contributeForm = ContributeForm() context = {'contributeForm': contributeForm} return render(request, 'index.html', context) return render(request, 'donate.html') donate.html tempate <form class='contribution_form' method="post"> {% csrf_token %} <div class="row"> <div class="col"> {{ contributeForm.firstName|as_crispy_field }} </div> <div class="col"> {{ contributeForm.lastName|as_crispy_field }} </div> </div> … -
Can i host only a python script directly on heroku without putting the script inside a django app?
i have a python script that needs to run on the heroku but its a pure python script and not a django app yet, so i wondering if i can run python script on heroku without putting it into a django app . I already have the script on heroku but i dont know how to execute it. -
How to fix XLConnect's java.lang.NullPointerException on page refresh
I'm using rpy2 to to use R in python, specifically to use XLConnect package. The reason is because I want to read password protected excel file. Other packages are limited both in R and python as I'm using Linux. So, I've successfully load the excel file now using XLConnect. However everytime I try to refresh my Django project, instead of loading the data it returns java.lang.NullPointerException. It works on the first load, then when I refresh the page, the error immediately pop out. Yet, after i left it without refresh for a few mins and refresh the page again, it works normally. The error just happened to immediate page refresh. It's so frustrating, i thought the error was caused by the error of reading cell (XLConnect's onErrorCell), however that's just warning. The line which caused the problem is on assigning the loadWorkBook to a variable. import rpy2.robjects as rob from rpy2.robjects.packages import importr xlc = importr('XLConnect') xlc_2 = importr('XLConnectJars') string = """ wb <- loadWorkbook("my_file_path_here", create=FALSE, password="ddd") """ powerpack = SignatureTranslatedAnonymousPackage(string, "powerpack") I expect the r code to load again as per normal and read the excel file. -
How to use @property in Django models?
I want to add one subquery to my query. And I created a @property in Transaction. I do not fully understand how they work. How to use it? views.py(Query) paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service__contractor',). models.py class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) payer_id = models.BigIntegerField(blank=True, null=True) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = '"processing"."payer_payment_source"' class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) @property def bank_card_details(self): return PayerPaymentSource.objects.filter(self.payment_source.source_details, payment_type='bank_card_details') class Meta: managed = False db_table = '"processing"."transaction"' -
Attach headers to redirect in Django
In my view, I want to redirect to a URL (which points to a hosted image) but also add the User-Agent header to that GET request (to avoid 403 errors when redirecting to some URLs). I've explored two options: The redirect(url) Django function. Is there a way to somehow add on headers? Using the requests library: r = requests.get(picture.url, headers={'User-Agent': user_agent,}) But then what should I return from my view? return r, return r.content or return json() didn't work for me. Thanks! -
rest framework swagger 'AutoSchema' object has no attribute get_link
I am trying to browse the api documentation of rest framework swagger. but getting error AttributeError: 'AutoSchema' object has no attribute 'get_link I have used django rest framework swagger. but not able to browse the documentation. from django.contrib import admin from django.urls import path, include from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('auth.urls')), path('docs/', schema_view), ] -
Combine repetitive dictionary in a python list of dictionaries to remove repetition
I want to c join this repetitive dictionaries in my list to remove repetiton: The dict: [{"name": "healthcheck","responseTime": 0.600845,"dateCreated": "11/06/19 13:44"}, {"name": "Stack Overflow","responseTime": 0.849753,"dateCreated": "11/06/19 13:44"}, {"name": "Sample Endpoint","responseTime": 0.559156, "dateCreated": "11/06/19 13:44"}, {"name": "healthcheck", "responseTime": 0.369526,"dateCreated": "11/06/19 08:04"}, {"name": "Stack Overflow","responseTime": 0.928371,"dateCreated": "11/06/19 08:04"}, {"name": "Sample Endpoint","responseTime": 0.535189,"dateCreated": "11/06/19 08:04"}] Expected dict: [ {"name": "healthcheck","responseTime": [0.600845, 0.369526],"dateCreated": ["11/06/19 13:44","11/06/19 08:04"]}, {"name": "Stack Overflow","responseTime": [0.849753,0.928371],"dateCreated": ["11/06/19 13:44","11/06/19 08:04"] }, {"name": "Sample Endpoint","responseTime": [0.559156, 0.535189] "dateCreated": ["11/06/19 13:44","11/06/19 08:04"]} ] -
django post_save: how to insert and update all related record from another table
class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section, Education_Levels=instance.Education_Levels, Courses=instance.Courses) for each in teachers: if created or teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( Students_Enrollment_Records= instance, defaults={'Subject_Section_Teacher':each} ) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) almost a week i tried to solve this problem but till now i didnt solve it, my problem is when i insert data(picture 1), it will get the related record from picture 2 but in my case only 1 save related record in picture 3, picture 1 picture 2 picture 3 -
How to execute a python script after clicking a button in HTML (Django)?
I want to execute a python script after a user (registered user) clicks on a button in HTML using Django. How can this be achieved? Can someone give me a hint on how to create the logic in the views.py along with the Html code in the template? Before executing the button code, I want to check whether if the user.id exists in the model. If not, the button doesn't do anything. Currently, this is basic understanding: views.py: def button(request): #python script return render(request, 'users/home.html') home.html: {% if user.id %} <button class="btn btn-outline-info" onclick="location.href={% url 'button' %}"> Manual Index </button> FYI, I am new to Django and am still exploring its potential. -
How to solve the access token error for Microsoft graph API?
I am trying to get mails from Outlook from Microsoft graph API by following https://docs.microsoft.com/en-us/outlook/rest/python-tutorial But on Django I am having following error: python3.6 manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 07, 2019 - 05:06:46 Django version 2.0.2, using settings 'python_demo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /tutorial/gettoken/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/komal/python_demo/tutorial/views.py", line 22, in gettoken access_token = token['access_token'] KeyError: 'access_token' [07/Nov/2019 05:06:54] "GET /tutorial/gettoken/?code=M596caf0d- 2dae-0da1-e124-a6ab92ffded9 HTTP/1.1" 500 71248 How to solve it? -
Django: Problem with Adding Clickable Link in the Second Template
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models and views. I have also managed to add clickable link in the first template (brandlist.html). In the first template, when you click on the brand name, like Samsung, you will be taken to the page of the phone model, like Galaxy S10. Here is the screenshot of the first template: When you click the link, you will be taken to the second template (phonemodel.html). But now, I am facing an issue. There is no clickable link on the phone model ("Galaxy S10") that will direct you to details.html. Here is the screenshot. Here are the codes of models.py inside the "PhoneReview" folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) def __str__(self): return … -
How do I link models together using foreign key with Django?
I am trying to update three models in django with a task function and link them together using a foreign key. Event, Market & Runner I would like to be able to query the data in my views and display the data. A single event has multiple markets and in each market there's multiple runners. I'm getting an error when I try to use foreign keys to link the three models together. django.db.utils.ProgrammingError: relation "apimb_event" does not exist STATEMENT: SELECT "apimb_event"."event_id", "apimb_event"."event_name", "apimb_event"."start_time", "apimb_event"."status" FROM "apimb_event" ORDER BY "apimb_event"."event_id" DESC LIMIT 21 I don't think I'm using foreign key's correctly. Each model has a id as a primary key. I can update and create this data fine without using foreign keys but, How can I update the model and then query the data to show as below? Event Market Runner event_name_1 market_name_1 runner_name_1 runner_name_2 runner_name_3 event_name_1 market_name_2 runner_name_1 runner_name_2 runner_name_3 runner_name_4 task_function @shared_task(bind=True) def get_events(self): api = get_client() events = api.market_data.get_events(sport_ids=[9],states=MarketStates.All, per_page=200, offset=0, include_event_participants=Boolean.T, category_ids=None, price_depth=3, side=Side.All, session=None) for event in events: event_name = event["name"] event_id = event['id'] start_time = event['start'] status = event["status"] ev, created = Event.objects.update_or_create(event_id=event_id) ev.event_name = event_name ev.start_time = start_time ev.status = status ev.save() markets = … -
Issue while returning the errors list
Below is code in views.py file. class login(View): def get(self, request): return render(request, 'login.html') def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') return HttpResponse("ok") else: form = LoginForm() return HttpResponse(form) Below code is in template file. <form method="post" action="{% url 'authapp:login' %}"> {% csrf_token %} <input type="text" name="username" class="form-control"> <input type="password" name="password" class="form-control"> <button type="submit" class="btn btn-primary"> Login </button> </form> below code is in forms.py file from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length = 50, required = True), password = forms.CharField(max_length = 50, required = True) Issue Details When i submit the form with both username and password empty, it returns just a textfield of password. I was expecting a list of errors for required username and password. As both are required in forms file. Can you please suggest something? -
Django Middleware - 'AnonymousUser' object is not iterable
Related question for context/code: My Django Middleware Isn't Working The Way It Should So I just got help and got my other question related to this one answered but after I added the code I found out now every time a user who isn't signed in views the site they see the error below so any help with be appreciated. Thanks Error: 'AnonymousUser' object is not iterable middleware.py: from .models import UserBanning from django.shortcuts import render, redirect class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if(UserBanning.objects.filter(ban=True, user=request.user)): context = { 'banned': banned[0], } return render(request, "account/banned.html", context) else: response = self.get_response(request) return response models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" -
write way of getting user ip address
I got this code from stack overflow answers. Getting user ip address def get_client_ip(request): x_forwarded_for =request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip= x_forwarded_for.split(",")[0] else: ip=request.META.get('REMOTE_ADDR',None) return ip This works well when i am running my webapp on local environment,but when i launched the website online, it does not get the right ip address allocated to me by ISP. And my ip the code gets keep on changing when ever i reload . What is the correct way to go about solving this problem thank you -
How to use update_or_create on django post_save?
class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section, Education_Levels=instance.Education_Levels, Courses=instance.Courses) for each in teachers: if created or teachers.exists(): print("if") StudentsEnrolledSubject.objects.create_or_update( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) Inserting data is working perfectly but when I update the existing data it creates another record not update -
unknown field specified error for drop down list in django forms
I am working on a web application. The application consists of a drop down list. I created a new model and migrated the model. But when I try to create a form with django forms.py I get the following error message django.core.exceptions.FieldError: Unknown field(s) (fruits) specified for Fruits models.py class Fruits(models.Model): FRUIT_CHOICE = ( ('apple', 'Apple'), ('mango', 'Mango'), ('banana', 'Banana'), ) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) email = models.EmailField(max_length=100) fruits = models.CharField(max_length=100, choices=FRUIT_CHOICE) def publish(self): self.save() def __str__(self): return self.firstName forms.py from .models import Fruits class Fruits(forms.ModelForm): class Meta: model = Fruits widgets = { 'firstName': forms.TextInput(attrs={'placeholder': 'First Name'}), 'lastName': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={'placeholder': 'Email'}), 'fruits': forms.ChoiceField() } fields = ('firstName', 'lastName', 'email', 'fruits') What am i doing wrong? -
Djngo REST API: KeyError at /api/update
i was trying to perform bulk update using django-bulk-update https://github.com/aykut/django-bulk-update But it throws KeyError at /api/update 'id' views class CartUpdatesView(ListBulkCreateUpdateDestroyAPIView): queryset=models.Cart.objects.all() serializer_class=serializers.CartUpdatesSerializer serializers class CartUpdatesSerializer(BulkSerializerMixin,serializers.ModelSerializer): class Meta(object): model = models.Cart fields = '__all__' list_serializer_class=BulkListSerializer models class Cart(models.Model): cart_id=models.AutoField(primary_key=True) product_qty=models.IntegerField() customer_id=models.IntegerField() product_id=models.ForeignKey('Products',db_column='product_id',on_delete=models.CASCADE) Does this happens because of 2 primary keys while joiing tables?. I dont have any idea on bulk update. By searching I figure out official doc provide only very little information on bulk update and everyone refers to use this package. GET HTTP 200 OK Allow: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "cart_id": 1, "product_qty": 4, "customer_id": 1, "product_id": 1 } ] PUT [ { "cart_id": 1, "product_qty": 9, "customer_id": 1, "product_id": 1 } ] Traceback Environment: Request Method: PUT Request URL: http://localhost:8000/api/update Django Version: 2.2.5 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shoppingcart', 'rest_framework', 'rest_framework.authtoken'] 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: File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, … -
forms module not found inside the child app
I have already checked this answer on stackoverflow but did not get any suggestion in this context. There is root app and then created another app in root. Inside the view.py of child app, I wrote below code. from forms import MyForm I got an ModuleNotFoundError No module named forms Also tried with .forms and with myapp.forms and .myapp.forms But no luck. Can you please suggest? -
how to loop insert data from database to select form with django
so i want to make a dependent select box , but im still beginner and want to try with the old way The point is , the first dropdown is the database name (schema in dbeaver) and the second dropdown is list of table name that the database has html code <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> {% for table_name in obj %} <option>{{ table_name.table_name }} {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> *here where i want to put the data after i select the first select above* <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> Havent put the post and get for the first select dropdown to send the parameter *dont know where views.py #for the first dropdown def list_all_table(request): obj = TableAll.objects.all() context = { 'obj' : obj } return render(request,'define_segment.html',context) #for the second dropdown form after you select the first dropdown def list_all_table2(request): #need to get parameter first but how dsn_tns = cx_Oracle.makedsn('IP', 'PORT', sid) … -
Mock import to test class method
I have a class that is a Django model: from django.db import models class User(models.Model): The class has a few methods unrelated to the DB side (helpers/static methods, etc). However, when I import it, because it calls django.db.models, it also tries to use the Django settings to connect to the DB. I'm not sure how to properly mock this so it's workable but I can write unit tests for the extra methods. -
How could I update mysql database information if my update button is on a modal?
{% for employee in employees %} <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" >Employee</h5> <button type="button" class="close" modalid="referral_modal" id="close_referral" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body" style="overflow: auto"> <div class="col-md-15"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col-md-12"> <h4>Your Profile</h4> <hr> </div> </div> <div class="form-group row"> <label for="name" class="col-4 col-form-label">First Name</label> <div class="col-8"> <input id="name" name="name" placeholder="First Name" value="{{ employee.first_name }}" class="form-control here" type="text" readonly> </div> </div> <div class="form-group row"> <label for="lastname" class="col-4 col-form-label">Last Name</label> <div class="col-8"> <input id="lastname" name="lastname" placeholder="Last Name" value="{{ employee.last_name}}" class="form-control here" type="text" readonly> </div> </div> <div class="modal-footer"> <button onclick="" name="submit" type="submit" class="btn btn-primary">Edit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="">Cancel</button> </div> Modal Code: Model.py class Employee(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'employee' Views.py (nothing) For now I don't have a view.py for the update button since i don't know how to start on that, asking for recommendation regarding that, I'm still new to Django. Thanks -
DRF: cannot convert URL to instance using HyperlinkedIdentityField
How can I use a HyperlinkedIdentifyField to convert a url to an instance? I have a couple of nested HyperlinkedModelSerializer: class ChildSerializer(HyperlinkedModelSerializer): class Meta: model = Child fields = ('url', 'name') extra_kwargs = { 'name': {'required': False} } class ParentSerializer(HyperlinkedModelSerializer): class Meta: model = Parent fields = ('url', 'child') But this doesn't work: >>> s = ParentSerializer(data={'child': {'url': '<valid url>'}}) >>> s.is_valid() True >>> s.validated_data() OrderedDict([('child', OrderedDict())]) For whatever reason, to_instance_value from HyperlinkedModelSerializer doesn't retrieve the actual object. So the obvious solution is to override this, but I cannot work out how to get the HyperlinkedIdentityField for ChildSerializer to return an internal value. I have a kludge that is working for now: class ChildSerializer(HyperlinkedModelSerializer): ... def to_internal_value(self, data): pk = parse_pk_from_url(data['url']) return self.Meta.model.objects.filter(pk=pk).get() But I feel like there must be a mechanism for retrieving objects from valid URLs that I'm missing here... -
Crystal Report with Django Python
Now I am working with Django Rest Framework and my requirement is to generate the report by using crystal reports or other tools but first will use crystal report. My project used DRF as backend and React as frontend. I think React cant do like that kind of job so I am trying to do generate report as pdf from DRF and I will respond to react. Now I am stuck how can I connect to crystal report from DRF? Please Help.