Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loading an object inside an object in a Django template
So I have an object that has a foreign key of another object. Whenever I load that object into a template and access said object, I get an error. <td><a href="{% url 'agente' 'Mark' %}" target="_blank">{{ ticket.get_agente }}</a></td> int() argument must be a string, a bytes-like object or a number, not 'Agente' I even tried adding a get_id after getting the object but displays the same error. Seems like the fact that it's an object inside an object confuses Django. -
Zappa is not invoking the right Virtual env correctly while deploy
I am trying to deploy a Django app with Zappa using. I have created virtualenv using pyenv. Following commands confirms the correct virtualenv ▶ pyenv which zappa /Users/****/.pyenv/versions/zappa/bin/zappa ▶ pyenv which python /Users/****/.pyenv/versions/zappa/bin/python But when I am trying to deploy the application using zappa deploy dev following error is thrown ▶ zappa deploy dev (pip 18.1 (/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages), Requirement.parse('pip>=20.1'), {'pip-tools'}) Calling deploy for stage dev.. Oh no! An error occurred! :( ============== Traceback (most recent call last): File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 2778, in handle sys.exit(cli.handle()) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 512, in handle self.dispatch_command(self.command, stage) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 549, in dispatch_command self.deploy(self.vargs['zip']) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 723, in deploy self.create_package() File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 2264, in create_package disable_progress=self.disable_progress File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/core.py", line 627, in create_lambda_zip copytree(site_packages, temp_package_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/utilities.py", line 54, in copytree lst = os.listdir(src) FileNotFoundError: [Errno 2] No such file or directory: '/Users/****/mydir/zappa/env/lib/python3.6/site-packages' ============== You can see the line at which error is thrown is different where virtualenv is installed. I don't know why Zappa deploy is looking for the site-packages here. -
How to add a filter in django for every request?
I want to add a security filter so that every request to my django app will go through the filter first and then let the request go through if the token from the header is valid. How can I accomplish that in django? Thanks. -
Is VS code better than pycharm when starting out with Django?
I am trying to understand the best platform for a free code editor -
GET 'today' data in Django-Filter/DRF
I'm trying to get the today or yesterday data from the current day using django-filter/DRF. class SampleFilter(filters.FilterSet): start_date = DateTimeFilter(field_name='timestamp', lookup_expr='gte') end_date = DateTimeFilter(field_name='timestamp', lookup_expr='lte') class Meta: model = Sample fields = [] on my django-rest api url. when I get the data start_date=${start}&end_date=${end} for the dates of today, it returns zero data even it have in the database. "GET /api/v1/rainfall/?start_date=2021-02-02&end_date=2021-02-02 HTTP/1.1" 200 2" it is 200 success but it returns nothing. What's wrong in my code? please help. thanks! -
how to redirect “print” command and the output of the script to Django3 template?
Views.py def configure(request): all_devices = Devices.objects.all() if request.method == "POST": for i in all_devices: platform = "cisco_ios" ssh_connection = ConnectHandler( device_type=platform, ip=i.IpAdd, username=i.username, password=i.password, ) output = ssh_connection.send_command("show ip arp\n") print(output) return render(request, "configure.html", {"output": all_devices}) ======================================================================== output from the console / terminal: February 03, 2021 - 07:57:28 Django version 3.1.5, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.177 3 000c.298a.429a ARPA FastEthernet0/0 Internet 192.168.15.184 - ca01.129a.0000 ARPA FastEthernet0/0 Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.177 3 000c.298a.429a ARPA FastEthernet0/0 Internet 192.168.15.185 - ca02.1227.0000 ARPA FastEthernet0/0 Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.1 0 0050.56c0.0008 ARPA Ethernet0/0 Internet 192.168.15.2 3 0050.56ef.adc2 ARPA Ethernet0/0 Internet 192.168.15.164 100 000c.298c.2625 ARPA Ethernet0/0 Internet 192.168.15.177 3 000c.298a.429a ARPA Ethernet0/0 Internet 192.168.15.186 - aabb.cc00.3000 ARPA Ethernet0/0 [03/Feb/2021 07:57:32] "POST /configure/ HTTP/1.1" 200 1454 configure.html == Templates {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token%} {{form}} {{output}} {% endblock content %} {% block result %} {% endblock result %} I'm getting: <QuerySet [<Devices: Reflect>, <Devices: Reflect2>, <Devices: Reflect-SW>]> Thank You. -
Create HTML/JS matrix in django template
I have a view which returns this data in dictionary form: {('ACCOUNTS', 'Staff'): 8, ('ACCOUNTS', 'TOA'): 3, ('HR', 'Officer'): 4, ('HR', 'Staff'): 1} I need to convert this dictionary to a matrix in django template. something like this: please note the dictionary could be any longer. -
Why am I getting django.db.models error telling me I have no attribute for TextChoices in Django (3.1.6) and Python(3.8)?
thanks so much for reading. I've got this running on my computer no problem. It's working on my VS on Windows 10. But this error keeps coming up, it looks like TextChoices is no longer usable? AttributeError: module 'django.db.models' has no attribute 'TextChoices' I'm putting it u0p on PythonAnywhere, Python 3.8, and Django 3.1.6 I am still new at this, so please forgive me1 My issue is with the TextChoices, here is the full error: Traceback (most recent call last): File "/home/sandorf/project/listings/models.py", line 6, in <module> class Listings(models.Model): File "/home/sandorf/project/listings/models.py", line 7, in Listings class Country(models.TextChoices): AttributeError: module 'django.db.models' has no attribute 'TextChoices' This is my models.py in the app directory from django.db import models from django.utils.timezone import now from datetime import datetime # Create your models here. class Listings(models.Model): class Country(models.TextChoices): USA = "USA" CHINA = "China" CANADA = "Canada" INDIA = "India" UK = "UK" EUROPE = "Europe" MIDDLE_EAST = "Middle East" OTHER = "Other" class Topic(models.TextChoices): STATISTICS = "Statistics" VACCINE = "Vaccine" NEW_STRAINS = "New Strains" LOCKDOWN = "Lockdown" COVID_NEWS = "Covid News" title = models.CharField(max_length=745) link = models.CharField(max_length=745) summary = models.TextField(Null=False) country = models.CharField( max_length=100, choices=Country.choices, default="Country.OTHER") topic = models.CharField( max_length=100, choices=Topic.choices, default="Topic.COVID_NEWS") list_date = models.DateTimeField(default=now) … -
Display the error_messages under the fields
I'm using this package for my form https://github.com/KuwaitNET/djvue but anyway it's like a general question, I've wrote the following method to validate my phone number field def validate_phone_number(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): self.fields["phone_number"].error_messages.update({"ph":"Wrong"}) raise ValidationError(_(u'The phone number entered is not valid.')) return value and it works just fine because in my Model: def serve(self, request, *args, **kwargs): if request.method == "POST": data = json.loads(request.body) serializer = ContactUsSerializer(data=data) if serializer.is_valid(): ticket_number = serializer.save() return JsonResponse({"ticket_number": ticket_number}) else: return JsonResponse(serializer.errors) ctx = self.get_context(request, *args, **kwargs) ctx["serializer"] = ContactUsSerializer() request.is_preview = getattr(request, "is_preview", False) return TemplateResponse( request, self.get_template(request, *args, **kwargs), ctx ) and actually when I enter an invalid phone number I'm getting a JsonResponse with the error: 0: "The phone number entered is not valid." which is great, but how can I display the updated error message below the phone_number field?? it looks like despite the errors are being updated the displaying is not, should I use Vue or something to achieve that? knowing that the package I'm using does so: <span class="help-block text-danger" v-for="error in errors" :key="error">{( error )}</span> but I'm not sure how and where they render the error, so I want maybe a pure … -
How to send live video captured from opencv in django to aws kinesis-video-streams putmedia endpoint?
To achieve: capture the live feed of a camera in web browser using OpenCV and send it to AWS Kinesis-video-stream(an aws service) using PUT_MEDIA(end_point). Have referred Amazon AWS Kinesis Video Boto GetMedia/PutMedia and made a few changes to capture from camera. HTML Code to display user stream (video captured from webcam): <html> <body> <video autoplay="true" id="myVideo"></video> </body> </html> ''' **views.py** def get_endpoint_boto(): import boto3 client = boto3.client('kinesisvideo','us-east-2',aws_access_key_id = your_env_access_key_var ,aws_secret_access_key = your_env_secret_key_var) response = client.get_data_endpoint( StreamName=your_stream_name, APIName='PUT_MEDIA' ) print(response) endpoint = response.get('DataEndpoint', None) print("endpoint %s" % endpoint) if endpoint is None: raise Exception("endpoint none") return endpoint def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def get_signature_key(key, date_stamp, regionName, serviceName): kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, 'aws4_request') return kSigning def get_host_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):] return str(retv) def get_region_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):].split('.')[2] return str(retv) class gen_request_parameters: def __init__(self): self._data = '' if True: print('True') cap = cv.VideoCapture(0) cap.set(5,60) if not cap.isOpened(): exit() ret, frame = cap.read() request_parameters = cap.read() self._data = request_parameters self._pointer = 0 self._size = len(self._data) def __next__(self): print('next') if self._pointer >= self._size: raise StopIteration left = self._size - self._pointer … -
In a journal app, author adding and requests with django
With the following code, i could make a simple journal app.. but i don't know how to control the relations between authors and editor. The thing i want, The Editor must add a author to own journal. and also, authors write an article only to journal to which he/she added. Also i want, authors can send editors request for authorship. How can i construct such a system? class Journal(models.Model): journal_editor = models.ForeignKey(User,on_delete=models.CASCADE,related_name="journal_editor",default=1) unique_id = models.CharField(max_length=100, editable=False, null=True) journal_title = models.CharField(max_length=250, verbose_name="Dergi Adı", blank=False, null=True) slug = models.SlugField(null=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Dergi" verbose_name_plural = "Dergiler" ordering = ["-created"] def __str__(self): return "%s" % (self.journal_title) def get_unique_slug(self): x = 0 slug = slugify(unidecode(self.journal_title)) new_slug = slug while Journal.objects.filter(slug=new_slug).exists(): x += 1 new_slug = "%s-%s" % (slug, x) slug = new_slug return slug def save(self, *args,**kwargs): if self.id is None: new_unique_id = str(uuid4()) self.unique_id = new_unique_id self.slug = self.get_unique_slug() else: journal = Journal.objects.get(slug=self.slug) if journal.journal_title != self.journal_title: self.slug = self.get_unique_slug() super(Journal, self).save(*args,**kwargs) class Article_of_Journal(models.Model): author_of_article = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name="author_of_article") journal_name = models.ForeignKey(Journal,on_delete=models.CASCADE,default=1,related_name="journal_name") unique_id = models.CharField(max_length=100,editable=False,null=True) article_title = models.CharField(max_length=250,verbose_name="Başlık",blank=False,null=True) article_content = RichTextUploadingField(null=True,blank=False,verbose_name="İçerik") slug = models.SlugField(null=True,unique=True,editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Makale" verbose_name_plural … -
How to iterate ManyToMany filed in serializer class
I have this Event model: # models.py class Event(models.Model): name = models.CharField(max_length=200)) user = models.ManyToManyField(User)) This is my ListCreateAPIView class: class EventListView(LoginRequiredMixin, generic.ListView): model = Event This is my ListCreateAPIView class: class Events(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Event.objects.all() serializer_class = EventSerializer This is my serialiser class: #serializers,py class EventSerializer(serializers.ModelSerializer): class Meta: fields = ( ‘id', 'name', 'user', ) model = Event And this is my REST request response: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "name": "My event1", "user": [ 1, 4 ], "registered": true // <—- I NEED THIS }, { "id": 2, "name": "Other event", "user": [ 2, 4, 6 ], "registered": false // <—- I NEED THIS } ] } What I am gonna need in REST response is property “registered”, which will contain true or false if current user is registered on particular event or not. My approach was to control if current user is in list of users of event. I tried to get this information in serialiser class this way: #serializers,py class EventSerializer(serializers.ModelSerializer): registered = serializers.SerializerMethodField(‘_user’) def _user(self, obj): request = getattr(self.context, 'request', None) if request.user in self.user: return True else: return False class Meta: fields = ( … -
Django: Parent model contain a list child model like a custom template
I'm a newbie Django. Example: I have a parent model Project, child model Phase like this: class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) ... def __str__(self): return self.name class Phase(models.Model): phase_id = models.AutoField(primary_key=True) phase_name = models.CharField(max_length=300, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) ... def __str__(self): return self.phase_name Question 1: How can I create a custom template is a list of Phase when user create new Project? New Project A: Phase 1 Phase 2 Question 2: And when user change a custom list of Phase, how can I store list and reuse it with another new Project? List Phase Custom: (edit phase: + Phase 3, + Phase 4, - Phase 2) Phase 1 Phase 3 Phase 4 New Project B: Phase 1 Phase 3 Phase 4 Any link references or document relate it? Thank you! -
How to generate models with another model's primary key as the model name in Django
I am working on a django project where the website will let the user to register for an event and let them check in. models.py contains: class Event(models.Model): eventName = models.CharField(max_length=264, unique=True) # Event Name eventDescription = models.TextField() # About the Event I want the program to generate more models with the eventName attribute row values from Event model. Example: Consider that Event model consists of the following row values: CodeChef | CodeChef annual Event GSOC | Google Summer Of Code Then I want the following models to be automatically generated with some predefined attributes (number of attendees, EventStatus): class CodeChef (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) class GSOC (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) PS: I am a beginner to Django. -
Uncaught TypeError: Cannot read property 'replace' of undefined using PostgreSQL database and django
I am getting the following error when I click on a marker deployed from my PostgreSQL database onto a google map. I am expecting an info modal to pop up and show some information. The information that should show up is being posted to the database from a form on my website via an AJAX call. The marker shows up in the correct position but I get this error when I click it: Uncaught TypeError: Cannot read property 'replace' of undefined Here is my AJAX call that posts the data: const commitNewCafe = function () { let name = document.getElementById("venueName").value; let type = document.getElementById("venueType").value; let address = document.getElementById("venueAddress").value; let latitude = parseFloat(document.getElementById("latitude").innerHTML); let longitude = parseFloat(document.getElementById("longitude").innerHTML); $.ajax({ type: 'POST', url: '/add_cafe/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'venuename': name, 'venuetype': type, 'venueaddress': address, 'latitude': latitude, 'longitude': longitude }, success: function(data) { console.log("Data sent"); } }); } Here is the views.py function that processes it for the database: def add_cafe(request): if request.method == "POST": new_obj = mapCafes() new_obj.cafe_name = request.POST.get('venuename') new_obj.cafe_address = request.POST.get('venueaddress') new_obj.venue_type = request.POST.get('venuetype') new_obj.cafe_long = float(request.POST.get('longitude')) new_obj.cafe_lat = float(request.POST.get('latitude')) new_obj.save() return render(request, 'testingland/addcafe.html') And here is the ajax call that retrieves the data for the marker modal box: $.ajax({ type: … -
how to reverse url with pk post django
hi i am creating a django blog in which i am adding a comment section,all stuff worked fine. but after adding comments i want to redirect to that perticular post in which i wanted to add comment views.py class add_comment(CreateView): model = comments fields = ['comment'] template_name = 'forum_app/add_comment.html' success_url = reverse_lazy('post_detail',) def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls.py from . import views from .views import post_detail,add_comment urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), path('<int:pk>/',post_detail.as_view(),name='post_detail'), path('add_comment/<int:pk>/',add_comment.as_view(), name='add_comment') ] all i want to do is once i click submit it should reverse to the same post which i wanted to add comments simple post_detail asking for pk but not able to integrate pk in this... help is appreciated -
How to warmup cache view as login user in Django?
I want to warmup cached View from scheduled management command. I have to be logined when doing request to View. What is the best practice to login as user and do get request to View? I am thinking about two ways: Use requests: request = requests.session() response = request.get(login_url) token = response.cookies['csrftoken'] data={'username':'username@username.ru', 'password': 'pass','csrfmiddlewaretoken':token} response = request.post(login_url, data=data) response = request.get(target_url) Use test.Client() and login option. What is better? Or maybe the best option exists? -
Update Django model based on the row number of rows produced by a subquery on the same model
I have a PostgreSQL query which updates the global_ranking field of each row, based on the row number of that row as computed by a subquery which takes that same table and sorts it according to another column called rating. Additionally, the update is partitioned, so that the ranking of each updated row is relative to only those rows which belong to the same language. In short, I'm updating the ranking of each player in a word game (why player statistics have a language field), based on their current rating. The working PostgreSQL query looks like this: UPDATE stats_userstats SET global_ranking = sub.row_number FROM ( SELECT id, row_number() OVER ( PARTITION BY language ORDER BY rating DESC ) AS row_number FROM stats_userstats ) sub WHERE stats_userstats.id = sub.id; I'm using Django, and it'd be fun to learn how to express this query using the Django ORM, if possible, before resorting to running a raw query. It seems like Django has all the parts that are necessary to express the query, including the ability to use PostgreSQL's row_number() windowing function, but my current attempt updates all rows ranking with 1: from django.db.models import F, OuterRef, Subquery from django.db.models.expressions import Window from … -
Why there is a lag between Django and Gunicorn?
I have my production server (RHEL 7) setup with the following Nginx -> Gunicorn -> Django. Below are the logs from django (removed log messages and modules info for safety reasons). { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:49,711" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,371" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,611" <removed for safety reasons> } { "log_level": "INFO", "_time": "2021-02-03 06:02:50,852" <removed for safety reasons> } It is clear that the time taken to process a request and respond is Approx 1-2 sec Below is the access log entry in gunicorn - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.0" 200 18496 "<domain name removed for safety reasons>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" and Below is the entry log in Nginx <ip removed for safety reasons> - - [03/Feb/2021:06:02:54 +0000] "GET /all_uploads/ HTTP/1.1" 200 18496 "<domain name removed for safety reasons>>" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" "-" "-" I assumed that the template rendering is taking time, however this template is a simpler one and shouldn't take more … -
Django: celery showing different status for the same task
I've a django app with two celery tasks, say task1 and task2. task1 gets triggered on a POST request from the frontend and the request has to sent back the task id so the frontend can poll its status later. task2 is supposed to run after task1 succeeds, asynchronously. Here're my task definitions: @shared_task(ignore_result=False) def task1(pk: int): # retrieve object matching pk return task1_func(obj) @shared_task(ignore_result=False) def task2(task_id: int): task = AsyncResult(task_id) while not task.ready(): logger.info("status {}".format(task.status)) time.sleep(1) return task2_func() Here's how I'm triggering them inside my views.py: class MyView(viewsets.ModelViewSet): def create(self, request): # create object task = task1.delay(obj.pk) task2.delay(task.id) #breakpoint return Response(task.id, status=status.HTTP_200_OK) Now when I try checking the status at the breakpoint, it shows success: In [1]: task.id Out[1]: '97f8d150-de04-4848-a400-3882988c833c' In [2]: task.status Out[2]: 'SUCCESS' In [3]: AsyncResult(task.id).status Out[3]: 'SUCCESS' But the code inside the task2 never gets executed because the status of task1 inside task2, never changes from PENDING. What am I doing wrong? Clearly my results are being stored and accessible but for some reason I cannot see the change in status from within another task. I cannot chain the tasks because I've to send the first task's id to the frontend. -
How exactly should JWT-based authentication be implemented in Django (drf and simplejwt)?
I am struggling to understand exactly how JWT-based authentication should be implemented in Django (I am using simplejwt). I am just a beginner, so please brace yourselves for some silly questions. The rest-framework-simplejwt documentation is very minimal and does not provide enough detail for a newbie like me. path('token/obtain', jwt_views.TokenObtainPairView.as_view(), name='token_create'), path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), So, I've created the paths in my urls.py as suggested by the official documentation. Where do I go from here? I guess my confusion comes from the fact that I am not sure where exactly in the code I have to issue my tokens. Let's say, I am logging in the user. So, in order to obtain the token, do I have to send a request to the 'token_create' endpoint from inside my view? Or do I have to somehow indicate it in one of my serializers? What about the 'refresh_token' endpoint? Is there a specific method that I need to use? Then, what do I do with the token once it has been issued? Clearly, I shouldn't save it in the database since it defeats the entire purpose of using JWTs in the first place. From my understanding, I should attach it to the headers … -
How to display single/particular data record from database -django
I want to display a particular data record from the database of a person who is logged in to the website. I have a default primary key in the migration. Other than that I don't have any of the primary or foreign keys. Below is the models.py and template codes. models.py class Ticket(models.Model): Email = models.CharField(max_length=40) to = models.CharField(max_length=40) cc = models.CharField(max_length=50) subject = models.CharField(max_length=25) class Meta: db_table = 'ticket' def __str__(self): return self.Email Following is the views which I had used before, that display's the whole data from the database. Views.py def ticket(request): ticket = Ticket.objects.all() return render(request, 'web/ticket.html', {'ticket':ticket}) But I want to display data of the respective mail id ticket.html {% for ticket in ticket %} <fieldset id="first"> <label for="From"><b>From</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="From" name="From" style="width:100%" value="{{ ticket.Email }}" required> <br> <br> <label for="To"><b>To</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="To" name="To" style="width:100%" value="{{ ticket.to }}" required><br> <br> <label for="Cc"><b>Cc</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Cc" name="Cc" style="width:100%" value="{{ ticket.cc }}" required><br> <br> <label for="Subject"><b>Subject</b></label> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="Subject" name="Subject" style="width:100%" value="{{ ticket.subject }}" required><br> <br> </fieldset> … -
Scraping jobs from PDF in india
I am facing an issue with PDF. I have to scrape the jobs from pdf file. Different pdfs are in different formats. I can scrape the data from pdf but, I need to identify which is a job title, job description..e.t.c.I am unable to do that.Can you guys suggest any solution to this issue? I need a solution in python. -
(1170, "BLOB/TEXT column 'BS_ID' used in key specification without a key length") Error while shifting my Django Database from Sqlite3 to mySQL
I have recently being try to change my Django database from sqlite3 to MySQL and while running the migrations I'm getting this error for the text field which is a primary key, its necessary to have it as a primary key because I have to use it for foreign key. Please share what changes do I need to make in my models to make this migration to MySQL successful. BS_ID = models.TextField(max_length=20,unique=True)- this field is the cause of the error. -
Pass the value of dropdown to sql query and fetch data and display in form of checkbox using Django Python
So i have a code which should get the value of dropdown selected value and pass it to a sql query fetch the result and pass it to another class , Since am new to django and am not really able to find what is the problem with the code . Can anyone kindly help me Posting the code <form enctype="multipart/form-data" action="{% url 'files' %}" method="POST"> {% csrf_token %} {{SnippetForm|materializecss}} <br> <table class="table form-table table-bordered table-sm"> <tbody> {% for form_data in formset %} <tr class="item"> <td> {{ form_data.server|materializecss }} </td> </tr> {% endfor %} </tbody> </table> {{ formset.management_form }} <br> <button type="reset" class="waves-effect waves light btn-large">Reset</button> <button type="submit" class="waves-effect waves light btn-large">Submit</button> </form> Here is the Index.html and the SnippetForm contains textbox Model.py # Create your models here. class Snippet(models.Model): customer = models.CharField(max_length=100, choices=customer_list) environment = models.CharField(max_length=100, choices=environment_list) def __str__(self): return self.customer class Meta: db_table = "snippet" Value = Snippet() cursor.execute("select distinct(VMName) from Inventory where customer='"+str(Value)+"' and status='Active'") records2 = cursor.fetchall() for i in range(len(records2)): server_choices[records2[i][0]] = records2[i][0] server_list = tuple([(str(k), v) for k, v in server_choices.items()]) class Files(models.Model): files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) snippet = models.ForeignKey(Snippet, related_name="files", on_delete=models.CASCADE) def __str__(self): return str(self.snippet) class …