Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Incorrectly Configured lookup_field error in ```HyperlinkedModelSerializer```
Myself Dhinesh. But I'm a beginner at Django Rest Framework. Here, I'm trying to change the lookup_field from pk to a custom field (IP_Address). But I'm getting this error again and again. Help to resolve this issue. Getting ImproperlyConfigured at /api/nodes/192.168.1.200/ Could not resolve URL for hyperlinked relationship using view name "nodemaster-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Models.py class NodeMaster(models.Model): Device_Manufacturer = models.CharField(max_length=50, choices = MANUFACTURER) Device_Type = models.CharField(max_length=50, choices = DEVICE_TYPE) Physical_Location = models.CharField(max_length= 50, null= True) IP_Address = models.CharField(max_length=50,unique = True ) Community_String = models.CharField(max_length = 50, null = False) def __str__(self): return self.IP_Address Serializers.py class NodeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = NodeMaster fields = '__all__' lookup_field = "IP_Address" views.py class NodeViewSet(viewsets.ModelViewSet): serializer_class = NodeSerializer queryset = NodeMaster.objects.all() lookup_field = "IP_Address" urls.py node_list = NodeViewSet.as_view({ 'get':'list', 'post' : 'create' }) node_detail = NodeViewSet.as_view({ 'get':'retrieve', 'put' : 'update', 'patch' : 'partial_update', 'delete' : 'destroy' }) urlpatterns = format_suffix_patterns([ path('', node_list, name = 'nodemaster-list'), path('<str:IP_Address>/', node_detail, name='nodemaster-detail') ]) -
pdf kit generating extra blank page
I'm using python pdf kit to generate pdf from html. Page contents are coming correctly to pdf but there is one extra blank page coming. How to get rid of this? I'm using Django def verify(request): try: import pdfkit pdf_options = { #'page-size': 'Letter', 'orientation': 'Portrait', 'page-width': '19in', 'page-height': '14in', 'margin-top': '0.15in', 'margin-right': '0.15in', 'margin-bottom': '0.15in', 'margin-left': '0.15in', 'encoding': "UTF-8", # 'custom-header': [ # ('Accept-Encoding', 'gzip') # ], # 'no-outline': None } pdf_url = APP_URL + '/certificate?c=QWEPR5P' out_put_dir = BASE_DIR /'website/static/certificates/certificate.pdf' pdfkit.from_url(pdf_url, str(out_put_dir) , options=pdf_options) except OSError as e: return str(e) return HttpResponse("pdf genereated") -
I have a problem in user redirecting in django
I am a beginner and I am creating a forum using html, css, bootstrap, python and django. I created a view for deleting posts: class DeletePost(DeleteView): model = Post success_url = '/' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(author_post_id=self.request.user.id) When a user will click the "Confirm button", when he need to remove a post, i would like to redirect him to the same discussion's page in which there was the post that he deleted, but i don't know how. Can somebody help? Thanks in advance -
Using Jinga2 Loop Control extension
I would like to break out of a for loop in a template. I understand this is not possible in DTL, but according to the docs it is possible if using Jinja2 (with the Loop Control extension) as the template engine. So I have updated my settings.py to include { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'project4.jinja2.environment'}, }, I define the Jinja environment in jinja2.py: from jinja2 import Environment from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse def environment(**options): env = Environment(**options, extensions=['jinja2.ext.loopcontrols']) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env In my views.py is point to the jinja template file: return render(request, "jinja2/index.html", { "pages": page_obj, "liked": liked_posts }) But when I try to use the break statement in my loop like so: {% for like in liked %} {% if like.liked_post == page %} <span><button class="btn btn-secondary" id="unlike">Unlike</button></span> {% break %} {% else %} <span><button class="btn btn-secondary" id="unlike">Like</button></span> {% endif %} {% endfor %} I receive the following error: Invalid block tag on line 30: 'break', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? What am I missing? Should the Jinja2 environment be be created in my views.py? -
can anyone tell me why pagination doesn't woek
How do I use pagination with Django ? this code is using django and this is the code i try alot of ways to do it but it doesn't work this website is blog website please help me with How can I do that? home.html <nav aria-label="Page navigation example"> <ul id='pagination' class="pagination justify-content-end container-fluid"> <li id='hasPrevious' class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li id='hasNext' class="page-item"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> views.py def home(request): context = {"blogs" : BlogModel.objects.all()} context["services"] = Service.objects.all() context["works"] = RecentWork.objects.all() return render(request,"home.html", context) def blogs_pagination(request,page_number=1): blogs_query = BlogModel.objects.all().order_by("-created_at") blogs_query = Paginator(blogs_query, 3) blogs = blogs_query.page(page_number) current_page_pagination = blogs_query.page(page_number) has_next = current_page_pagination.has_next() has_previous = current_page_pagination.has_previous() total_pages = blogs_query.num_pages return JsonResponse( { "blogs": [blogs.serialize() for blog in blogs], "totalPages": total_pages, "hasNext": has_next, "hasPrevious": has_previous, },safe=False ) -
In Django REST framework, how do I call my serializer's validate method and also validate the required fields are submitted?
I'm using Python 3.9 with the Django REST framework (v 3.12.2). In a view, I validate that the object fields were submitted properly like so ... @api_view(('POST',)) def save_to_sheet_from_form(request): valid_ser = ValidateNewCoopSerializer(data=request.data) if valid_ser.is_valid(): ... do valid actions ... return Response(post_data, status=status.HTTP_201_CREATED) else: return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST) My serializer is set up like below ... class ValidateNewCoopSerializer(serializers.Serializer): # Set all fields as not required and allow_blank=true, so we can combine all validation into one step id=serializers.CharField(required=False, allow_blank=True) coop_name=serializers.CharField(required=False, allow_blank=True) street=serializers.CharField(required=False, allow_blank=True) address_public=serializers.CharField(required=False, allow_blank=True) city=serializers.CharField(required=False, allow_blank=True) state=serializers.CharField(required=False, allow_blank=True) zip=serializers.CharField(required=False, allow_blank=True) county=serializers.CharField(required=False, allow_blank=True) country=serializers.CharField(required=False, allow_blank=True) websites=serializers.CharField(required=False, allow_blank=True) contact_name=serializers.CharField(required=False, allow_blank=True) contact_name_public=serializers.CharField(required=False, allow_blank=True) contact_email=serializers.CharField(required=False, allow_blank=True) contact_email_public=serializers.CharField(required=False, allow_blank=True) contact_phone=serializers.CharField(required=False, allow_blank=True) contact_phone_public=serializers.CharField(required=False, allow_blank=True) entity_types=serializers.CharField(required=False, allow_blank=True) scope=serializers.CharField(required=False, allow_blank=True) tags=serializers.CharField(required=False, allow_blank=True) desc_english=serializers.CharField(required=False, allow_blank=True) desc_other=serializers.CharField(required=False, allow_blank=True) req_reason=serializers.CharField(required=False, allow_blank=True) def validate(self, data): """ Validation of start and end date. """ errors = {} # required fields required_fields = ['coop_name', 'websites', 'contact_name', 'contact_name_public', 'entity_types', 'req_reason'] for field in required_fields: if not data[field]: errors[field] = 'This field is required.' # contact info contact_email = data['contact_email'] if 'contact_email' in data else None contact_phone = data['contact_phone'] if 'contact_phone' in data else None if not contact_email and not contact_phone: errors['contact'] = 'Either contact phone or contact email is required.' if errors: raise serializers.ValidationError(errors) return data The … -
Change assign Django field with only the string as a key
I want to change the data of a Django field with only the string as a key. Example: person = Person.objects.get(pk=1) person['name'] = 'John' person.save() My Code: changes: dict[str, Any] = json.loads(request.body) user: User = User.objects.get(id=user_id) for key in changes.keys(): user[key] = changes.get(key) user.save() response = json.dumps([{ 'Success' : 'User changed successfully!'}]) return HttpResponse(response, content_type='application/json') I get the following error message: TypeError: 'User' object does not support item assignment How should I do this? Thank you! -
Function to resend otp not working in django project
I have madefunction that resends otp when the 'resend Otp' lick is clicked. This is django project. The following are the codes that I wrote. html (this page extends base.html) <a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a> <script type="text/javascript" src="{% static 'jquery-3.6.0.min.js' %}"></script> <script type="text/javascript" src="{% static 'regd_ajax.js' %}"></script> js file function ReSendOTP(username, mess_id){ mess = document.getElementById(mess_id); mess.innerText = "Sending..."; $.ajax({ type: 'GET', url: '/user/resendOTP', data: {usr:username}, success: function(data){ mess.innerText = data; } }) } views.py def resend_otp(request): if request.method == 'GET': get_user = request.GET['usr'] if User.objects.filter(username = get_user).exists() and not User.objects.get(username = get_user).is_active: user = User.objects.get(username=get_user) user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return HttpResponse("Resend") return HttpResponse("Can't Send OTP") urls.py from .views import resend_otp path('resendOTP', resend_otp) So here I am requesting a resend otp for the "username: rick.bhardwaj27@gmail.com" but I am getting the follwing error in the console jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found) -
check if quiz time ended in django
I want to check if time if the quiz is ended while the user is answering the quiz and if time is finished user will be redirected to another page the problem is that I can't find a way to start the check process without reloading the page if there is a way to make it work or if there is another way better than this I am all ears thanks in advanced models.py class Quiz(models.Model): name = models.CharField(max_length=30) start_date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) duration = models.IntegerField(null=True,blank=True) quiz_images = models.ImageField(upload_to=PathAndRename("images\\quiz_images"), default="images\\quiz_images\\default.png") slug = models.SlugField(max_length=8, null=True, blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) prof = models.ForeignKey(User, on_delete=models.SET_NULL, null=True,limit_choices_to={'is_prof':True}) class Meta(): constraints = [ models.UniqueConstraint(fields=['name','course'],name='unique course') ] def __str__(self): return f"{self.name}/{self.course.name}" def save(self, *args, **kwargs): if not self.slug: self.slug = slug_generator(self) super().save(*args, **kwargs) image_resize(self.quiz_images.path) def get_absolute_url(self): return reverse('create-quiz-question', kwargs={'slug': self.slug}) @property def get_end_time(self): q_time=datetime.combine(self.start_date,self.start_time) return q_time+timedelta(minutes=self.duration) @property def is_open(self): if datetime.utcnow() > self.get_end_time: return False return True @property def get_quiz_grade(self): total = 0 for question in self.questions.all(): total += question.grade return total views.py def quiz_view(request,slug): quiz = Quiz.objects.filter(slug=slug).first() form = AnswerQuizForm(questions=quiz.questions.all()) # if not quiz.is_open: # if form.data: # form = AnswerQuizForm(data=request.POST,questions=quiz.questions.all(),user=request.user) # if form.is_valid(): # attemp=form.save() # attemp.quiz=quiz # attemp.save() …