Skip to content

Commit

Permalink
added
Browse files Browse the repository at this point in the history
  • Loading branch information
Nandeesh778 committed Jan 4, 2024
1 parent fe40de4 commit 3b8ae0a
Show file tree
Hide file tree
Showing 42 changed files with 747 additions and 81 deletions.
Binary file added mypro/db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions mypro/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mypro.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file added mypro/myapp/__init__.py
Empty file.
Binary file added mypro/myapp/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/admin.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/apps.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/models.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/tests.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added mypro/myapp/__pycache__/views.cpython-310.pyc
Binary file not shown.
6 changes: 6 additions & 0 deletions mypro/myapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.contrib import admin

# Register your models here.
from .models import Question

admin.site.register(Question)
6 changes: 6 additions & 0 deletions mypro/myapp/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
Binary file added mypro/myapp/blue_page.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
82 changes: 82 additions & 0 deletions mypro/myapp/convert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import pdfkit
import cairosvg
from html2image import Html2Image
hti = Html2Image()

def convert_html_file_to_pdf(html_file_path, output_file_path, type, output_pdf_file_path):
"""
Convert HTML file to PDF.
Args:
html_file_path (str): Path to the HTML file.
output_file_path (str): Path to save the output PDF file.
"""

if(type == "pdf"):
try:
options = {
'page-size': 'A4',
'margin-top': '0mm',
'margin-right': '0mm',
'margin-bottom': '0mm',
'margin-left': '0mm',
}
print("html_file_path>>>>>>>>>>", html_file_path)
pdfkit.from_file(html_file_path, output_file_path, options=options)
print(f'PDF successfully created at: {output_file_path}')
except FileNotFoundError as e:
print(f'HTML file not found: {html_file_path}')
except Exception as e:
print(f'Error converting HTML to PDF: {e}')

elif(type == "svg"):
#write a code to convert html to svg
# try:
# with open(html_file_path, 'rb') as html_file:
# svg_data = cairosvg.svg2svg(file_obj=html_file)

# with open(output_file_path, 'wb') as svg_file:
# svg_file.write(svg_data)

# print(f'SVG successfully created at: {output_file_path}')
# except FileNotFoundError as e:
# print(f'HTML file not found: {html_file_path}')
# except Exception as e:
# print(f'Error converting HTML to SVG: {e}')
#Assuming hti.screenshot captures HTML content and saves it to an image
#hti.screenshot(html_file=html_file_path, save_as='temp_img.svg')

# Convert the temporary image to SVG using cairosvg
# cairosvg.svg2svg(url='temp_img.png', write_to=output_file_path)
# try:
# cairosvg.svg2svg(url=html_file_path, write_to=output_file_path)
# except Exception as e:
# print(f"Error converting image to SVG: {e}")
from weasyprint import HTML
HTML(filename=html_file_path).write_pdf(output_pdf_file_path)
from cairosvg import svg2svg

# Convert PDF to SVG using cairosvg
svg2svg(url=output_pdf_file_path, write_to=output_file_path)





elif(type == "img"):
#write a code to convert html to img
hti.screenshot(html_file=html_file_path,save_as='blue_page.png')


if __name__ == "__main__":
type = "svg"
# Input HTML file path
html_file_path = "/home/nandeesh/Desktop/demo_django/mypro/myapp/input.html"
output_pdf_file_path = "/home/nandeesh/Desktop/demo_django/mypro/myapp/output.pdf"

# Output PDF file path
output_file_path = "/home/nandeesh/Desktop/demo_django/mypro/myapp/output.svg"

convert_html_file_to_pdf(html_file_path, output_file_path, type, output_pdf_file_path)

10 changes: 10 additions & 0 deletions mypro/myapp/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample HTML file.</p>
</body>
</html>
32 changes: 32 additions & 0 deletions mypro/myapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 4.2.5 on 2023-09-06 06:02

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='myapp.question')),
],
),
]
Empty file.
Binary file not shown.
Binary file not shown.
27 changes: 27 additions & 0 deletions mypro/myapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from django.db import models
import datetime
from django.utils import timezone

# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")

def __str__(self):
return self.question_text

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self) :
return self.choice_text


def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
Binary file added mypro/myapp/output.pdf
Binary file not shown.
Binary file added mypro/myapp/output.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions mypro/myapp/static/myapp/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
li a {
color: green;
}

body {
background: yellow url("images/background.png") no-repeat;
}
Binary file added mypro/myapp/temp_img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions mypro/myapp/templates/detail.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<form action="{% url 'myapp:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
13 changes: 13 additions & 0 deletions mypro/myapp/templates/myapp/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'myapp:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}

{% load static %}

<link rel="stylesheet" href="{% static 'myapp/style.css' %}">
9 changes: 9 additions & 0 deletions mypro/myapp/templates/myapp/results.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'myapp:detail' question.id %}">Vote again?</a>
129 changes: 129 additions & 0 deletions mypro/myapp/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
from django.test import TestCase

# Create your tests here.
import datetime

from django.urls import reverse
from django.utils import timezone

from .models import Question


class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)


def test_was_published_recently_with_old_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_question = Question(pub_date=time)
self.assertIs(old_question.was_published_recently(), False)


def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)

def create_question(question_text, days):
"""
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)


class QuestionIndexViewTests(TestCase):
def test_no_questions(self):
"""
If no questions exist, an appropriate message is displayed.
"""
response = self.client.get(reverse("myapp:index"))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerySetEqual(response.context["latest_question_list"], [])

def test_past_question(self):
"""
Questions with a pub_date in the past are displayed on the
index page.
"""
question = create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse("myapp:index"))
self.assertQuerySetEqual(
response.context["latest_question_list"],
[question],
)

def test_future_question(self):
"""
Questions with a pub_date in the future aren't displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse("myapp:index"))
self.assertContains(response, "No polls are available.")
self.assertQuerySetEqual(response.context["latest_question_list"], [])

def test_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
are displayed.
"""
question = create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse("myapp:index"))
self.assertQuerySetEqual(
response.context["latest_question_list"],
[question],
)

def test_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
question1 = create_question(question_text="Past question 1.", days=-30)
question2 = create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse("myapp:index"))
self.assertQuerySetEqual(
response.context["latest_question_list"],
[question2, question1],
)


class QuestionDetailViewTests(TestCase):
def test_future_question(self):
"""
The detail view of a question with a pub_date in the future
returns a 404 not found.
"""
future_question = create_question(question_text="Future question.", days=5)
url = reverse("polls:detail", args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)

def test_past_question(self):
"""
The detail view of a question with a pub_date in the past
displays the question's text.
"""
past_question = create_question(question_text="Past Question.", days=-5)
url = reverse("polls:detail", args=(past_question.id,))
response = self.client.get(url)
self.assertContains(response, past_question.question_text)
Loading

0 comments on commit 3b8ae0a

Please sign in to comment.