Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change object through views in Django?
I'm trying to get the login_attempts number in my object to count down after unsuccessful login attempts. So every time someone sends the incorrect username and password via POST the number would go down up to 0 and then they would get error message. Thanks in advance -
Django default queryset values shorthand
I am initializing variables to None as default value. If the queryset returns no objects then the program will not fail. Is there a shorter method on this? Thanks qs_data = { 'flal_id_no' : None, 'mail_id_no' : None, 'subject_id_no':None, 'pdsbj_id_no':None, } qs = vFileAllocation.objects.values().filter(track_id_no=get_track_id_no)[0] if qs: qs_data['flal_id_no'] = qs['flal_id_no'] qs_data['mail_id_no'] = qs['mlal_id_no'] qs_data['subject_id_no'] = qs['subject_id_no'] qs_data['pdsbj_id_no'] = qs['pdsbj_id_no'] -
Retrieving the actual file from a http request (for os.stat)
I'd like to retrieve the meta data of an uploaded file by use of: st = os.stat(file_path) However I'm not sure how to parse the file_path attribute from the http request. For example, I've used: request.FILES but then get: TypeError: stat: path should be string, bytes, os.PathLike or integer, not MultiValueDict I also serialize the request, like so: serializer = FileSerializer(data=request.data) How do I get the actual uploaded file in the http reques? -
Http Referer header changed after first load
So I have a django application and it's acting weirdly as for the first call the http_referer is correct but from the next call even for the static files the referer is changed to the current domain. -
How to compare date field with None in django ORM?
I have a model where there is a Date field. I'm trying to query the model by passing date object or a null value. The query should behave in different ways based on the input provided in ORM query. I'll be passing two variables to ORM query st_date and exp_date. exp_date can be None sometimes. I need to query the model and fetch all the records which has the expiration_date greater than provided exp_date if there is some value in exp_date. If not, it should not consider the filter at all. models.py: class DtModel(models.Model): scheduled_start_date = DateField() scheduled_end_date = DateField() ORM query: st_date="2020-05-01" exp_date=None DtModel.objects.filter(scheduled_start_date__gte=st_date, scheduled_end_date__lte=exp_date) It's throwing an error when the exp_date is null when it tries to compare None and date field? ValueError: Cannot use None as a query value -
unable to retrive data in crud operation
{%for x in read%} {%if request.user == user%} <div class="card " > <h5> <div class="card-header bg-info"> Dr.{{i.name}} </div> </h5> <div class="card-body"> <h6 class="card-title ">Appointment Date : {{x.appoinment_date}}</h6> <h6 class="card-title">Age : {{x.age}}</h6> <h6 class="card-title">Digree : {{x.disease}}</h6> <h6 class="card-title">Email : {{x.email}}</h6> </div> </div> {%endif%} {%endfor%} i am using code below but i am getting data of all users instead of current user -
Direct assignment to the forward side of a many-to-many set is prohibited. Use fieldname.set() instead
Custom User Model from django.db import models # from roles_tasks.models import mst_org_roles # from organizations.models import config_orgs # from projects.models import mst_projects from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class UserManager(BaseUserManager): def create_user(self,email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None, is_admin=False, is_staff=False): if not email: raise ValueError("email id is required") if not password: raise ValueError("password must required") if not first_name: raise ValueError("first_name is required") if not last_name: raise ValueError("last_name is required") if not role_id: raise ValueError("role_id is required") if not org_id: raise ValueError("org_id is required") if not status: raise ValueError("status is required") if not created_by: raise ValueError("created_by is required") if not modified_by: raise ValueError("modified_by is required") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name=first_name user_obj.last_name=last_name user_obj.role_id=role_id user_obj.org_id=org_id user_obj.project_id=project_id user_obj.status=status user_obj.created_by=created_by user_obj.modified_by=modified_by user_obj.admin=is_admin user_obj.staff=is_staff user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=False, is_staff=True ) return user def create_superuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=True, is_staff=True ) return user Status = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ('Deleted', 'Deleted') ] class User(AbstractBaseUser): username = None last_login = None email=models.EmailField(max_length=255,unique=True) admin=models.BooleanField(default=False) staff=models.BooleanField(default=False) first_name=models.CharField(max_length=200) last_name=models.CharField(max_length=200) role_id = models.ForeignKey('roles_tasks.mst_org_roles', … -
Half Hours choice fields for TimeField in Django model
I want to have field choice in form that user can pick hours with half hours choice. I have this model and this TimeField: class Sample: start_time = models.TimeField(choices=global_vars.TIME_MAP_HALF_HOURS_CHOICES,) I want to show half hours time to customer. This is my Choices: TIME_MAP_HALF_HOURS_CHOICES = ( (datetime.time(00, 00, 00), '00:00'), (datetime.time(00, 30, 00), '00:30'), (datetime.time(1, 00, 00), '01:00'), (datetime.time(1, 30, 00), '01:30'), (datetime.time(2, 00, 00), '02:00'), (datetime.time(2, 30, 00), '02:30'), (datetime.time(3, 00, 00), '03:00'), (datetime.time(3, 30, 00), '03:30'), (datetime.time(4, 00, 00), '04:00'), (datetime.time(4, 30, 00), '04:30'), (datetime.time(5, 00, 00), '05:00'), (datetime.time(5, 30, 00), '05:30'), (datetime.time(6, 00, 00), '06:00'), (datetime.time(6, 30, 00), '06:30'), (datetime.time(7, 00, 00), '07:00'), (datetime.time(7, 30, 00), '07:30'), (datetime.time(8, 00, 00), '08:00'), (datetime.time(8, 30, 00), '08:30'), (datetime.time(9, 00, 00), '09:00'), (datetime.time(9, 30, 00), '09:30'), (datetime.time(10, 00, 00), '10:00'), (datetime.time(10, 30, 00), '10:30'), (datetime.time(11, 00, 00), '11:00'), (datetime.time(11, 30, 00), '11:30'), (datetime.time(12, 00, 00), '12:00'), ) But When I want to save object, the form not validate and raise error: Choose a valid option. How can I fix this error? -
get() returned more than one Post : return 2
i was trying to make like button for my django blog but i'm getting error while hitting like the error is get() returned more than one Post -- it returned 2! here is my code views.py class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): obj.likes.add(user) return url_ models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True,related_name='post_likes') content = models.TextField() img = models.ImageField(upload_to='pics',blank=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('LoveTravel-Details', kwargs={'pk': self.pk}) urls.py path('blog/<int:pk>/like/', PostLikeRedirect.as_view(),name='Like'), -
Python Django Model Commit behaviour?
My model class is Document as below. I want to update all status to 'Superseded' for every new or update record based 'DocumentNo' field to database. I succeeded to achieve this goal, But Please explain me if any error occurred on save will commit to database or not ? will these save method behave like database transaction ? class Document(models.Model): DocumentNo = models.CharField(max_length=100) Rev = models.CharField(max_length=10) Description = models.TextField(max_length=500) Area = models.CharField(max_length=100,blank=True,null=True) ReceivedDate = models.DateField() Status = models.CharField(max_length=20,choices=[('Current','Current'),('Superseded','Superseded')],default='Current') class Meta: constraints=[ models.UniqueConstraint(fields=['DocumentNo', 'Rev'], name='unique_document'), ] indexes=[ models.Index(fields=['Area','Status']) ] ordering=[ 'DocumentNo', 'Rev' ] def __str__(self): return self.DocumentNo + ' (' + self.Rev +')-Status: ' + self.Status def save(self, *args, **kwargs): existing_documents=Document.objects.all().filter(DocumentNo=self.DocumentNo) for doc in existing_documents: doc.Status='Superseded' doc.saveIndividual() super().save(*args, **kwargs) def saveIndividual(self, *args, **kwargs): super().save(*args, **kwargs) ``` -
django all fields not appearing in admin form
I have following model in django: class ProjectScheme(models.Model): name = models.CharField(max_length=250, blank=False,null=False) parent_scheme_id = models.ForeignKey(ProjectSchemeMaster, on_delete = models.CASCADE) rule = models.TextField(blank=True) created_on = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.IntegerField(blank=True,null=True) updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.IntegerField(blank=True,null=True) def __str__(self): return str(self.name) And in admin.py # Register your models here. class ProjectSchemeAdmin(admin.ModelAdmin): exclude = ('id',) class Meta: model = ProjectScheme admin.site.register(ProjectScheme, ProjectSchemeAdmin) But date fields: updated_on, created_on don't show up on admin form. I also tried without ProjectSchemeAdmin class, and also: class ProjectSchemeAdmin(admin.ModelAdmin): pass But the same. I need to get all the fields in admin form. -
create log file in specific directory django
in my server's root directory i have lrwxrwxrwx 1 root root 7 Jul 11 2018 bin -> usr/bin dr-xr-xr-x. 6 root root 4096 Apr 17 02:41 boot drwxr-xr-x. 2 root root 87 Dec 19 08:15 bundle drwxr-xr-x 16 root root 2680 May 4 05:00 dev drwxr-xr-x. 134 root root 8192 May 4 05:00 etc drwxr-xr-x. 10 root root 4096 May 1 08:20 home lrwxrwxrwx 1 root root 7 Jul 11 2018 lib -> usr/lib lrwxrwxrwx 1 root root 9 Jul 11 2018 lib64 -> usr/lib64 drwxr-xr-x. 2 root root 6 Apr 11 2018 media drwxr-xr-x. 2 root root 6 Apr 11 2018 mnt drwxr-xr-x. 3 root root 25 Apr 11 2018 opt dr-xr-xr-x 150 root root 0 May 4 05:00 proc dr-xr-x---. 10 root root 4096 May 4 10:01 root drwxr-xr-x 42 root root 1340 May 4 05:00 run lrwxrwxrwx 1 root root 8 Jul 11 2018 sbin -> usr/sbin drwxr-xr-x. 2 root root 6 Apr 11 2018 srv dr-xr-xr-x 13 root root 0 May 4 08:56 sys drwxrwxrwt. 12 root root 98304 May 4 09:58 tmp <-- i want to create logs inside this directory drwxr-xr-x. 13 root root 155 Jul 11 2018 usr <-- my file is located … -
Django without any Default Migration setting
I am going to build a simple API without auth and admin application. Is there anyway to exclude the all the build-in table? I tried to annotate all the default setting however I can't run the server. # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', -
Could not retrieve AJAX request data value in Django view function
I have an AJAX request to pull some data from post model"I am using Django3 and python 3.8". When I print the request.GET.get to the console, I got "None". There was no Data. However, when I alert the passed data in javascript I got the right value. I could not figure out which portion of my code should be tweak a little bit to work. Here is the AJAX call: <script type="text/javascript"> // to submit the get request and prevent the default submission $(document).on('click', '#post-det', function(e) { e.preventDefault(); var post_id = $(this).children(':first-child').text(); var post_id = parseInt(post_id); alert(post_id); $.ajax({ 'type':'GET', 'url': "{% url 'get_post_details' %}", 'data':post_id, 'processData': false, 'cache':false, 'contentType': false, 'dataType': 'json', csrfmiddlewaretoken:'{{ csrf_token }}', success: function(data) { alert(data) }, }); }); </script> I got "2" for the post_ID However, I could not retrieve it in Django view function. Here is the view function: def post_details(request): if request.method == 'GET' and request.is_ajax: post_id = request.GET.get('data') print("this is to check if the post_id is passed", post_id) print(request.GET.get) data = GetPostDetails(post_id) data = json.dumps(str(data)) return JsonResponse(data, safe=False) return JsonResponse({"error": "there was an error"}, status=status.HTTP_400_BAD_REQUEST) The print function print this line. this is to check if the post_id is passed None <bound method … -
Cannot create links to some allauth files which I changed
I customized the 'allauth' password_reset and password_change files and my file structure looks like: Templates _account ____login ____logout ____password_reset ____password_change The problem is I cannot create links to those two files (but I can create links to the other files in the same folder. For example: <a href="{% url 'account_login' %}">Login</a> works, but <a href="{% url 'account_password_reset' %}">Reset Password</a> doesn't. The error I get is: NoReverseMatch at /accounts/login/ Reverse for 'account_password_reset' not found. 'account_password_reset' is not a valid view function or pattern name. I've tried a lot of things but just can't figure it out. Any help would be greatly appreciated. Thank you. -
Django/JavaScript button click shows value - reload page removes value
I'm creating a game in Django more specifically in oTree with a Django Template Language and JavaScript frontend. When I click a button a value needs to be shown (got that covered) this is done with some JavaScript. But when I refresh/reload the page I need that value to still be displayed and not click the button all over. Does anybody know if there is a workaround for this in either Django or JavaScript? -
How to stop django from generating empty csv file
with open(file_name, 'w') as output_file: data = campaign_dict try: writer = csv.DictWriter(output_file, data[0].keys()) writer.writeheader() writer.writerows(data) except: pass with open(file_name, 'r') as myfile: response = HttpResponse(myfile, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+file_name return response Above code was used to generate and download csv file in django.But also django generate empty file and download .I want to stop file from downloading if file is empty.. -
ModelForm in Django not saving anything
I am making a twitter clone app in Django. I have a model, and a modelform as so: Class Tweet(models.Model): content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) class TweetForm(forms.ModelForm): class Meta: model = Tweet fields = ['content',] def clean_content(self): content = self.cleaned_data.get('content') if len(content) > MAX_TWEET_LENGTH: raise forms.ValidationError('This tweet is too long') I have a view for this: def tweet_create_view(request, *args, **kwargs): if request.method == 'POST': form = TweetForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() form = TweetForm() context = { 'form': form } return render(request, 'components/form.html', context) and the template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary" type="submit">Save</button> </form> When I submit the form data, in the database the value is shown as NULL, even if I pass in some text. What am I doing wrong?? -
Get some infomation from crawler service by scrapy
I have a crawler service that crawl some website on google , now i want to write scipt that take a domain from that crawler service, can i do that and how , tks you , can i use the python requests to get the url of scrapy service and get that domain data import requests r = requests.get("scrapy url") Can i use example like this , tks you -
'EACCES' error for django dumpdata on heroku
I want to copy the database from heroku to import into my local development environment. In the past I've done this with: heroku run python manage.py dumpdata -- > data.json However when I run this command now I get the following message: Running python manage.py dumpdata on [[projectname]]... up, run.5450 (Free) internal/fs/utils.js:230 throw err; ^ Error: EACCES: permission denied, write at writeSync (fs.js:599:3) at SyncWriteStream._write (internal/fs/sync_write_stream.js:24:3) at doWrite (_stream_writable.js:442:12) at writeOrBuffer (_stream_writable.js:426:5) at SyncWriteStream.Writable.write (_stream_writable.js:317:11) at Dyno.ondata (_stream_readable.js:695:22) at Dyno.emit (events.js:310:20) at addChunk (_stream_readable.js:286:12) at readableAddChunk (_stream_readable.js:268:9) at Dyno.Readable.push (_stream_readable.js:209:10) { errno: -13, syscall: 'write', code: 'EACCES' } From looking around it seems that this error has to do with a not properly logged in heroku CLI. However, I am logged in and can run other commands such as heroku run python manage.py shell etc. Anybody have a clue what's going wrong? -
Override POST in CreateAPIView
In my django app I have two models i.e. Package and Address Models.py class Package(models.Model): sender_name = models.CharField(max_length=255, default=0) sender_company = models.CharField(max_length=255, blank=True, null=True) sender_phone = models.CharField(max_length=255, default=0) sender_city = models.CharField(max_length=255, default=0) sender_state = models.CharField(max_length=255, default=0) sender_country = models.CharField(max_length=255, default='India') ... class Address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, default=0) city = models.CharField(max_length=255, default=0) state = models.CharField(max_length=255, default=0) country = models.CharField(max_length=255, default='India') I am overriding the post method in my CreateAPIView like the following: class package(APIView): permission_classes = (permissions.IsAuthenticated,) def post (self, request, format=None): ... if serializer.is_valid(): serializer.save() print("s data", serializer.data) Address.objects.create(user=request.user.id, name=request.data["name"], city = request.data["city"]...) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is there any other way to save Address from package model when a Package object is created ?? -
Python MongoDB ReferenceError: weakly-referenced object no longer exists
I am an error ReferenceError: weakly-referenced object no longer exists in my code, I have tried to debug it that I don't know why am I getting this. I am using mongodb and python 3.6.10 here is my code, please help a = 't1' b = ['v1', 'v2', 'v3'] services = dict() for value in b: record = MyModel.objects.filter(myid=id, a=a, value=value).first() keys = record['services'].keys() for key in keys: key_value = record['services'][key] if key in services: services[key].extend(key_value) # Getiing error here in this line else: services.update({key: key_value}) print(services) MyModel looks like { "myid" : "1", "a" : "t1", "b" : "v1", "services" : { "service_1" : [ { "serviceid" : "1012", "service_type" : "service_1" } ] } { "myid" : "1", "a" : "t1", "b" : "v2", "services" : { "service_2" : [ { "serviceid" : "1013", "service_type" : "service_2" } ] } code works fine if there is only one value in b, but if code iterate the second time and tries to perform services[key].extend(key_value), code generates the error. -
How to build a django model to store twitter conversations?
I'm building a tool, that gets user timeline tweets and their responses and I need to find out how to store those conversations in a database to render them afterwards in a template. To get a conversation, I use a while loop, that gets 'in_reply_to_status_id' of a tweet, then retrieves the status object of this reply by the id, finds its 'in_reply_to_status_id' etc till the whole conversation gets retrieved. This is the code I use: conversation = [] while True: response = api.get_status(id=tweet_id, tweet_mode='extended')._json if response['in_reply_to_status_id'] == None: break else: message_dict = {} message_dict['author'] = response['user']['screen_name'] message_dict['text'] = response['full_text'] message_dict['created_at'] = response['created_at'] message_dict['author_profile_url'] = response['user']['profile_image_url'] conversation.append(message_dict) tweet_id = response['in_reply_to_status_id'] if len(conversation) == 0: return None return reversed(conversation) In my models.py I have a Tweet model and I need to find out how to make a model that stores the whole conversation/dialogue/thread retrieved by the script above. Also, it should be possible to render the conversation as a simple chat dialogue afterward. My first thought was to add "replies" field to my Tweet model and store the conversation as a JSON but this doesn't look like the right solution to me. -
How to use ManytoMany relationship in django custom user model?
My Custom User Model from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class UserManager(BaseUserManager): def create_user(self,email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None, is_admin=False, is_staff=False): if not email: raise ValueError("email id is required") if not password: raise ValueError("password must required") if not first_name: raise ValueError("first_name is required") if not last_name: raise ValueError("last_name is required") if not role_id: raise ValueError("role_id is required") if not org_id: raise ValueError("org_id is required") if not status: raise ValueError("status is required") if not created_by: raise ValueError("created_by is required") if not modified_by: raise ValueError("modified_by is required") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name=first_name user_obj.last_name=last_name user_obj.role_id=role_id user_obj.org_id=org_id user_obj.status=status user_obj.created_by=created_by user_obj.modified_by=modified_by user_obj.admin=is_admin user_obj.staff=is_staff user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=password, is_admin=False, is_staff=True ) return user def create_superuser(self,email,first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=password, is_admin=True, is_staff=True ) return user Status = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ('Deleted', 'Deleted') ] class User(AbstractBaseUser): username = None last_login = None email=models.EmailField(max_length=255,unique=True) admin=models.BooleanField(default=False) staff=models.BooleanField(default=False) first_name=models.CharField(max_length=200) last_name=models.CharField(max_length=200) role_id = models.ForeignKey('roles_tasks.mst_org_roles', on_delete=models.DO_NOTHING) org_id = models.ForeignKey('organizations.config_orgs', on_delete=models.DO_NOTHING) project_id = models.ManyToManyField('projects.mst_projects', blank=True) status = models.CharField(choices = Status, default = 'Active', max_length = 15) … -
So, im doing the updation in my django project and i'm getting a error for reverse match
THE ERROR IS-- NoReverseMatch at /updatemedicine/2 Reverse for 'updatemedicine' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['updatemedicine/(?P<pk1>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/updatemedicine/2 Django Version: 2.2.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'updatemedicine' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['updatemedicine/(?P<pk1>[0-9]+)$'] Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['D:\\django project\\admin4', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\lenovo\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\Pythonwin'] MY HTML CODE IS === {% extends 'Pharmacetical/homepage.html' %} {% block content %} <div class="box box-warning"> <div class="box-header with-border"> <h3 class="box-title">Add Medicines Here</h3> </div> <!-- /.box-header --> <div class="box-body"> <form role="form" method="POST" action="{% url 'updatemedicine' pk1=med.pk1 %}" enctype="multipart/form-data"> <!-- text input --> {% csrf_token %} <div class="form-group"> <label>Disease Name</label> <select class="form-control" name="desigid"> {% for i in d %} <option value="{{ med.dsg_id }}">{{ i.diseas }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Medicine Name</label> <textarea class="form-control" rows="3" name="medname" id="" value="{{ med.medicine }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Uses</label> <textarea class="form-control" rows="3" name="uses" id="" value="{{ med.uses }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Side Effects</label> <textarea class="form-control" rows="3" name="effects" id="" value="{{ med.sideeffects }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Precautions</label> <textarea class="form-control" rows="3" name="precaution" id="" value="{{ med.precautions }}" placeholder="Enter ..."></textarea> …