Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django ORM explain() function not giving expected output?
I'm trying to understand how the .explain() function works in Django ORM. The official documentation here says this. print(Blog.objects.filter(title='My Blog').explain()) gives below output. Seq Scan on blog (cost=0.00..35.50 rows=10 width=12) Filter: (title = 'My Blog'::bpchar) But if I try to print the same thing in my local Django shell, it is giving me different output like below. print(OCUser.objects.all().explain()) gives SIMPLE alyssa_ocuser None ALL None None None None 2853 100.0 None which is not similar to the one in the official documentation. I'm not sure what this SIMPLE, and all those None values are. Can someone please explain? Am I doing something wrong? Please leave a comment before downvoting the question. Python: 3.7.3 Django: 2.1.5 Mysql: Ver 14.14 Distrib 5.7.26 -
Django 1.11: URL function in template not working as expected
I've created 2 test apps, test1 and test2, and added the same functions in the views and same entries in the url files. The problem is that it does not matter which app you access, the same link, appname/link, is shown as the href. Does not matter if I access http://127.0.0.1:8000/test1 or http://127.0.0.1/test2, the link will always be "Test Link" Using the syntax url 'appname:link' does work, and sending an extra parameter to the html template to use the app name does work, but how can it be addressed only to use url 'link' Project urls: from django.conf.urls import include, url from django.views import generic from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^test1/', include('test1.urls')), url(r'^test2/', include('test2.urls')), ] test1 url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'testapp/', views.testapp, name='testapp'), ] test2 url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'testapp/', views.testapp, name='testapp'), ] test1 views: from django.shortcuts import render def index(request): return render(request, 'testme.html') def testapp(request): return render(request, 'testme.html') test2 views: from django.shortcuts import render def index(request): return render(request, 'testme.html') def testapp(request): return render(request, 'testme.html') testme.html: <a href = {% url 'testapp' %}>Test … -
Django setting media storage in settings issue
In my development.py settings I have the following: from django.core.files.storage import FileSystemStorage ... MEDIA_STORAGE = FileSystemStorage(location='/Users/myuser/myfolder') and in my staging.py settings I have this: from django_s3_storage.storage import S3Storage ... MEDIA_STORAGE = S3Storage(aws_s3_bucket_name=DOCUMENTS_BUCKET) The development.py settings file causes no issues and storing files works fine. However, importing the staging settings breaks on this line, MEDIA_STORAGE = ... so it cannot build. I had the exact same line outside the settings file, in the models.py where it's used. It worked normally. Should it be written differently if it's extracted into settings? -
IN Django IF ELSE Not Working within For Loop
for product in products: for dess in peice: for cell in sell: try: if product == dess: print(123) else: if product == sell:: print(456) else: print(nothing) except: pass i try to run this type of for loop with if else. but if 1st statement run then out from loop and not show any result. can you check what is issue ? -
Related posts by tag name
i want to show related posts by tag name However i got the error " get() returned more than one Tag -- it returned 2!" def post_detail(request,slug): post=get_object_or_404(Post,slug=slug) comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date') comment_count=len(Comment.objects.filter(post=post, statusc=2)) tag=get_object_or_404(Tag,post=post) related_item=Post.objects.filter(tag__tag_name__icontains=tag.tag_name,status=2).order_by('-created_date').distinct()[:3] -
Changing DateTime localization in Open Edx Bitnami edition
I want to change all DateTime values inside all pages in an Open Edx system (Bitnami release Ironwood 2.0) to Persian format. I found two ways to do that: 1- Add a new python module called 'django-jalali-date' at https://github.com/a-roomana/django-jalali-date, and also follow the instructions prepared at https://openedx.atlassian.net/wiki/spaces/AC/pages/30965856/How+to+add+a+new+feature+to+LMS+or+Studio, section How to add a new Django app to the edX platform. 2- Using http://ui-toolkit.edx.org/utilities/date-utils/ In option 1, I copied the 'jalali_date' folder to /opt/bitnami/apps/edx/edx-platform/openedx/features/jalali_date and added ('jalali_date', None) in OPTIONAL_APPS section in /opt/bitnami/apps/edx/edx-platform/lms/envs/common.py. Then I tried to use this module in my view by: from jalali_date import datetime2jalali, date2jalali. Unfortunately, I catch Internal Server Error, which says ImportError: No module named jalali_date. In option 2, I couldn't find any relevant help, so I have no idea how to use this library. Any help would be greatly appreciated. -
Django ORM Search Multiple Conditional Query
I have a problem when I want to search my queryset with multiple conditional. In my database, the hscode saved as "0105.14.90". I need to search the hscodes with following this query "01051490". eg: >>> query = '0105.14.90' >>> HSCode.objects.filter(hscode=query) <QuerySet [<HSCode: 0105.14.90>]> >>> query = '01051490' >>> HSCode.objects.filter(hscode=query) <QuerySet []> The bad think I can do, is look like this: hscodes = [] query = '01051490' for hscode in HSCode.objects.order_by('-id'): if query.isdigit() and hscode.hscode == query: hscodes.append(hscode) elif hscode.hscode.replace('.', '') == query: hscodes.append(hscode) How can handle it with ORM only? >>> query = '01051490' >>> HSCode.objects.filter(Q(hscode=query) | Q(???)) <QuerySet [<HSCode: 0105.14.90>]> -
attributeerror 'functools.partial' object has no attribute '__name__'
am using django 2.2 and python 3.7, am trying to make a decorators.py function called ajax required and am getting this error on the cmd once i run the server attributeerror 'functools.partial' object has no attribute 'name' decorators.py from django.http import Http404 def ajax_required(function): def wrap(request, *args, **kwargs): if not request.is_ajax(): raise Http404 return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap -
Finding APIs in Django projects
I am new to the use of APIs, so kindly ignore if something sounds unusual. I have been shared a Django project and I need to modify some of the API whose URL is given to me. I tried looking at urls.py and found some URL matching with those that need to be modified. How to find other APIs in my Django project? -
When I PATCH a Boolean field, the update is reflected in the database but not the JSON output, why? (Django Rest Framework Serializer)
Assuming I have to override the update method in DRF's ModelSerializer - whenever I run PATCH to update a Boolean field from False to True, it will not be reflected in the JSON output. But when I check it is reflected in the SQLite database. Then, I run PATCH or GET to query data again, only then will the change show in the JSON output. Why does this happen and is there a way for the change to be reflected in the JSON body output immediately? The code below shows a stripped down version of my JobSerializer class. class JobSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ( 'slug', 'student', 'service', 'time_slots', 'tutor_accept', ) def update(self, instance, validated_data): instance.tutor_accept = validated_data.get('tutor_accept', instance.tutor_accept) instance.save() return instance -
Django management for authentication session
I am researching into how I can use Django to manage the authentication session of users. I am new to the topic, so I would really appreciate as many details as you can provide. Basically, I will have some users logging in with the company credentials (username and password). Then, Django gets the "OK" from SecAuth and then I need to figure out how to manage the user session, once they are in. Specifically, the top 2 things I need to find out are how to: Manage token life cycle in Django Manage permissions to certain APIs in Django Optionally, if anyone can assist, I need to find out how to: Support some APIs without authentication Lock down other APIs with authentication Lock GUI down as per APIs Thank you very much in advance! :) -
The included URLconf "" does not appear to have any pattern in it
I have looked at other answers to this question, but i still can't figure out what's wrong. Indeed, my projects works on Ubuntu and Fedora but I have to deploy my script on a Debian and that's where I get the error message >Exception in thread django-main-thread: >Traceback (most recent call last): > File "/var/rails/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns > iter(patterns) >TypeError: 'module' object is not iterable > >During handling of the above exception, another exception occurred: > >Traceback (most recent call last): > File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner > self.run() > File "/usr/lib/python3.5/threading.py", line 862, in run > self._target(*self._args, **self._kwargs) > File "/var/rails/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper > fn(*args, **kwargs) > File "/var/rails/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run > self.check(display_num_errors=True) > File "/var/rails/venv/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check > include_deployment_checks=include_deployment_checks, > File "/var/rails/venv/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checks > return checks.run_checks(**kwargs) > File "/var/rails/venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checks > new_errors = check(app_configs=app_configs) > File "/var/rails/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config > return check_resolver(resolver) > File "/var/rails/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver > return check_method() > File "/var/rails/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in check > for pattern in self.url_patterns: > File "/var/rails/venv/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__ > res = instance.__dict__[self.name] = self.func(instance) > File "/var/rails/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line … -
Why Django couldn't find an object with given slug?
Django tells that the object with given slug could not be found (i.e. 404 code). Though queryset returned isn't empty class PollDetailView(RetrieveAPIView): serializer_class = PollSerializer def get_queryset(self): slug = self.kwargs['pk'] print(Poll.objects.filter(slug=slug)) # Prints '<QuerySet [<Poll: ddd>]>' reaching '/api/poll/ddd/' url return Poll.objects.filter(slug=slug) # 404 Not Found -
How do i submit mutiple crispy forms in django using one submit button?
I have two separate forms which i am trying to render in a single template. However when i am trying to submit the form, the form is not getting submitted. Is there any possible way to do this? It is working fine when i am not using crispy forms forms.py class BasicInfoForm(ModelForm): class Meta: model = BasicInfo fields = '__all__' helper = FormHelper() helper.form_class = 'form-group' helper.layout = Layout( Row( Column('name', css_class='form-group col-sm-4 col-md-4'), ), Row( Column('birthMonth',css_class='form-group col-sm-4 col-md-4'), ), Row( Column('birthYear', css_class='form-group col-sm-4 col-md-4'), ), ) class IncomeDetailForm(ModelForm): class Meta: model = IncomeDetail fields = '__all__' exclude = ['user'] helper = FormHelper() helper.form_class = 'form-group' helper.layout = Layout( Row( Column('gross', css_class='form-group col-sm-4 col-md-4'), Column('monthlyExpense',css_class='form-group col-sm-4 col-md-4'), Column('hasSavingsInvestment', css_class='form-group col-sm-4 col-md-4'), )) Views.py def getIndexDetails(request): if request.method == 'POST': print("inside post method") basicinfoform = BasicInfoForm(request.POST) if basicinfoform.is_valid(): basicinfoform.save() incomedetailform= IncomeDetailForm(request.POST) if incomedetailform.is_valid(): incomedetailform.save() <form action="." method="POST"> {% csrf_token %} {{ crispy basicinfoform }} {% crispy incomedetailform %} <input type="submit" class="btn btn-info" value="Submit Button"> </form> -
How to incorporate one API endpoint with another?
I am new to Django Rest and using API's. So, I have an existing project where I am getting estimated price from a method price_estimation_based_on_region. I want to use the result_data object from here to another method, where I am sending and saving the new inquiry in a method name save_new_inquiry. The price is coming as a response from an endpoint which I need to associate in the save_new_inquiry method. How to do this? Here are the methods: def save_new_inquiry(self, data: dict): try: LOGGER.info('GENERATE NEW INQUIRY=======================') time_services = TimeServices() main_data = data['data'] region, address_details = self.find_region(main_data) main_data['region_id'] = region.id if region else None inquiry_serializer = InquirySerializer(data=main_data) if inquiry_serializer.is_valid(): saved_data = inquiry_serializer.save() saved_data.from_address_zip_code = address_details['postal_code'] saved_data.save() send_email = EmailServices() data = self.formatting_data_for_api_call(main_data) if region: response = API(domain=region.region_company_ids.first().db_name, method_name='query-form', data=json.dumps(data), token=FB_CONFIG['apiKey']).execute(TYPE.POST) LOGGER.info(response.text) if response.status_code == 200: response_data =json.loads(response.text) saved_data.gen_qid = response_data.get('gen_qid','') saved_data.order_id = response_data.get('id','') saved_data.link_hits = region.region_company_ids.first().db_name saved_data.is_associated_company = True saved_data.save() send_email.email_send_to(email=[data['customer_email']], subject="Takk for henvendelsen din!", template='email_inquiry.html', context={}, source='BusGroup <no-reply@busgroup.no>') def price_estimation_based_on_region(self, data: dict): try: region,address_details =self.find_region(data) time_services = TimeServices() main_submission = { "passenger": data.get('passenger',0), "order_type": data.get('order_type','Single'), "bus_availability": data.get('availability','False'), "departure_datetime": time_services.convertUserTimeToUTCwithFormat( time=data.get('departure_datetime', ''), input_format='%d.%m.%Y %H:%M', output_format='%Y-%m-%d %H:%M:%S', tz_time='Europe/Oslo'), "return_datetime": time_services.convertUserTimeToUTCwithFormat( time=data.get('return_datetime', ''), input_format='%d.%m.%Y %H:%M', output_format='%Y-%m-%d %H:%M:%S', tz_time='Europe/Oslo'), "from_address": data.get('from_address',''), "from_address_latlng": data.get('from_address_latlng',''), "to_address": … -
Live Scoreboard implementation in Django
I have to create a Live Scoreboard in Django for a game. The game will have 5 players and each of them will receive a score between -5 to 25 every round. The game will have multiple rounds and I want to display their total score(sum of scores up to the latest round) after every round on a scoreboard page that they can connect to from their devices.Being able to store every game after it ends would be an added bonus. I want to know how I could implement this -
Django url Error. Debug returns NoReverseMatch
I'm trying to make a link to the admin page (localhost:8000/admin), but when trying to link like this: Html: {% if user.is_staff %} <a class="nav-item nav-link" href="{% url 'admin' %}">Admin</a> {% endif %} Code: urlpatterns = [ path('admin/', admin.site.urls, name='admin'), ] I get an error saying NoReverseMatch at /. Traceback: File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\base.py" in _get_response 143. response = response.render() File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\response.py" in rendered_content 83. content = template.render(context, self._request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 171. return self._render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\loader_tags.py" in render 150. return compiled_parent._render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\defaulttags.py" in render 309. return nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\defaulttags.py" in render 443. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\urls\base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) … -
I am not able to use "python manage.py dbshell" in visual code
I have installed sq-lite program in my local machine & set environment variables also. After that I am able to use "python manage.py dbshell" in command line but when using same command in visual code it showing error "CommandError: You appear not to have the 'sqlite3' program installed or on your path." I have attached screenshot also for reference. In environment variables I have added "c:\sqlite" into path variable. dbshell_error_screenshot -
ManyToManyField Self object lis comes up as empty in the Admin panel of Django
I've got a Model object of Document that has a number of fields that link to itself. However, when creating a new object from the admin page, or editing an existing one, the list of linked Documents come up as empty. Other ManyToManyFields that are in the same object seem to be fine, and list the right content. I tried changing the related_name filter and play around with symmetrical and even changed self to Document,it still comes up as an empty list (I have other Document objects already created, so the object list is not empty) Note: I can tell they still link to Document as when I click the little plus button to add a document inside the document (recursive add), the pop up I get is for another Document with the right fields. Screenshot How can I get a list Document objects to link in object Document? Am I doing anything wrong? Thank you for your help. class Document(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) document_content = models.TextField(blank=True, null=True) file_date = models.DateField(blank=True, null=True) file_text = models.TextField(blank=True, null=True) parent_document = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) #The ones below do not show up anything, show up as empty boxes. related_checklist … -
How to create a search function on a class-based list view?
I am trying to create a search function based on the title of my posts. Right now I am trying to implement this search using a filter but the list view is not rendering. I am unsure if I should implement a URL for my search function. This is my model: class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.ManyToManyField(Feedback) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) This is my class-based list view: class PostListView(ListView): model = Post template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html context_object_name = 'post' ordering = ['date_posted'] paginate_by = 12 def get_queryset(self): try: title = self.kwargs['title'] except: title = '' if (title != ''): object_list = self.model.objects.filter(title__icontains = title) else: object_list = self.model.objects.all() return object_list This is my search bar: <div id="search"> <form method='GET' action=''> <input type="text" name='q' placeholder=""> <button id='search_holder'> <img src="/static/store/search_icon.gif" id="search_icon"> </button> </form> </div> This is my html that is rendering the posts: {% extends "store/base.html" %} {% block content %} {% include "store/home_ext.html" %} <div style="padding-top: 20px;" id="main" > <section class="text-center mb-4"> <div class="row" id="random"> {% for post in posts %} … -
how to configure autocomplete_light in django 2.2?
I tried to configure autocomplete_light for django2.2 but i'm getting some errors its because for django version i guess. Initially it was related to render() got an unexpected keyword argument 'renderer' this got fixed by adding "renderer=None" in render function in widgets.py. After that this error, from django.core import urlresolvers its depreciated in django 2.2. So i used, from django.urls import reverse(in base.py). then the error changed to "function' object has no attribute 'NoReverseMatch'". autocomplete_light_registry.py from autocomplete_light import shortcuts as autocomplete_light from django.db.models import Q from assets.models import Dealer class DealerAutocomplete(autocomplete_light.AutocompleteModelBase): autocomplete_js_attributes = { 'placeholder' : 'Region' } attrs={ 'placeholder':'Region', 'class':'form-control', 'data-autocomplete-minimum-characters': 1, } def choices_for_request(self): q = self.request.GET.get('q','') choices = self.choices.filter(is_deleted=False) if q: choices = choices.filter(Q(region__istartswith=q)) return self.order_choices(choices)[0:self.limit_choices] autocomplete_light.register(Dealer, DealerAutocomplete) forms.py class DealerForm(forms.ModelForm): class Meta: model = Dealer fields = ('region','dealer_name','type_dealer','address','loc_latitude','loc_longitude','mobile','phone','email') widgets = { "region": autocomplete_light.ChoiceWidget('DealerAutocomplete'), 'dealer_name' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Dealer name'}), 'type_dealer' : forms.Select(attrs={'class':'form-control', 'placeholder':'Dealer Type'}), 'address' : forms.Textarea(attrs={'class':'form-control', 'placeholder':'Address'}), 'loc_latitude' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Location Latitude'}), 'loc_longitude' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Location Longitude'}), 'mobile' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Mobile'}), 'phone' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone'}), 'email' : forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}) } What i want know whether autocomplete_light works in django2.2 or is there any issues in my code. Please correct or pointed out the mistakes. -
django admin forms.ModelForm validation for blank IntegerField
How can you make it in django admin so that when you click save if the forms.IntegerField is blank to return a validation error?. Currently if you save the model it will still accept the transaction. Any suggestions? class CarInlineForm(forms.ModelForm): car_type = forms.CharField(disabled=True) car_qty = forms.IntegerField(min_value=1) class Meta: model = Car exclude = ['created'] class CarInline(admin.TabularInline): model = CarOrderItem extra = 1 max_num = 1 form = CarInlineForm exclude = [ 'created', ] class CarAdmin(admin.ModelAdmin): inlines = [CarInline] -
I need an real-life project for practice with python and Django
I'm working as an apprentice for a software company in Germany. The most time I work for projects with Visual Basic for Application (Excel). For my finals I need more practice in modern languages. I like to build a web-application for free, can be a little project or something bigger, the important thing is that I learn a few things about planing a project, speaking with the customer about the project and build the application. Why Python and Django? Aside from VBA, I learned Python for my own projects. But writing application for myself is not the same like working for a customer. Best Regards, Tobias.M -
How to link multiple form with primary key?
I am trying to create one to many relationship in django forms , in which i have created one customer with id , and i want to use information of that customer to create new form models.py from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender = models.CharField(max_length=50); class Ipd(models.Model): Presenting_complaints = models.CharField(max_length=300); Reason_admission = models.CharField(max_length=300); patient = models.ForeignKey('Patient',on_delete=models.CASCADE forms.py from django.forms import ModelForm from django import forms from .models import Patient,Ipd class PatientForm(ModelForm): OPTIONS = ( ('',''), ('Doctor1','Doctor1'), ('Doctor2','Doctor2'), ) OPTIONS2 = ( ('Male', 'Male'), ('Female', 'Female'), ) Gender= forms.TypedChoiceField(required=False, choices=OPTIONS2, widget=forms.RadioSelect) consultant = forms.ChoiceField(choices=OPTIONS) class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm (ModelForm): patient = Patient.objects.all() class Meta: model = Ipd fields = ('Presenting_complaints','Reason_admission', 'patient') def save(self, commit=True): instance = super().save(commit) # set Car reverse foreign key from the Person model instance.patient_set.add(self.cleaned_data['patient']) return instance views.py @login_required def new(request): if request.POST: form = PatientForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Patient is successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = PatientForm() return render(request, 'new.html', {'form':form}) … -
"How to display DOC file on web page in django"
Problem is when I upload any doc file on the website it will display on my web page as HTML view of doc file format