Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReadingFile' object has no attribute 'get_text_from_image'
I have a python Django application. And I want to filter some sub text from extracted text. So this is how my views.py looks like: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if uploadfile.image.path.endswith('.pdf'): content = ExtractingTextFromFile.filterAnanas(self) # ENDING Reading pdf file else: with open(os.path.join(settings.MEDIA_ROOT, uploadfile.image.path)) as f: content = f.read() return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) and this is class: ExtractingTextFromFile.py class ExtractingTextFromFile: def extract_text_from_image(filename): text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) return text_factuur_verdi def __init__(self ): # class variables: self.apples_royal_gala = 'Appels Royal Gala 13kg 60/65 Generica PL Klasse I' self.ananas_crownless = 'Ananas Crownless 14kg 10 Sweet CR Klasse I' self.peen_waspeen = 'Peen Waspeen 14x1lkg 200-400 Generica BE Klasse I' self.tex_factuur_verdi = [] def make_pattern(substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" def filterAnanas(self): … -
How to declare and get an output parameter in store procedure in Django?
I am trying to work with store procedures. So far I am able to work with input parameters and is successfully able to retrieve records or insert etc. Now, I have a store procedure that requires an output parameter @Id. The goal is to insert a record in the database using the store procedure which I am able to that. The issue, however, I am facing is that I am not being able to get the @Id. I am using MsSQL database. I have tried various ways to get the @Id output, but it gives an error. This is the code: cursor.execute("DECLARE @Id int; exec proc_jobcardInsert @Id = @Id OUTPUT, @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() I have also tried it like this: cursor.execute("exec proc_jobcardInsert @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() And I also tried cursor.fetchone()[0] All of them are not working. I also one or two other things but all gives me an error stating: django.db.utils.ProgrammingError: No results. Previous SQL was not a query Data is being inserted into the database but I want the @Id at the end. Please guide me as how to achieve it and what am I doing wrong here. -
Razorpay signature verification fail even after passing all the data correctly - Django
I am trying to verify the signature with razorpay. I am receiving the data required for the verification correctly from the frontend and also passing the data correctly to the utility.verify_payment_signature(). The code is as below # setup razorpay client this is the client to whome user is paying money that's you client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_SECRET_ID)) # razorypay information razorpay_payment_id = request.data.get('razorpay_payment_id','') razorpay_order_id = request.data.get("razorpay_order_id",'') razorpay_signature = request.data.get('razorpay_signature','') # this is for verification of razorpay params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razorpay_signature, } check = client.utility.verify_payment_signature(params_dict) if check == None: #code else: #fail_payment The tutorial from which I learnt this says if the verification is successful the check should return None but instead the check is returning True, hence, failing the payment. I am unable to understand what is actually the problem. Please suggest me a solution -
AttributeError at /website/tbt.html 'User' object has no attribute 'get'
I am trying to generate a pdf from data taken by the user. in this case it contains a few fields as shown in models. It gives me an error after I hit the submit button my models.py tbt_date = models.DateField( verbose_name="Date of Creation", default=timezone.now ) selected_site = models.ForeignKey( sites_data, verbose_name="Choose a site", on_delete=models.CASCADE ) selected_block = models.ForeignKey( blocks_list, verbose_name="Choose a block", on_delete=models.SET_NULL, null=True ) tbt_report_img1 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 1" ) tbt_report_img2 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 2" ) rt_pdf = models.FileField(upload_to='pdfs/', verbose_name='PDF File', null=True) my views.py tbt_form_view = tbt_report_form() context = { "loggedInUser": request.user, "tbt_form":tbt_form_view, } return context #@login_required(login_url="user_login") def generate_tbt_report(request, t_form, selected_form, filename): selected_site = t_form.selected_site selected_block = t_form.selected_block selected_site_data = sites_data.objects.filter(name=selected_site)[0] tbt_date = t_form.tbt_date print(tbt_date) params = { "selected_site": selected_site_data, "tbt_date": tbt_date, "selected_block": selected_block, "t": t_form, "data": selected_form, "loggedInUser": request.user, } template_path = "website/tbt_report_pdf.html" temp_pdf = render_to_pdf(request, template_path, params, filename) return temp_pdf @login_required(login_url="user_login") def tbt_form(request): if request.method == "POST": t_form=tbt_report_form(request.user, request.POST, request.FILES) t_form.full_clean() print("in post") if t_form.is_valid(): print("Valid") t_form = t_form.save() filename='TBT' + ' ' + str(t_form.tbt_date) + ' ' + str(t_form.selected_block) + '.pdf' pdf = generate_tbt_report(request, t_form, filename) cv_get = tbt_report.objects.get(id = t_form.id) cv_get.rt_pdf.save(filename, File(BytesIO(pdf.content))) print("Saved") return pdf else: print("1") print(t_form) messages.error( request=request, message="Please … -
django: build a class based view that set a session object and call another view
is possible to build a class based view that set a session object and call another view? I did this with a form, but I need to set a session object just calling a url. Thanks -
Run Daphne in production on (or forwarded to?) port 443
I am trying to build a speech recognition-based application. It runs on Django with Django-channels and Daphne, and Nginx as the web server, on an Ubuntu EC2 instance on AWS. It should run in the browser, so I am using WebRTC to get the audio stream – or at least that’s the goal. I'll call my domain mysite.co here. Django serves the page properly on http://www.mysite.co:8000 and Daphne seems to run too, the logs show 2022-10-17 13:05:02,950 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne0.sock 2022-10-17 13:05:02,951 INFO HTTP/2 support enabled 2022-10-17 13:05:02,951 INFO Configuring endpoint fd:fileno=0 2022-10-17 13:05:02,965 INFO Listening on TCP address [Private IPv4 address of my EC2 instance]:8000 2022-10-17 13:05:02,965 INFO Configuring endpoint unix:/run/daphne/daphne0.sock I used the Daphne docs to set up Daphne with supervisor. There, they use port 8000. My first Nginx config file nginx.conf (I shouldn't use that one, should I?) looks like this: worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: … -
Websocket fails to connect in deployment
I deployed an app using Django Channels to connect, send and receive data through a websocket. I get the backend working, but the problem is, the app fails when I try to connect to a websocket. I know this works in my local drive so I believe the problem has little to do with how I set up my websockets and more to do with deployment settings. Here is a link to the logs I get (I deployed this app to render.com): https://paste.pythondiscord.com/ I know my Redis Channels Layer is up and running (has also been deployed to render.com). This is the service address: redis-kufk:10000 These are my channels layer and cache settings in settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "LOCATION": "redis://127.0.0.1:6379", }, } ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "TIMEOUT": 5 * 60, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "pairprogramming" } } REDIS_HOST_LAYER = '127.0.0.1' REDIS_PORT = 6379 ... REDIS_HOST = '127.0.0.1' REDIS_PORT = 6379 These is my asgi.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') ... import django django.setup() ... application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) ) }) -
Should I move windows project folder into WSL?
I'm trying to set up a work environment on a new machine and I am a bit confused how best to procede. I've set up a new windows machine and have WSL2 set-up; I plan on using that with VS Code for my development environment. I have a previous django project that I want to continue working on stored in a folder in a thumb drive. Do I move the [windows] project folder into the linux folder system and everything is magically ready to go? Will my previous virtual environment in the existing folder still work or do I need to start a new one? Is it better to just start a new folder via linux terminal and pull the project from github? I haven't installed pip, python, or django on the windows OR linux side just yet either. Any other things to look out for while setting this up would be really appreciated. I'm trying to avoid headaches later by getting it all set-up correctly now! -
Consolidating Multiple Django Projects
I want to Consolidating (Connect[Link together]) Two or Three Django Projects! like: Project_1 --> a Eshop Project_2 --> Deliveries in Our City. how its work?? -
Django Two Factor Auth combined with Rest Framework?
I'm trying to implement django two factor auth into my Rest API. Is there a possibility to implement this by using custom views and model creations? Because, at least that's the way I understood it, this library is mainly working based on default django templates and predefined routes. Is it possible to combine this library with a Rest API or should I use another library? -
Update Django model field by CSV file upload via change_form.html override
Django is still not my superpower, so I hope that some of you could help me to find a way to achieve my goal, which is: I need to find a way to get "Upload file" feature at Django admin change_form.html template. By uploading that file my app would be able to update body of the specific instance of Content model (with fields id, title and body). I already implemented solution for similar problem, which is how to add new objects by clicking custom "Upload csv" button in admin panel. I achieved it by following this solution: I added this in app's admin.py file: from .models import Content class CsvUploadForm(forms.Form): csv_file = forms.FileField() class CsvUploadAdmin(admin.ModelAdmin): change_list_template = "admin/change_list.html" def get_urls(self): urls = super().get_urls() additional_urls = [ path("upload-csv/", self.upload_csv), ] return additional_urls + urls def changelist_view(self, request, extra_context=None): extra = extra_context or {} extra["csv_upload_form"] = CsvUploadForm() return super(CsvUploadAdmin, self).changelist_view(request, extra_context=extra) def upload_csv(self, request): if request.method == "POST": form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): if request.FILES['csv_file'].name.endswith('csv'): try: decoded_file = request.FILES['csv_file'].read().decode( 'utf-8') except: self.message_user( request, "Can not decode the file, please check its content if valid CSV format", level=messages.ERROR ) return redirect("..") content_body = decoded_file content_title = request.FILES['csv_file'].name try: csv.reader(content_body.splitlines()) except: self.message_user( request, … -
Does default isolation level setting in Django depend on database?
I read Isolation level in Django documentation and it says as shown below: Like PostgreSQL itself, Django defaults to the READ COMMITTED isolation level. So, if I use Django with MySQL whose default isolation level is REPEATABLE READ: Is the default isolation level setting in Django also REPEATABLE READ? Or Is the default isolation level setting in Django READ COMMITTED? -
Error when importing models into test.py file, django
I'm trying to create a test.py file for some of my database methods in a current django project. I need to import my models.py file, but the import statement I'm using below (which follows the official Django example) is causing an error. Both test.py and models.py are already in appFolder, so is that the issue? from appFolder.models import Class1,Class2,Class3 Using only 'import models' didn't work when I ran it earlier. How can I resolve this? (I have also been running the file with the command './manage.py test' if that's relevant) -
How to create custom validation within custom model field type?
I am trying to make a school management system where super users who can add new students (and teachers later on) on the database have to also enter the student's courses. However, I want to use validation for different purposes: Students need to take at least and a maximum of 1 option from the English and Math field (which does not need any further validation if left as it is) Students need to take at least 1 science and a maximum of 2 --> Needs validation to ensure courses are not taken twice. Students can pick any 3 courses from Science, Art, and Society, but cannot take the same courses twice. I apologize if this question is silly or for any errors in the code as I started learning django and html 3 days ago to complete a school project. I read the django documentation in hopes for an answer but I couldn't find what I was looking for. class Student(models.Model): student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100) class English(models.TextChoices): LANGLIT = 'LL', _('Language and literature') LIT = 'L', _('Literature') english = models.CharField(max_length=2, choices=English.choices, default=English.LANGLIT) class Math(models.TextChoices): AA = 'AA', _('Analysis & Approaches') AI = … -
Problem with permissions on macos when i try to work in django shell
Im open shell with python manage.py shell, import model and try to make response to db (its remote) and have this problem: connection to server at "192.168.0.110", port 5023 failed: could not open certificate file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.crt": Permission denied If i make sudo su i have this problem: OperationalError: connection to server at "192.168.0.110", port 5023 failed: private key file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.key" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root Than i make chmod 600 config/extra/ and restart shell. After this: OperationalError: connection to server at "192.168.0.110", port 5023 failed: private key file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.key" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root How can i fix this?... -
Refresh Values on Django Template using repeated AJAX calls
I have a django webapp where I want to update a field with random values after every 10 seconds. Here's the code structure: views.py temp_values = [1, 2, 3, 3, 4, 5, 5, 6, 6, 7] def get_temp(): return temp_values[random.randint(0, 6)] def ajax_data(): data = {'temp': get_temp()} json_data = json.dumps(data) return Response(json_data, mimetypes='application/json') template.html <div class="container"> <div class="section"> <div class="col grid_1_of_3"> <h3>Temperature</h3> <input type="checkbox"> On/Off <br> <label>Current: </label><input type="text" placeholder="{{ v }}" disabled="disabled"><br> <form action="" method="POST"> {% csrf_token %} <script src="http://code.jquery.com/jquery-3.0.0.js"></script> <script language="javascript" type="text/javascript"> function updateValue() { $.ajax({ url:"/ajax_data", }); } $(document).ready(function(){ var v = setInterval(updateValue,1000); }); </script> {{ form.as_p }} <button type="submit">Set</button> </form> <img src="{% static 'img/graph.png' %}" alt="graph"/> </div> There is a current temp field & a set temp field (for which I have created a form which posts request on submit button click). However console keeps throwing 404 url not found error. Please let me know where I am I going wrong -
Like button only work when clicked on but cant unlike post object using ajax in Django
I'm trying to work Django with ajax to stop the reload of page when a post object is liked by a user, but somehow when the like button is clicked it update the button as liked, but when i click the button to unlike the post doesn't unlike. I'm wondering how i could do it better to stop this malfunction. why does it only toggle to like but doesn't back to unlike ? My likeview def Addlike(request,post_id): if request.method == 'POST': post = Post.objects.get(id=post_id) is_liked = False if post.like_page_post.filter(id=request.user.id).exists: post.like_page_post.remove(request.user) is_liked = False else: post.like_page_post.add(request.user) is_liked = True return JsonResponse({'is_liked':is_liked,'count_likes':post.like_page_post.all().count()}) Ajax function function likeajax($this) { var id = $this.attr("id"); var count_likes = $('#count_likes'); var like_icon = $('#like_icon'); $.ajax({ headers: {'X-CSRFToken': document.getElementById('csrf').querySelector('input').value}, method: 'POST', url: "{% url 'page:like' page.id %}", dataType: "json", data: { }, success: function (data) { if(data.is_liked) { like_icon.html('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="blue" width="22" height="22" class="dark:text-gray-100" ><path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" /></svg>'); count_likes.text(data.likes_count); } else { like_icon.html('<svg … -
How to reduce inventory when creating a purchase instance in Django?
I'm working on a Django project that is a simple restaurant management system. One of the key functionalities is to record inventory and purchases. I'm looking to add functionality where once I create a Purchase instance, my program automatically reduces the inventory by the amount used in that purchase. I've been scratching my head a bit and poking around the internet but I'm honestly not sure exactly where to start. This is my first Django project so would greatly appreciate a bit of direction. See below for my models.py and views.py. Models.py class Inventory(models.Model): ingredient_name = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=2) units_avail = models.IntegerField() def __str__(self): return self.ingredient_name + " avail: " + str(self.units_avail) def get_absolute_url(self): return "/inventory" class MenuItem(models.Model): menu_item_name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.menu_item_name + " with Price: " + str(self.price) def available(self): return all(recipe_req.enough() for recipe_req in self.reciperequirement_set.all()) def get_absolute_url(self): return "/menu" def cost(self): item_cost = 0 for recipe_req in self.reciperequirement_set.all(): item_cost += recipe_req.ingredient.price return item_cost def profit(self): item_cost = self.cost() item_profit = self.price - item_cost return item_profit class RecipeRequirement(models.Model): ingredient = models.ForeignKey(Inventory, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return self.ingredient.ingredient_name + " in " + self.menu_item.menu_item_name def … -
как парсить url картинки с сайта ? python и вывести её в консоль [closed]
<img class="bookkitem_cover_img" src="https://s13.knigavuhe.org/2/covers/40052/1-1@2x.jpg?1" alt="Юдифь"> html -
Hello, I am facing an error I am facing while using Django templates
Heyy, I wanted some help with an error I am facing while using Django templates. I am facing a Template Syntax Error "Invalid block tag on line 77: 'else'. Did you forget to register or load this tag?" <!-- Logged In --> {% if request.user.is_authenticated %} <div class="header__user"> <a href="profile.html"> <div class="avatar avatar--medium active"> <img src="https://randomuser.me/api/portraits/men/37.jpg" /> </div> <p>{{request.user.username}}<span>@{{request.user.username}}</span></p> </a> <button class="dropdown-button"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"> <title>chevron-down</title> <path d="M16 21l-13-13h-3l16 16 16-16h-3l-13 13z"></path> </svg> </button> </div> {% else %} <!-- Not Logged In --> <a href="{% url 'login' %}"> <img src="./assets/avatar.svg" /> <p>Login</p> </a> {% endif %} Can you please help me fix this? Thank you ! -
How would you achieve this Dynamic updating
I have this simple form "Manufacturers" have a DB, "Models" have a DB with a ForeignKey to Manufacturers. There are indoor and outdoor systems which are simply provided in the Models DB FIRST Dynamic updating - This is what I want to happen with the above. When "Indoor Manufacturer" is selected, "Indoor Model" shows relevant records on "Indoor Model". Ditto for "Outdoor Manufacturer" & "Outdoor Model" SECOND Dynamic updating - But to make the form a tad easier, when the Checkbox "Indoor/ Outdoor Unit Same Manufacturer" is clicked, it locks "Outdoor Manufacturer" to what is selected in "Indoor Manufacturer" - it still needs to update "Outdoor Model" selection though I'm not entirely new to Django, but still very much a Beginner. I can manage the First Part using HTMX but then I run into a brick wall with trying to combine the First Part & the Second Part. I suspect I'm reaching the limits of my ability here and may be using HTMX incorrectly, so look for advice on how others would approach this? -
How to prevent my queries from getting out of order when I show them in the template with a nested loop
I am making a query to the database, ordering it by date and then sending it to the template, but it is displayed out of order in the template. I think the problem is the nested loop. When i take out the nested loop it worked but i really need the loop to be there. How can I make it work? This is the query from the view: recibos=grupo.recibos.all().order_by('-fecha_pago') This is the template code: {% if recibos %} <table class="table table-responsive-sm table-sm table-hover datatable"> <thead> <tr> <th>Responsable</th> <th class="text-center">Fecha</th> <th class="text-center">Monto</th> <th class="text-center">Forma de Pago</th> <th class="text-center"></th> </tr> </thead> <tbody> {% for recibo in recibos %} <tr> <td> <div>{{recibo.responsable.nombre}} {{recibo.responsable.apellido}}</div> <div class="small"><span>&nbsp;&nbsp;<i class="fa-solid fa-graduation-cap"></i></span> {% for alumno in recibo.alumnos.all %} {% if not forloop.last %} {{alumno.nombre}}, {% else %} {{alumno.nombre}} {% endif %} {% endfor %} </div> </td> <td class="text-center"> <div>{{recibo.fecha_pago}}</div> </td> <td class="text-center"> <div>${{recibo.importe|floatformat:"2g"}}</div> </td> <td class="text-center"> <div>{{recibo.forma_pago}}</div> </td> <td class="text-center"> <div>botones</div> </td> </tr> {% endfor %} </tbody> </table> {% else %} <br> {% if filtro == True %} <div class="alert alert-warning text-center"> <strong>No hay resultados para este filtro</strong> </div> {% else %} <div class="alert alert-warning text-center"> <strong>No hay recibos para esta familia</strong> </div> {% endif %} {% endif … -
Django migrate Oracle DB
I have a Django App (Python 3.8 // Django 3.2.15) currently using an MSSQL DB Server (with the 3rd Party Microsoft Connector) and would like to migrate it to Oracle. Completely new and empty oracle 19c instance with my own new/empty schema. Connection seems to be working according to manage.py and when migrating I instantly get the Error: Applying contenttypes.0001_initial...Traceback (most recent call last) django.db.utils.DatabaseError: ORA-00900: invalid SQL statement (even though the migrations and contenttype table are created) Anyone got any idea? I have not made any modifications to the migrations and even when running a specific app migration it fails with the same issue... (the only options I use for the DB are the recommended threaded and use_returning_into) -
how to save the user that entered a form in Django?
I have a form in a Django application. I want to save a user with the form and associate that data with the user in the database. This seems like something you should be able to do but I can't find anything in the docs and no information anywhere else. any help would be very much appreciated. -
i don't know if these models are setup correctly for django ecommerce
` from django.db import models from phonenumber_field.modelfields import PhoneNumberField Create your models here. CATGORIES_CHOICE = ( ("Sports"), ("Fashion"), ("Electronics"), ("Fishing"), ("Books"), ("Cosmetics"), ("Games"), ("Pets"), ("Outwear"), ("Lingerie"), ("Medicals") ) ORDER_HISTORY_CHOICE = () class User(models.Model): email = models.EmailField(unique=True) password = models.CharField(max_length=15) phone_number = PhoneNumberField(region="US") address1 = models.TextField() address2 = models.TextField(blank=True,null=True) created = models.DateTimeField(auto_now_add=True) class Store(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=100,default="official store") created = models.DateTimeField(auto_now_add=True) class Product(models.Model): store_id = models.ForeignKey(Store,on_delete=models.CASCADE) #product_id = models.IntegerField(unique=True,max_length=13) title = models.CharField(max_length=110) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=15,decimal_places=2) discount = models.DecimalField(max_digits=2,decimal_places=2,default=0.00) available = models.IntegerField() category = models.CharField(choices="",max_length=20) # image = models.ImageField(upload_to="images") condition = models.CharField(choices="",max_length=20) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) @property def sales_price(self): return "%f" %(float(self.price * (1 - self.discount))) class CartItem(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) order_number = models.IntegerField(unique=True,default=7) ordered = models.BooleanField(default=False) items = models.ManyToManyField(CartItem) created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() class Review(models.Model): created_by = models.ForeignKey(User,on_delete=models.CASCADE) product_id = models.ManyToManyField(Product,on_delete=models.CASCADE) rating = models.DecimalField(max_digits=2,decimal_places=1,default=0.0) label = models.CharField(max_length=100) comment = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class BlogPostInfo(models.Model): title = models.CharField(max_length=100) written_by = models.CharField(max_length=70) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Saved(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) products = models.ManyToManyField(Product) class History(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) products = models.ManyToManyField(Product) status = models.CharField(choices="",max_length=20) `