Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django form changed_data method: why checked radio button always in changed_data even if not changed?
I want to check when field has been changed when submitting of form with Django. There are tow form attributed that can be used: has_changed (return True if at least one field has been changed) and changed_data (that return list of changed field). But for a reason I can not understand, when a radio button field is checked, has_changed will always return True, even if not changed (and filed is in changed_data list) In the example belwo, inc_dat field (date field) behavior is correct but not inc_oui_age which is a radio button models.py class Inclusion(models.Model): """ A class to create a Inclusion instance. """ _safedelete_policy = SOFT_DELETE_CASCADE # insert model fields ide = models.AutoField(primary_key=True) pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') inc_dat = models.DateField('Date de la visite', null=True, blank=True) inc_oui_age = models.IntegerField('18 ans ≤ âge ≤ 45 ans OU âge ≥ 55 ans', null=True, blank=True) ... forms.py class InclusionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.IDE = kwargs.pop("ide", None) self.PATIENT = kwargs.pop("patient", None) self.USER = kwargs.pop("user", None) super(InclusionForm,self).__init__(*args, **kwargs) self.fields['inc_dat'] = forms.DateField(label = 'Date de la visite',widget=forms.TextInput(attrs={'autocomplete': 'off'}),required=False, disabled=DISABLED) self.fields['inc_oui_age'] = forms.TypedChoiceField(label = '18 ans ≤ âge ≤ 45 ans OU âge ≥ 55 ans',widget=forms.RadioSelect(attrs={'disabled': DISABLED}),required=False,choices=[i for i in Thesaurus.options_list(1,'fr') if i … -
Django Elastic Beanstalk - No module named 'turtle'
After running eb deploy & opening up my elastic beanstalk django website I get a module error of No module named 'turtle'. It all run perfect locally and I have PythonTurtle installed & in my requirements.txt. Is there a missing pip I haven't accounted for in my requirements.txt? I've run pip3 freeze > requirements.txt many times with the same result. How can I get past this error? appdirs==1.4.4 asgiref==3.3.4 astroid==2.4.2 attrs==21.2.0 autopep8==1.5.7 awsebcli==3.20.2 bcrypt==3.2.0 blessed==1.18.1 botocore==1.21.65 bugsnag==4.2.0 cached-property==1.5.2 cement==2.8.2 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 colorama==0.4.3 cryptography==3.4.7 distlib==0.3.1 dj-places==4.0.0 Django==3.1.6 django-crispy-forms==1.11.0 django-filter==21.1 django-mathfilters==1.0.0 djangorestframework==3.12.4 djangorestframework-simplejwt==5.0.0 docker==4.4.4 docker-compose==1.25.5 dockerpty==0.4.1 docopt==0.6.2 filelock==3.0.12 future==0.16.0 idna==2.10 importlib-metadata==4.8.2 isort==5.7.0 jmespath==0.10.0 jsonschema==3.2.0 lazy-object-proxy==1.4.3 Markdown==3.3 mccabe==0.6.1 paramiko==2.7.2 pathspec==0.5.9 psycopg2-binary==2.8.6 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.3.0 pylint==2.6.0 PyNaCl==1.4.0 pyrsistent==0.18.0 python-dateutil==2.8.1 PythonTurtle==0.3.2 pytz==2021.1 PyYAML==5.4.1 requests==2.25.1 s3transfer==0.5.0 selenium==3.141.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.1 termcolor==1.1.0 texttable==1.6.3 toml==0.10.2 tqdm==4.62.3 urllib3==1.26.7 virtualenv==20.4.2 wcwidth==0.1.9 websocket-client==0.59.0 wrapt==1.12.1 zipp==3.6.0 -
deploying https://github.com/codervivek/deep_player on my localhost [closed]
following error pops up for django: [Errno 11001] getaddrinfo failed Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 3.2.12 Exception Type: gaierror Exception Value: [Errno 11001] getaddrinfo failed Exception Location: C:\Program Files\Python37\lib\socket.py, line 752, in getaddrinfo Python Executable: C:\Program Files\Python37\python.exe Python Version: 3.7.9 Python Path: ['C:\Users\User_Name\OneDrive\Interview\Academics\University\Under_Graduation\BE\SEMESTER_8\BE_PROJECT\deep_player', 'C:\Program Files\Python37\python37.zip', 'C:\Program Files\Python37\DLLs', 'C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Users\Ayush Adhikari\AppData\Roaming\Python\Python37\site-packages', 'C:\Program Files\Python37\lib\site-packages'] Server time: Tue, 08 Mar 2022 16:14:22 +0000 -
How to exclude field conditionaly?
I need to exclude id_from_integration if Company.integration_enabled == False. My resource and model: class Company(models.Model): integration_enabled = models.BooleanField() class Report(models.Model): company = models.ForeignKey(Company) class ReportResource(resources.ModelResource): ... class Meta: model = Report fields = ('name', 'id_from_integration', ...) -
Cannot force Postgresql to accept SSL connections only
Here's my current config: postgresql.conf: ssl = on ssl_cert_file = '/etc/postgresql/12/main/fullchain.pem' ssl_key_file = '/etc/postgresql/12/main/privkey.pem' pg_hba.conf: local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5 # IPv4 remote connections: hostssl all all 0.0.0.0/0 md5 # IPv6 remote connections: hostssl all all ::/0 md5 Still, my Django application is able to migrate database changes with and without 'OPTIONS': {'sslmode': 'require'} and that is not what I want. I want Postgresql to reject non-ssl connections and I don't know what I'm missing here. P.S: Certificate is valid and created by certbot. -
How to create retro load file in django
def create_workflow_status_node_merchant_financing_135_handler(apps, _schema_editor): workflow = Workflow.objects.get(name=WorkflowConst.MERCHANT_FINANCING_WORKFLOW) WorkflowStatusNode.objects.get_or_create( status_node=135, handler=MerchantFinancing135Handler.__name__, workflow=workflow ) class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(create_workflow_status_node_merchant_financing_135_handler, migrations.RunPython.noop), ] like this how to create a retroload file in django .for adding data in to database -
Adding Like Functionality to an image
New to Django any help will be appreciated. Thank you. I am trying to add a likes feature to my photos app like Instagram and even show the number of like at the moment I am getting a 'Page not found error'. I sure my logic is not working too models.py Photo Model class Photo(models.Model): img = models.ImageField(upload_to='images') caption = models.CharField(max_length=250, default='Caption here') date_posted = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(User, on_delete=models.CASCADE) Likes Model class Like(models.Model): like = models.IntegerField() image = models.ForeignKey(Photo, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=20) Like Button in a form PS. I was using I was using class based views here hence the use of 'object' <form action="{ url 'like-photo' object.id }" method="POST"> {% csrf_token %} <button class="btn btn-primary" type="submit" name="img_id" value="{{ object.id }}">Like</button> </form> views.py I want to be redirected to photo-detail view def LikeView(request, pk): photo = get_object_or_404(Photo, id=request.POST.get('img_id')) photo.like.add(request.user) return HttpResponseRedirect(reverse('photo-detail', args=[str(pk)])) urls.py urlpatterns = [ ... path('like/<int:pk>/', LikeView, name='like-photo'), ] -
hi three i have been in trouble whnever i try to do "docker-compose build" ,,,
actually i was trying to make image by docker so i executed "docker-compose build" on terminal but i failed,, here's my failed informations, if you want to know more about other impormations, let me know it, i will add it as soon as possible! #11 70.18 warning: build_py: byte-compiling is disabled, skipping. #11 70.18 #11 70.18 running build_ext #11 70.18 building '_cffi_backend' extension #11 70.18 creating build/temp.linux-x86_64-3.9 #11 70.18 creating build/temp.linux-x86_64-3.9/c #11 70.18 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -D USE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/usr/local/include/python3.9 -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.9/c/_cffi_backend.o #11 70.18 c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory #11 70.18 15 | #include <ffi.h> #11 70.18 | ^~~~~~~ #11 70.18 compilation terminated. #11 70.18 error: command '/usr/bin/gcc' failed with exit code 1 #11 70.18 [end of output] #11 70.18 #11 70.18 note: This error originates from a subprocess, and is likely not a problem with pip. #11 70.19 error: legacy-install-failure #11 70.19 #11 70.19 × Encountered error while trying to install package. #11 70.19 ╰─> cffi #11 70.19 #11 70.19 note: This is an issue with the package mentioned above, not pip. #11 70.19 hint: See above for output from the failure. ------ failed … -
How to rewrite django admin login view?
This is my custom login view where user can only login if their email verified. I also added two step verification in my login view. is there any way where I can implement this view in django admin login ? def login_view(request): username = None password = None two_factor = None if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') otp = request.POST.get('auth_code') user = authenticate(request, username=username, password=password) User = get_user_model() if user is not None and user.is_active: user_mail = user.userprofile.filter( user=user, email_confirmed=True) two_factor = user.userprofile.filter( user=user, two_factor=True) for i in two_factor: ....my two factor code if user_mail and two_factor: if secret_code == otp: login(request, user) -
I have ran the DJango project in my local machine windows 10 getting the below errors
Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "env\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "env\lib\site-packages\django\core\management_init_.py", line 345, in execute settings.INSTALLED_APPS File "env\lib\site-packages\django\conf_init_.py", line 83, in getattr self.setup(name) File "env\lib\site-packages\django\conf_init.py", line 70, in _setup self.wrapped = Settings(settings_module)enter code here File "env\lib\site-packages\django\conf_init.py", line 177, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _call_with_frames_removed File "settings\django.py", line 5, in from base.settings.django import * -
I am getting Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I am building an e-com site using the Django framework. to make it more efficient I am using javascript here and there. So the problem occurs at the checkout page and specifically if a user is logged in. On my site, a user can shop even if he is not logged in as a guest user. so if a guest user is going to the checkout page he can submit the process and make payment without running into any issues. But when a user is logged in the checkout page returns the error on load! even before writing anything into the form. I am attaching the checkout page code here for you guys to give it a good look. I have tried to debug it as well as run into the built-in code snippets here. It works fine without any issues {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="Form-control" type="text" name="name" placeholder="Name"> </div> <div class="form-field"> <input required class="Form-control" type="email" name="email" placeholder="Email"> </div> </div> <div id="shipping-info"> <hr> <p>shipping-info</p> <hr> <div class="form-field"> <input required class="Form-control" type="text" name="address" placeholder="Street"> </div> <div class="form-field"> <input … -
Django what function is called at the moment the queryset is evaluated?
I want to override the behavior (add a small step) before the queryset is evaluated. For write/read querys like update, get, I can just override the update/get method. However, I wonder what function is triggered when you do list(queryset), or len(queryset). What funciton is triggered here, and how should I override this? -
wagtail 'NoneType' object has no attribute 'model'
I have install a fresh wagtail when I try to create a page I'm getting error : 'NoneType' object has no attribute 'model' My class is : class CategoryPage(Page): description_meta = models.CharField(max_length=500, null=True, blank=True) template = models.CharField(max_length=500, null=True, blank=True, default='_nixaTemplate/category/default.html') image = models.ImageField(_("Image"), upload_to="img/category/", blank=True, null=True) display = models.BooleanField(_("Display Post"), default=False ) content_panels = Page.content_panels + [ FieldRowPanel([ FieldPanel("description_meta", classname="col-12 col12"), FieldPanel("template", classname="col-12 col12"), ImageChooserPanel("image", classname="full"), ]), ] when I try to create Category Page I get that message -
How to view value of related foreign key in Django from multiple models
I have the following models in my Django project from different apps Student App Model from django.db import models import batch.models import course.models class Student(models.Model): ACTIVE = 'Active' DROPPED = 'Dropped' TRANSFERRED = 'Transferred' INACTIVE = 'Inactive' studentStatus = [ (ACTIVE, 'atv'), (DROPPED, 'drp'), (TRANSFERRED, 'trf'), (INACTIVE, 'inv'), ] first_name = models.CharField('First Name', max_length=30) last_name = models.CharField('Last Name', max_length=30) student_batch = models.ManyToManyField(batch.models.Batch,related_name='batch') contact_no = models.CharField('Contact No', max_length=20, null=True, blank=True) email_address = models.EmailField('Student Email', null=True, blank=True) student_status = models.CharField('Student Status', max_length=20, choices=studentStatus, default=ACTIVE) student_remark = models.CharField('Student Remark', max_length=255, null=True, blank=True) student_course = models.ManyToManyField(course.models.Course,related_name='course') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.first_name} {self.last_name}" Batch App Model from django.db import models from datetime import date, timezone import course.models import trainer.models from django.contrib.auth.models import User class Batch(models.Model): ACTIVE = 'Active' HOLD = 'Hold' SCHEDULED = 'Scheduled' CANCELED = 'Canceled' TRANSFERRED = 'Transferred' batchStatus = [ (ACTIVE, 'act'), (HOLD, 'hld'), (SCHEDULED, 'scd'), (CANCELED, 'cld'), (TRANSFERRED, 'trd'), ] batch_course = models.ForeignKey(course.models.Course, on_delete=models.SET_NULL, blank=True, null=True) batch_trainer = models.ForeignKey(trainer.models.Trainer, on_delete=models.SET_NULL, blank=True, null=True) batch_time = models.TimeField('Batch Time', blank=True, null=True) batch_start_date = models.DateField('Batch Start Date', default=date.today) created_by = models.ManyToManyRel('Batch Created By', to=User) batch_status = models.CharField('Batch Status', choices=batchStatus, default=ACTIVE, max_length=20) created_on=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) def __str__(self): return f"{self.batch_course} | {self.batch_time} | … -
Pass dropdown selected:option text that is being printed to cosole.log() or HTML page to python terminal in views.py
I want to get the option text of selected option from dropdown as a variable in views.py that are being printed in console.log() or which are being displayed on HTML page. Like AMBALA being displayed on HTML or console.log() here I am quite new to Django, so not sure how to fetch it. However, the question is related to the previous query as in here. for getting text of option, the Jquery is as: function get_district_text(){ display_district_text = $("#district_from_dropdown option:selected").text(); console.log("to_display", display_district_text) to_display = document.querySelector("#query_btn_Distdisplay").textContent=display_district_text } index.html is as <div > <input type="submit" value = "click", onclick="get_district_text()"> <b name="query_btn_Distdisplay" id="query_btn_Distdisplay"> </b> </div> In views.py StateName & DistrictName are being parsed or showing text but DistrictNameText is giving print output as None def inputconfiguration(request): if request.method == "POST": StateName=request.POST.get('state_from_dropdown') DistrictName=request.POST.get('district_from_dropdown') DistrictNameText = request.POST.get('query_btn_Distdisplay') print(StateName, DistrictName, DistrictNameText ) return render(request, 'configure_inputs.html') How to get the text of DistrictNameText as a python variable in views.py? -
How to convert raw query to django orm query?
I was trying this morning onwords but couldn't get as excepted result and i'm learning something today with this could you guys help me to get this. and i'm newby to django. SELECT Id, Name, PersonContactId, Phone, Ob_Designation__c, ClubName__c, Membershipno__c, FirstName, LastName, Religion__pc, LanguageName__pc, sfid FROM salesforce.Account WHERE producthierarchycode__c in (select distinct productcode__c from salesforce.dimmarketinghierarchy__c where mh2code__c = 'CCMDTEST') and WSS_Terri_Code__c in (SELECT WSSTerritoryCode__c FROM salesforce.DimMarketingHierarchy__c WHERE MH2Code__c = 'CCMDTEST') and (IsDeleted__c IS NULL OR IsDeleted__c != '1') ORDER BY createddate DESC limit 50 here is my query. -
Django as a websocket client
I know that Django Channels can be used to make websocket server, not client. So I used websockets to relay websocket incoming message to my Django like this: async def relay(): source_server = 'ws://source.example/ws/message' # This is an external server target_server = 'ws://target.example/ws/message' # This is my Django server async for target in websockets.connect(target_server): try: async for source in websockets.connect(source_server): try: while True: try: message = await source.recv() await target.send() # log message except websockets.ConnectionClosed as e: # lost source server or target server or both raise(e) except Exception as e: # did not lose servers continue except websockets.ConnectionClosed as e: # lost source server or target server or both if target.close_code is not None: # lost target server and need to start from the outer for loop # (to get a new target websocket connection) source.disconnect() raise(e) # lost source server and will continue the inner for loop # (to get a new source websocket connection) continue except Exception as e: # did not lose any server and will continue the inner for loop # (to get a new source websocket connection) continue except websockets.ConnectionClosed as e: # lost target server and will continue the outer for loop # … -
Django How do I check that a choices field is not blank in a filter
I have a choices field that can be blank review_comment = models.CharField(max_length=60, choices=REVIEW_COMMENT_CHOICES, blank=True) I now want to filter by review_comment!=blank e.g. return self.filter(active=True, review_comment!=blank) How can I achieve this? -
Unable to make requests to AWS mysql in ec2 instance after delpoying through eb cli
I'm using RDS MySQL from AWS and it works on a local machine I can successfully login to Django admin using the same db also can migrate and etc. But the problem is when I deployed this project with the same settings with EB CLI via ec2 instance, the project loaded successfully. except for the db operations, that does not work properly. I can't log in into admin, and that gives 504 Gateway Time-out That takes 60 sec to process the request but fails every time. But db operations are working on the local machines. For example, I tried making a GET request from localhost using the same db /api/v1/categories/1/ that gives me `200 response But when I tried from the same project hosted on ec2 instance it gives 504 response These are the eb configurations: packages: yum: python3-devel: [] mariadb-devel: [] option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application Some suggest increasing HTTP request processing time. But why does it's taking too long but works on the remote connection locally. from the local Django settings. Are there any extra settings to set up to handle this problem? Or what might be the solution could be? -
Python Django: Customize User
I only use the Rest_Api from Django 4.1 Python. Thats my project Setting: mealSheetAI setting.py mealSheetApi admin.py models.py models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) USERNAME_FIELD = 'email' admin.py from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) settings.py AUTH_USER_MODEL = 'mealSheetApi.User' -
How to load static file image in Vue component with Django Application
I am currently using laravel-mix, Django, and Vue together. I would like to load the static image inside the Vue component. My images store in static/img folder First of all, I have set up an alias in Webpack config pointing to the static folder. const path = require('path') let publicPath = 'src/static' module.exports = { resolve: { extensions: ['.js', '.vue'], alias: { '@': path.join(__dirname, publicPath) }, }, } And load the image in Vue component <img :src='require(`@/img/Blue.jpg`).default' alt=""> I can't load images and Webpack generated new images into the images folder. How to prevent it and load image correct -
django allauth google login
I'm learning how to develop a todo app with users using their google accounts and I found this tutorial https://www.tutorialspoint.com/google-authentication-in-django and I'm trying to create a log out button but its giving me an error Reverse for 'auth_logout' not found. 'auth_logout' is not a valid view function or pattern name. home.html {% load socialaccount %} <h1>Django Allauth Tutorial</h1> {% if user.is_authenticated %} <p>Welcome {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}?next=/">Sign In</a> {% endif %} <a href="{% url 'auth_logout' %}?next=/"> Logout</a> urls.py from todo.views import todo_view, add_todo, delete_todo, home urlpatterns = [ path('', home), path('accounts/', include('allauth.urls')) ] settings.py LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' I just copy+paste this from another thread <a href="{% url 'auth_logout' %}?next=/"> Logout</a> -
DJANGO - HOW TO SAVE A FORM WITHIN A GET METHOD?
I have a view that will load specific data in order to store it on another table. But as I click on Save, it hasn't been reflected on the view using method POST. Have to load first some data on a table then post it to another table using the loaded data clicked on the select input. Can you pls help? Thanks <form action="{% url 'save_selectionlist' %}" method = "POST"> {% csrf_token %} <!--FORM HEADING--> <div class="row"> <div class="col-md-12 mx-0"> <div class="form-group col-md-9 col-sm-9 text-left"> <label for="disabledTextInput">Election Code: </label> <span class="lead">{{ get_election_code.code }}</span> </div> <div class="col text-right"> <button type="button" id= "AddButton" class="btn btn btn-outline-primary btn-sm">Add More +</button> </div> </div> </div> <!--THIS IS WHERE I LOAD DATA FROM VIEW--> <div class="row" id = "SelectionField"> <div class="col-md-12 mx-0" id = "field1"> <div class="col-md-4 col-sm-6 form-group text-left"> <select id ="selection-sh" name = "selection-sh" class="form-control form-control-sm sh" aria-label=".form-select-sm example"> <option selected>-- SELECT STOCKHOLDER --</option> {% for sh in get_stockholder %} <option value="{{sh.id}}" >{{sh.sh_fname|add:' '|add:sh.sh_lname}}</option> {% endfor %} </select> </div> <div class="col-md-4 col-sm-6 form-group text-left"> <select id ="selection-proxy" name="selection-proxy" class="form-control form-control-sm pr" aria-label=".form-select-sm example" disabled> <option selected>-- SELECT PROXY --</option> {% for pr in get_proxylist %} <option value="{{pr.id}}" >{{pr.sh_proxy_fname|add:' '|add:pr.sh_proxy_lname}}</option> {% endfor %} </select> </div> … -
How to pass update django model ID in knockout ajax success url and how to slice id with url
views.py def visitor(request,id): # fruser = get_object_or_404(FRUser,id=id) if request.method == "POST": uid = request.GET.get('visitor_nric_no') name = request.GET.get('name') company_name = request.GET.get('company_name') user_type = request.GET.get('userType') visit_purpose = request.GET.get('purposeOfVisit') valid_from_date = request.GET.get('validFrom') valid_till_date = request.GET.get('validTill') fruser = FRUser.objects.get(id=uid) fruser.name = name fruser.company_name = company_name fruser.user_type = user_type fruser.visit_purpose = visit_purpose fruser.valid_from_date = valid_from_date fruser.valid_till_date = valid_till_date fruser.save() print(fruser.name) context = {'fruser':fruser} return render(request, 'kiosk/visitor-checkIn/visitor-new-registration.html',context) knockout.js submitHandler: function() { var ViewModel = function () { var self = this; self.nric_no = ko.observable(""); self.save = function () { var formdata = new FormData(); formdata.append('nric_no', self.nric_no()); console.log(formdata) $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/kiosk/kiosk/nric/api", data: formdata, headers: { 'X-CSRFToken': csrftoken }, processData: false, contentType: false, success: function () { alert('Success'); window.location = '/kiosk/kiosk/visitor/visitor-new-registration' + fruser.uid; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()); }, }); How to give django model id in knockout js ajax succes url and how to slice id with url I want to pass django FRUser model uid to success url ajax knockout area how to pass that and I want to slice id with url how to solve this Thanks in advance -
How to replace line breaks (\n) with <br> for textual data to html content
I am loading data from a database. The textual data has line breaks \n as uploaded by the user, I would like to print this data on a html page. However line breaks do not occur. I have tried replacing \n with <br>, but that prints with <br> as part of the string instead of actually breaking the line. How I replace value['description'].replace('\n', '<br>') How it appears: