Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Images Suddenly Not Rendering on Front End
I have just encountered an odd problem I'm trying to debug but cannot figure out what is wrong. I have a wagtail site with images that were all working. At one point I refreshed the browser, and the images suddenly all disappeared from every page. wagtailimages_tags is there static is all loaded the images are all in the correct media directory as specified and have been uploaded through the CMS if i inspect element, the image is in fact coming through in the code perfectly. But the site itself just does not show the image. I have checked the CSS and nothing has changed there and it is not hiding the image somehow. My last resort - I actually started the project over completely in a new environment and added each application one by one to see if I could solve the issue ... nope. No images on the new install from scratch either! No idea why all the images would suddenly just fail to appear in browser. Just seems super strange to me. Any ideas on debugging appreciated. -
Creating new Objects instead of updating - Django
I am trying to use Update in Django, but it is not being updated, rather a new object of the model is being created in the database. For example, if I try to change product label "Laptop" to "Smartphone", Django creates a new product called "Smartphone" instead of updating "Laptop". This is my code Model: class Products(models.Model): label = models.CharField(max_length=50) description = models.CharField(max_length=250) first_price = models.FloatField(null=True) price = models.FloatField() quantity = models.IntegerField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.label @property def imageURL(self): try: url = self.image.url except: url = '' return url Form: class ProductForm(ModelForm): class Meta: model = Products fields = ['label', 'description', 'first_price', 'price', 'quantity', 'image'] View: @login_required(login_url='login') def editProduct(request, id): product = Products.objects.get(id=id) form = ProductForm(instance=product) if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Product was edited.') return redirect('index') context = { 'form': form } return render(request, 'store/edit-product.html', context) Template: <h3>Edit Product</h3> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.label.label }} {{ form.label }} {{ form.description.label }} {{ form.description }} {{ form.first_price.label }} {{ form.first_price }} {{ form.price.label }} {{ form.price }} {{ form.quantity.label }} {{ form.quantity }} {{ form.image.label }} {{ form.image }} <input type="submit" name="Add product"> {{form.errors}} </form> Thank you … -
Django admin set fk_name = to_field in inline class only allows one image to be uploaded
I am new to Django and I ran into a problem when I tried enable the admin to add multiple images to a user profile at once. I created a Model Profile that allows a user to have one profile, and can have more than one photo in the profile. I want to use user_id to link images to profile and use user_id for filter. However, when I tried to upload more than one photo to a profile, it displays error. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, ) GENDER_CHOICES = ( ('F', 'Female'), ('M', 'Male') ) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, default='F', blank=False, choices=GENDER_CHOICES ) about_me = SizedTextField( size_class=2, null=True, blank=True ) date_created = models.DateTimeField(default=timezone.now) class Photos(models.Model): user = models.ForeignKey( Profile, to_field='user', null=True, blank=True, on_delete=models.SET_NULL ) photo = models.ImageField( upload_to='photos/%Y/%m/%d/', blank=True ) admin.py class PhotosInline(admin.TabularInline): model = Photos fk_name = 'user'#only one photo allowed to be uploaded, I want more than one @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'date_of_birth','gender', 'about_me'] inlines = [PhotosInline,] Why does it only allow one photo to be uploaded? What must I do? -
I keep getting a 'There is no current event loop in thread 'Stream''
I'm trying to redo a project based on a github repo I found a while back. When I try to run the author's code I get the 'There is no current event loop in thread 'Stream''. I've looked online through some stackoverflow questions that had the same issue I'm facing but none of their code seems to be similar to mine. They all have used the Asyncio package while I opted for the Threading package. Here's the code to the python file where the error occurs: import base64 import cv2 import time from threading import Thread import RPi.GPIO as GPIO import collect import visit import os #import save #from pymongo import MongoClient GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(27, GPIO.OUT) class Stream(Thread): def __init__(self): self.flag = [False] self.capture_flag = [False] #self.ws = ws self.clients = [] Thread.__init__(self, name=Stream.__name__) def run(self): self.camera = cv2.VideoCapture(0) prev_input = 1 #mongo_db = MongoClient('localhost',27017) #db = mongo_db.smartbell.visitors while True: # Read camera and get frame rval, frame = self.camera.read() if frame is None: self.camera.release() self.camera = cv2.VideoCapture(0) continue # Send camera stream to web if self.flag[0]: rvel, jpeg = cv2.imencode('.jpg', frame) encode_string = base64.b64encode(jpeg) for client in self.clients: client.write_message(encode_string) # A visitor pushes button but = … -
Select2 in django doesn't show the options
I want to join selections in a form. I have the model "Country" and the model "City". when a user selects a Country only the Cities listed in that country should be listed. The problem is that When I try to do it, in the form I cant see any options, so no country or cities are listed at all. This is my code: forms.py: Blockquote from django import forms from django.forms import ModelForm from .models import Country, City from django_select2.forms import ModelSelect2Widget class AddressForm(forms.Form): country = forms.ModelChoiceField( queryset=Comunidad.objects.all(), label=u"Country", widget=ModelSelect2Widget( dependent_fields={'city': 'city'}, search_fields=['name__icontains'], ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( search_fields=['name__icontains'], max_results=500, ) ) '''''' This is what I have in models.py: class Country (models.Model): name= models.CharField(max_length=20, help_text="Añada Comunidad Autónoma") def __str__(self): return self.name class City(models.Model): name= models.CharField(max_length=20, help_text="Añada provincia") country = models. ForeignKey('Country', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name ''' and, in the template: '''{{form.as_table}}''' What I get is the text: "Country" and "City" followed by a drop down button but it's empty. So I see no Countries and no Cities at all, but database is not empty. I don't know what am I missing. Any help will be welcome. -
How can I convert a Django Project into a Django application inside my own project?
I have found a Django project who's purpose is to send emails to subscribers and it is divided into several applications but I view this project as an application and want to include it in my own project. What are the minimal steps to convert that project into an app ? -
how to verify if input email is already exist in database?
I have an issue with the program am trying to develop. I have a function that will send OTP code to user when they request to login. the OTP code should be sent through email to the registered users. the problem is that my code now accepts every email and it doesn't validate the users from the database. How can I do this? this is my script <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type='text/javascript'> {% block title %} {% endblock %} {% block content %} <h1>OTP Verification Page</h1> <br> <br> <p> </script> <div id="email_div" style="display: block;" > <label for="email">Email</label> <input type="text" name="email" id="email"> <button onclick="ajax_send_otp()">Send OTP</button> </div> <div id="verify_text_div"></div> <div id="otp_div" style="display: none;" > <label for="email">OTP</label> <input type="text" name="otp" id="otp"> <button onclick="verify_otp()">Verify</button> </div> </p> {% endblock %} <script> var otp_from_back=""; function ajax_send_otp(){ document.getElementById("email_div").style.display='none'; email = document.getElementById("email"); $.post("/send_otp", { "email":email.value, "csrfmiddlewaretoken":"{{csrf_token}}" }, function(data, status){ if(status=="success"){ otp_from_back = data; document.getElementById("otp_div").style.display='block'; } } ); } function post(path, params, method = 'post') { const form = document.getElementById('post-form'); form.method = method; form.action = path; for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } } document.body.appendChild(form); form.ajax_send_otp(); } // Submit post on submit var form … -
Django - get id in form
I try to develop a web app with Django and Stripe API. But my problem is i'd like to allow visitor to register/login. Then if the user is connected he can use a form to create a company (one user can get n companys) then when this form is validate there are a redirection to STRIPE API to pay an abonments. So i've theses databases : User (name, adress, ...) Company (company name, employees,...) Transaction(subscription plan, idUser, idCompany) I don't know how to get the CompanyId because when the company form is validate there are a redirection to stripe api then if payment = "ok" redirect to sucess page. I try to use input hidden but its doesn't work because I didn't get the id in the company form because the company didn't create yet. Someone get ideas ? Thanks a lot -
Problems with a Form to Edit a Model in Django - Reverse for 'variable name' not found
I'm currently having an issue to display a form, the following code is a depiction of the problem: views.py class LeadUpdate(UpdateView): model = Leads fields='__all__' template_name_suffix = '_update_form' urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), path('', include('django.contrib.auth.urls')), path('edit/', views.edit, name='edit'), path('add_client/', views.add_client, name='add_client'), path('add_company/', views.add_company,name='add_company'), path('add_lead/', views.add_lead, name='add_lead'), path('add_call/', views.add_call, name='add_call'), path('add_status/', views.add_status, name='status'), path('leads_view/', views.leads_view, name='leads_view'), path('client_view/', views.client_view, name='client_view'), path('deal_view/', views.deal_view, name='deal_view'), path('<int:project_id>/',views.LeadUpdate.as_view(), name='edit_lead') ] The problem I have corresponds to the last URL The dashboard displaying the list and the web app is design such that when the user clicks the number you can edit the form dashboard.html <table class="styled-table"> <thead> <tr> <th>Project ID</th> <th>Agent</th> <th>Company</th> <th>Country</th> <th>Modelling Services</th> <th>Est. Closing Date</th> <th>Est. Revenue</th> <th>Est. # of Licenses</th> <th>Status</th> </tr> </thead> <tbody> {% for lead in leads %} <tr> <td><a href="{% url 'project_id' lead.project_id %}">{{lead.project_id }}</a></td> <td>{{ lead.agent }}</td> <td>{{ lead.company }}</td> <td>{{ lead.country }}</td> <td>{{ lead.modeling_services }}</td> <td>{{ lead.estimated_closing_date }}</td> <td>{{ lead.expected_revenue }}</td> <td>{{ lead.expected_licenses }}</td> <td>{{ lead.status }}</td> </tr> {% endfor %} </tbody> </table> This is the file edit_lead.html {% extends "base.html" %} {% block … -
Check if the last file in os.listdir()
I need to know if the file currently checked in the os.listdir is the last file. I need it in a condition I have. Here is the code: # iterate through all files in directory for filename in os.listdir(edgar_path): # open and read with open(edgar_path + filename, 'r') as file: # rearrange by date (column 3) tsv_file = sorted(list(csv.reader(file, delimiter='|')), key=lambda t: t[3]) # get date today today = datetime.datetime.now() # get start date and end date depending on the first and last row start_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d") end_date = datetime.datetime.strptime(tsv_file[len(tsv_file) - 1][3], "%Y-%m-%d") # check print logger.debug(start_date) logger.debug(end_date) # if within date range if start_date <= today <= end_date: logger.debug('pass condition 1') # if not within date range, but # the date today is greater than the end date # and its the last file being checked so it still passes elif today >= end_date: logger.debug('pass condition 2') # add to delete files if both conditions are unmet else: files_to_delete.append(filename) logger.debug('no pass') Any help is appreciated. -
Django How do add reply to rich editor
I create a post and this post's comment in my page. Users can comment on posts and I use rich editor(ckeditor) for this. But I want users to reply on comments too. Because of this, I added "Reply" button. When the user clicks the "reply" button, I want to redirect to ckeditor and add the message to ckeditor. LİKE THİS; Actually, I don't want something that complicated, Just user to know reply to other user it works for me. My models: class UserPosts(models.Model): postTitle = models.CharField(max_length=100, verbose_name="Title") postContent = RichTextUploadingField(null=True, verbose_name="Content") username = models.ForeignKey( User, on_delete=models.CASCADE, blank=True ,null=True, verbose_name="Username") class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) My Views: def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) messages = UserMessages.objects.all().filter(post_id =postDetail.id) if request.method == "POST": #New Message if request.method == "POST": #New Message form = MessageForm(request.POST,request.FILES) if form.is_valid(): form.instance.username = request.user form.instance.post = postDetail form.save() return redirect("detail",postDetail.id) context= { "detail":postDetail, "messages":messages, "form":form, } return render(request,"DetailPost.html",context) and my HTML: {% if request.user.is_authenticated %} <div class="comment-user "> <form method="POST" class=" "> {% csrf_token %} {{form.media}} <div class="form-group "> {{ form }} </div> <div class=""> <button type="submit" class="btn btn-primary btn-block">Submit</button> </div> … -
What should i use for front-end vue.js/react or django templates?
I know that big projects typically use django REST for back-end and vue.js or react for front-end, so my question is how do I choose what I should do? And why do big projects use two different frameworks? -
i need to create test for my models in django
i need to create some test for one of method of models but i cant do that model in my project: class Member(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def borrowed_books(self, genre): pass def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): title = models.CharField(max_length=50) genre = models.CharField(max_length=50) def __str__(self): return self.title class Borrowed(models.Model): member = models.ForeignKey('Member', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) i need create test for borrowed_books borrowed_books get one genre for Input variable and return list of book id this genre i need to Write test for none list variable and return correct lenght But contains incorrect book id class MemberAppTest(TestCase): def setUp(self): ali=Member.objects.create(first_name='xxx', last_name='yyy') Member.objects.create(first_name='zzz', last_name='kkk') Book.objects.create(title='fff' , genre='m') def test_borrowed_books(self): self.assertIsNone(Book.genre) What should I do? -
Pagenation firestore data in python
Hey there i need to Pagenate this code can you guys please help me out i tried the docs but not able to get hold of it. cases = db.collection(u'hospitals').document(request.session['hospital_email']).collection('cases').where( u'status', u'==', "done").where("formstatus", "==", "draft").order_by(u'date').limit(3).get() for i in cases: cases_data[i.id] = i.to_dict() print(cases_data[i.id], " ==>", i.to_dict()) print("") -
Django - how to return a pre_signed s3 (boto3) url to the client for download
I have the following code at my views.py def download(request, pk): obj = get_object_or_404(Files, pk=pk) file = obj.file_path download_url = s3_get_client(endpoint=obj.s3_backend.endpoint, access_key=obj.s3_backend.access_key, secret_key=obj.s3_backend.secret_key, region=obj.s3_backend.region ).generate_presigned_url( ClientMethod='get_object', Params={'Bucket': obj.s3_backend.bucket, 'Key': file}, ExpiresIn=1000 ) return download_url Now I would like to know how I can immediately instruct the clients browser to download the returned download_url. Thanks in advance -
how to download videos in user machine Django
Here is my views.py file from django.shortcuts import render,HttpResponse,redirect import youtube_dl from django.contrib import messages from pytube import * # Create your views here. def home(request): return render(request,'home.html') def download(request): if request.method == 'POST': video_url = request.POST.get('url') if video_url: ydl_opts = {'outtmp1': 'D:/'} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) messages.success(request, 'Video Downloaded.') return redirect('home') else: messages.warning(request, 'Please Enter Video URL') return redirect('home') return redirect('home') How can I download the video file to the user's machine? can anyone help me? -
I have problem when i import Django-Markdownx
i have problem when i import markdownx. i installed Markdownx for Django, and add in url. and i want to in models.py, but it has problem. problem is.. (Import 'markdownx.models' could not be resolved Pylance(reportMissingImports) [3, 6]) And my code Settings.py INSTALLED_APPS = [ 'blog', 'single_pages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'crispy_forms', 'markdownx', ] project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), path('markdownx/', include('markdownx.urls')), path('', include('single_pages.urls')), ] blog/models.py from markdownx.models import MarkdownxField class Post(models.Model): title = models.CharField(max_length=30) hook_text = models.CharField(max_length=100, blank=True) content = MarkdownxField() when i import this line, it has problem -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest' when a POST request is sent to Django
I'm trying to send a POST request which I have done through Postman and through the command line but I get the same result which is TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest' This request is going to my tasks route which then calls the create_task function # backend/tasks/urls.py from django.urls import path from django.views.decorators.csrf import csrf_exempt from . import views urlpatterns = [ path('tasks/', csrf_exempt(views.create_task)) ] This is views.create_task is in backend/task/views.py from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie from celery.result import AsyncResult from rest_framework.parsers import JSONParser from .tasks import create_task @csrf_exempt def run_task(request): if request.method == 'POST': data = JSONParser().parse(request) print("hello") print(data.data) task_type = data.data print(task_type) task = create_task.delay(int(task_type)) return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result } return JsonResponse(result, status=200) Nothing I print is being logged, so I don't know if what I'm doing is being properly parsed, all I get is the error in my title -
camelot-py: ccv2.error: OpenCV(4.5.3) error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
I want to get some data from table in pdf file with library camelot-py in my django project. But when I try to run a simple code, it rise Traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\io.py", line 117, in read_pdf **kwargs File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\handlers.py", line 177, in parse p, suppress_stdout=suppress_stdout, layout_kwargs=layout_kwargs File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\parsers\lattice.py", line 423, in extract_tables self._generate_table_bbox() File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\parsers\lattice.py", line 259, in _generate_table_bbox c=self.threshold_constant, File "C:\Users\myuser\Desktop\Project\siteproject\.venv\lib\site-packages\camelot\image_processing.py", line 36, in adaptive_threshold gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-c2l3r8zm\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' My code: import camelot pdf_file = 'C:/Users/myuser/Desktop/statement_7022035.pdf' csv_file = 'C:/Users/myuser/Desktop/ex.csv' def export_csv(pdf_file, csv_file): tables = camelot.read_pdf(pdf_file) tables.export(csv_file, f='csv', compress=True) OS: Windows 10 Python version: 3.7.5 All dependencies for Windows have been installed successfully (Ghostscript and ActiveTcl). Camelot-py have been installed with pip (pip install "camelot-py[base]"). My file is text-based PDFs Please, tell me, where I have done mistake. -
how to use (from itertools import chain) to search multiple model
i want to search field of a multiple model in a single search view here is what i tried i know this is not a clean and better way to do that's why i am looking for a clean and better way to do it i read it is possible with (from itertools import chain) but i did not completely understand how to use it in my function based views without passing so many context here is my view def search_item(request): search_item = request.GET.get('search') if search_item: story = Story.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) news = News.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) Stock = stock.objects.filter(Q(title__icontains=search_item)|Q(written_by__icontains=search_item)) return render(request, 'search_result.html', {'ttts':ttt,'story':story,'news':news,'stock':Stock,}) thank you -
Superuser is not login in admin in django why after creating superuser it is not login to admin
models.py (adding all requirement )when i create superuser and try to login it is not accessing , i have also added AUTH_USER_MODEL= 'Myappname.User'in setting.py but it is not working can anyone help me to find solution class User(AbstractUser): G = [ ('Female', 'Female'), ('Male', 'Male'), ('Others', 'Others'), ] first_name = models.CharField(max_length=50 ) last_name = models.TextField(max_length=50 ) phone = models.CharField(max_length=15 ) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) Gender = models.CharField(max_length=150,choices=G ,default='',null=True,blank=True) def __str__(self): return self.first_name def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return User.objects.get(email=email) except: return False def isExists(self): if User.objects.filter(email = self.email): return True return False is_staff = models.BooleanField(('Staff status'),default=False,) is_active = models.BooleanField(('Active'),default=False,) class Email(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="emails" ) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') recipients = models.ForeignKey(User, on_delete=models.PROTECT, related_name='receiver') . .... -
'User' object is not subscriptable : Django
Data is stored in database along with the following error. ERROR TypeError at /auth/email-register 'User' object is not subscriptable Request Method: POST Request URL: http://127.0.0.1:8000/auth/email-register Django Version: 3.2.6 Exception Type: TypeError Exception Value: 'User' object is not subscriptable Exception Location: C:\xampp\htdocs\Projects\Barter\Authentication\views.py, line 72, in post Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sun, 05 Sep 2021 17:46:29 +0000 CDOE models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager import datetime import os # Create your models here. def filepath(request, filename): old_filename = filename timeNow = datetime.datetime.now().strftime('%Y%m%d%H%M%S') filename = "%s%s", (timeNow, old_filename) return os.path.join('product_images/'+str(filename)) # Create your models here. class CustomUserManager(BaseUserManager): def _create_user(self, email, **extra_fields): if not email: raise ValueError("Email must be provided") user =self.model( email = self.normalize_email(email), **extra_fields ) user.save(using=self._db) return user def create_user(self, email, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, **extra_fields) def create_superuser(self, email, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=1024) first_name = models.CharField(max_length=1024, null=True) last_name = models.CharField(max_length=1024, null=True) user_mobile = models.CharField(max_length=1024, null=True) user_image = models.ImageField(upload_to=filepath, null=True) user_bio = models.CharField(max_length=4096, null=True) user_dob … -
Pure CSS radial timer with Django
I know that it's possible to create timed animations in pure CSS, and I've been able to get a 5 minute radial timer working in CSS the way I'd like. I'm just getting started with Django, and I'm curious whether I can make this functional for users. If someone visits my page, would Django be able to pull their visit time and pass it to the CSS animation, so that the animation is at the same point in the progression for all visitors? Is there any way to make the animation progression persistent upon page refresh as well? I'm very interested to know if there is any JavaScript-free solution to this, even if it is unwieldy. -
Django total price of OrderItems in Cart
How can i get "total" price of items of OrderItem in cart model from these models down below? I tried doing something in views but I get attribute error that QuerySet' object has no attribute 'total'. views.py def cart(request): cart = Cart.objects.filter(order_user=request.user) order_items = OrderItem.objects.filter(cart__in=cart) total = 0 for i in order_items: total = i.quantity * i.item.price + cart.total cart.update(total=total) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) ordered = models.BooleanField(default=False) total = models.IntegerField(default=0, help_text="100 = 1EUR") order_items = models.ManyToManyField(Item, related_name='carts', through=OrderItem ) -
What is the best way to create a 'list' associated with a model?
I want to be able to associate a company name in my models with a list of 'milestone' percentage points, in order to calculate how far each company is from the nearest milestone. For example: List_Of_Milestones = [5, 10, 15, 20, 25] Current_Progress = 9.5% Example Output = "Company A is 0.5% away from the 10% milestone, and 4.5% above the 5% milestone." The logic is simple from a Python standpoint, but I can't get my brain around how I would create this in a model setup and allow the user to set their own list of milestones.