Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return incomplete body errors in django?
class OrderViewSet(viewsets.ViewSet): def list(self, request): orders = Order.objects.all() return Response({ "code": "success", "orders": orders, }) def create(self, request): comment = request.data["comment"] product_id = request.data["product_id"] order = Order(comment=comment, product_id=product_id) order.save() return Response({ "code": "success", }) I would like to return error if product_id is not supplied by the user in request body: "code": "invalid-request", "details": { "product_id": { "type": "required", "message": "Product id is required", } } Also, there's KeyError if comment isn't supplied, but I don't want to make comment mandatory in request body. How do I set it to '' if its not supplied & still return success? Thanks -
Use view/form in Django to upload a multiple files
Class below is used to create a form in Django and get neccesary information. Problem is, it offers only one file to upload. I need to upload multiple files. I use Crispy forms. My simplified view.py looks like: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} When I inspect page, object looks like: <input type="file" name="file_1" class="clearablefileinput form-control-file" id="id_file_1"> I want it to contain multiple atribute. How can I achive that? I can't get it to work using documentation (https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/). I have tried: widgets = {'file_1': form.ClearableFileInput(attrs={'multiple': True})} form.instance.file_1 = form.FileField(widget=form.ClearableFileInput(attrs={'multiple':True})) form.instance.file_1 = form.FileField(widget=form.FileInput(attrs={'multiple': True})) My models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") I can't find an example how to implement multiple files upload which could be implemented in my class. -
How do I reactivate a django server?
I'm very new to django web development in python and I'm currently following a course on building a simple django website. The problem is, I went to sleep and decided to shut down my computer. And now I think I need to reactivate the website or something because the website just says 'This site can't be reached'. I opened up the code and I'm not sure if I'm suppose to write a certain command in the terminal or something. The terminal is empty when before it was running the website and had stuff there. I do understand that it is going to stopping running the website when I shut down my computer because it's my computer hosting it, but I just need to know how to start running it again. So how do I 're-activate' a django website? -
Django queryset custom order
I would like to make a queryset, which will first order by title then by size, but the size should be custom ordered, like the order in the list. For example order_size_ist = ['S', 'M', 'L', 'XL', 'XXL' ] queryset = RawMaterial.objects.order_by('title', 'size') The size should be ordered first S, then M then L and so on. Any ideas ? Thank you in advance :) -
Add intermediate model fields to reverse relationship
I have two related models (Product and Recipe). There is a many-to-many relationship defined between them (with a through model). I am able to query the 'through' model fields using the below serializer, but I am unable to make this work the other way around (from Product to Recipe) models.py: class Product(models.Model): version = models.CharField(max_length=4) displayname = models.CharField(max_length=50,validators=[alphanumeric]) ... class Recipe(models.Model): ... ingredients = models.ManyToManyField(Product, through='RecipeInput', related_name='recipe_input') products = models.ManyToManyField(Product, through='RecipeOutput',related_name='recipe_output') class RecipeInput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) amount_min = models.FloatField(blank=True, null=True) class RecipeOutput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) amount_min = models.FloatField(blank=True, null=True) mj = models.FloatField(blank=True, null=True) serializers.py: class RecipeInputSerializer(serializers.HyperlinkedModelSerializer): product_id = serializers.ReadOnlyField(source='product.id') product_name = serializers.ReadOnlyField(source='product.displayname') class Meta: model = RecipeInput fields = ('product_id',"product_name", 'amount', 'amount_min', ) class RecipeOutputSerializer(serializers.HyperlinkedModelSerializer): product_id = serializers.ReadOnlyField(source='product.id') product_name = serializers.ReadOnlyField(source='product.displayname') class Meta: model = RecipeOutput fields = ('product_id',"product_name", 'amount', 'amount_min', 'mj', ) class ProductInputSerializer(serializers.HyperlinkedModelSerializer): recipe_id = serializers.ReadOnlyField(source='recipe.id') recipe_name = serializers.ReadOnlyField(source='recipe.displayname') class Meta: model = RecipeInput fields = ('recipe_id','recipe_name', 'amount_min', 'amount', ) class RecipeSerializer(serializers.ModelSerializer): ingredients = RecipeInputSerializer(source='recipeinput_set', many=True) products = RecipeOutputSerializer(source='recipeoutput_set', many=True) class Meta: model = Recipe fields = "__all__" depth = 1 class ProductSerializer(serializers.ModelSerializer): products_in = ProductInputSerializer(source='recipe_input', many=True) class Meta: model = Product … -
Pip hangs on installing packages
I'm using django in a virtual environment. I'm using powershell and trying to install pyopenssl. I try pip install pyopenssl: (bookmarks) bookmarks> pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting six>=1.5.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/d9/5a/e7c31adbe875f2abbb91bd84cf2dc52d792b5a01506781dbcf25c91daf11/six-1.16.0-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... it hangs on Installing build dependencies .... I've waited 30mins but nothing happened. I've also tried python -m pip install pyopenssl (bookmarks) bookmarks> python -m pip install pyopenssl Collecting pyopenssl Using cached https://files.pythonhosted.org/packages/b2/5e/06351ede29fd4899782ad335c2e02f1f862a887c20a3541f17c3fa1a3525/pyOpenSSL-20.0.1-py2.py3-none-any.whl Collecting cryptography>=3.2 (from pyopenssl) Using cached https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz Installing build dependencies ... \ And when I try pip -v install pyopenssl: (Since the ouput is large, i'm only showing the last part.) Added semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) to build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Removed semantic-version>=2.6.0 from https://files.pythonhosted.org/packages/a5/15/00ef3b7888a10363b7c402350eda3acf395ff05bebae312d1296e528516a/semantic_version-2.8.5-py2.py3-none-any.whl#sha256=45e4b32ee9d6d70ba5f440ec8cc5221074c7f4b0e8918bdab748cc37912440a9 (from setuptools-rust>=0.11.4) from build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' Installing collected packages: setuptools, wheel, pycparser, cffi, toml, semantic-version, setuptools-rust Creating C:\Users\Suhail\AppData\Local\Temp\pip-build-env-fwbrqqmx\overlay\Scripts Successfully installed cffi-1.14.6 pycparser-2.20 semantic-version-2.8.5 setuptools-58.1.0 setuptools-rust-0.12.1 toml-0.10.2 wheel-0.37.0 Cleaning up... Cleaned build tracker 'C:\\Users\\Suhail\\AppData\\Local\\Temp\\pip-req-tracker-86fcyvxc' 1 location(s) to search for versions of pip: * https://pypi.org/simple/pip/ Getting page https://pypi.org/simple/pip/ Found index url https://pypi.org/simple Looking up "https://pypi.org/simple/pip/" in the cache Request header has "max_age" as 0, cache bypassed Starting new HTTPS connection (1): pypi.org:443 https://pypi.org:443 "GET /simple/pip/ HTTP/1.1" … -
Django: How to add DeleteView and UpdateView
Hi I'm Student in django, i want to add UpdateView and DeleteView, can someone expert guys can help me to figure out (Forum website) :D i provide some of my views.py code class TopicView(View): def get(self, request, *args, **kwargs): tid = request.GET.get('id') print(tid) topic = Topic.objects.filter(id=tid).first() print(topic) # topic.clicks += 1 topic.save() username = check_result(request, topic) print(username) comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) @check_login def post(self, request, *args, **kwargs): topic_id = request.POST.get('topic', '') content = request.POST.get('content') topic = Topic.objects.filter(id=topic_id).first() username = check_result(request, topic) if content: user = UserInfo.objects.filter(username=username).first() comment = Comment(user=user, topic_id=topic_id, content=content) comment.save() comments = topic.comments() content = create_content_paginator(request, queryset=comments, page_size=5) content.topic = topic print(Form.errors) return render( request, 'topic.html', context={'username': username, 'content': content, 'form': Form} ) tid = Topic_id of post_id .. content = the content inside the topic class PublicView(View): @check_login def get(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() # semester = subject.semester username = request.session.get('name') return render( request, 'public.html', context={'username': username, 'form': Form, 'content': {'subject': subject}} ) @check_login def post(self, request, pid, *args, **kwargs): subject = Subject.objects.filter(id=pid).first() username = request.session.get('name') print(username,'asdasd') user = UserInfo.objects.filter(username=username).first() name = request.POST.get('title') content = request.POST.get('content') … -
Django: unable to make a calculation inside a template
I've created a e-commerce Django application and in the back office of this application, I have a page that is supposed to show some statisctics. I'm trying to display benefits or losses. For the costs, I've created a @property in the model as following: class Statistics(models.Model): """ The Statistics model represents the statistics that can be calculated """ costs_infra = models.FloatField(verbose_name="Costs Infrastructure") costs_salary = models.FloatField(verbose_name="Costs Salary") class Meta: verbose_name_plural = "Statistics" def __str__(self): """Unicode representation of Statistics""" return " Infra costs: {}, Salary costs: {}".format( self.costs_infra, self.costs_salary ) @property def calculate_costs(self): return self.costs_infra + self.costs_salary For the total income, I've calculated it inside a view as following: @group_required('Administrator', 'Manager') def stats_home(request): total_users = User.objects.all().count() costs = Statistics.objects.all() subscriptions_1month = Subscription.objects.get(plan_name='1 Month') subscriptions_1year = Subscription.objects.get(plan_name='1 Year') subscriptions_3year = Subscription.objects.get(plan_name='3 Years') user_subscriptions_1month = UserSubscription.objects.filter(subscription=subscriptions_1month).annotate(Count('user', distinct=True)).count() user_subscriptions_1year = UserSubscription.objects.filter(subscription=subscriptions_1year).annotate(Count('user', distinct=True)).count() user_subscriptions_3years = UserSubscription.objects.filter(subscription=subscriptions_3year).annotate(Count('user', distinct=True)).count() income_per_subscription_1month = Subscription.objects.get(plan_name='1 Month').price * UserSubscription.objects.filter(subscription=subscriptions_1month).count() income_per_subscription_1year = Subscription.objects.get(plan_name='1 Year').price * UserSubscription.objects.filter(subscription=subscriptions_1year).count() income_per_subscription_3years = Subscription.objects.get(plan_name='3 Years').price * UserSubscription.objects.filter(subscription=subscriptions_3year).count() total_income = income_per_subscription_1month + income_per_subscription_1year + income_per_subscription_3years return render (request, "stats_home.html", locals()) An finally, I'm trying to make a simple calculation (total income - total costs) but I'm unable to do this inside the template, as far as I could see … -
how to use external webcam as an image scanner to save into the database?
I'm trying to use an external webcam as an image scanner, is'nt there a way to achieve that please , im using django as backend **3.2 version ** this is my models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) i have to instead of scan documents , just capture a picture of them from my web browser and upload them ? i know i have to use js to access webcam , but i dont know how to save it into the database thank you in advance .. -
custom message in raise PermissionDenied not working in Django rest
I tried raise PermissionDenied("Anonymous user") inside a custom permission function but the message I wrote is not showing in the api response. Instead, it is showing the default forbidden message that says you dont have permission to perform this action My snippet is here: class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request,view): slug = request.resolver_match.kwargs["slug"] if slug is not None and request.method == 'POST': if slug == "abc": user = request.user if user.is_staff: return True if user.is_anonymous: print("iam here") raise PermissionDenied("Anonymous user") elif slug == "mnp": return True else: return True Here in the above code I reached to ("iam here") but anonymous user is not printing instead showing the default message. -
Django QuerySet from one-to-many and from many-to-one
working on a project, where i came to a small problem with QuerySets. (Look at the bottom to see a short diagram of my model structure.) I tried to query some information of a BLOG-Model starting from the Collection-Model. Now is it better to query first the Entrie-Model and find somehow the Collection to afterwards find the Blog-Model and add the information in the end to the Collection? Or is there a better / faster way to get information directly from the parent Model? Normaly it is easy if you just have 1:n->1:n Relations because you can easily follow the foreignkey, but this confuses me. Here a short overview of my model structure: <--------------- QUERY DIRECTION ---------------- (BLOG) --(1:N)--> (ENTRIE) <--(N:1)-- (COLLECTION) BR, Felix -
How to store the path of a media file in Cassandra when using django-cassandra-engine?
Hey guys I am learning to implement Cassandra db with Django. In SQL db's we can store the path of a file in FileField, but how to do the same with Cassandra? Can anyone give some insights? Thanks in advance. -
send a specific queryset to all templates
I have a Django application which has notification.It uses Django channels this way that it takes user id in view and then at templates uses json_script to make the id a JS object. So i have to write the bellow code every where user=user.id context={....,"user":user} How can i write it one instead of every where? -
try and except not working in Django Rest Framework
I have written custom permission based on the http method and the user that is requesting. I have to use try and except at one point. But seems like it is not working properly. The snippet is here: class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request,view): slug = request.resolver_match.kwargs["slug"] print(slug) if slug is not None: if slug == "abc": try: user = request.user if user.is_staff: return True else: print("yes object") raise PermissionDenied("You need to be an admin to perform this action") except ObjectDoesNotExist: print("no object") raise PermissionDenied("Anonymous user") elif slug == "xyz": print("iam xyz") print(slug) return True else: print("nothing") return True Here the issue is when the request has a slug in its url and it is "abc", but no any user credentials is provided( no token in the headers), then the code of except ObjectDoesNotExist: should have worked, however, the print("yes object") is printing. It should only print yes object if there is user and it is not staff. The print I should be getting is ("no object"), because there is no user since the object doesn't exist. Also, I am getting permissiondenied message, instead the default 403 forbidden message. What … -
Prevent the release of the download file link
Hello to all Django lovers I have a question that I have not received an answer for a month. My question is: How to write a model and view in Django that only users who are registered in the site are allowed to download the file. That is, how can I prevent the publication of links to our files. Please suggest a way. -
how to call back tenant schema name django
im trying to return back tenant schema names in one of my tables data , im using django-tenant this is what im trying to achieve class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,default=1) full_name = models.CharField(max_length=150) @login_required def daily_vistors_detail_html(request,day): lists = BookingVisitor.objects.annotate(day=TruncDay('date')).filter(day=day).order_by('-pk') context = { 'lists':lists } sometimes i have to return back data's with its tenant domain ! <table class="w-full text-center table-auto display nowrap" style="width:100%" id="vistors"> <thead> <tr> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "admin" %}</th> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "full name" %}</th> <th class="p-2 text-xs text-white bglightpurple md:text-base">{% trans "tenant name" %}</th> </tr> </thead> <tbody id="list_vistors_daily" class="w-full"> {% for i in lists %} <tr> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{i.admin}}</td> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{i.visitor.full_name}}</td> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple">{{tenant name}}</td><!-- this is should return the current tenant name --> is there any way to return current tenant name from a view?!thank you in advance -
Without passing Request parameter How Can i get the Logged in Username in django
i make a class in a py file in my django project. In this i need the logged in person's username. in views.py file, every function i pass request perameter, so that i could easily get the logged username. but in other py file i make a class, and there how can i get the logged user??? Thanks. in class, i can not pass the request perametar. so i can not call requset.user. how can i get the logged user??? -
Django project - Scape the data using selenium and then save the data into live server database without using form
I have a website for which data is being displayed in real-time. To enter data into the database, currently, I am using selenium to extract the data from other sites and then putting those data into forms and save. This includes various steps and hence delays the process. My question: Is there any process to scrape the data using selenium externally and directly save those data into my live domain sqlite database? -
Random '>' not supported between instances of 'NoneType' and 'float' with xhtml2pdf
I'm using xhtml2pdf in a Django application to generate PDF files from Pandas html output. I'm having this error that raise randomly (not all times): Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python37\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python37\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\DEV\webdeploy\django_proj\django_app\views.py", line 171, in post return pdfDownload(pivot, data_stock, data_ecarts,annee_,request) File "D:\DEV\webdeploy\django_proj\django_app\views.py", line 310, in pdfDownload pdf = pisa.pisaDocument(BytesIO(html_styled.encode("ISO-8859-1")), result) File "C:\Python37\lib\site-packages\xhtml2pdf\document.py", line 144, in pisaDocument doc.build(context.story) File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 1079, in build self.handle_flowable(flowables) File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 955, in handle_flowable (self._fIdent(f,60,frame),_fSizeString(f),self.page, self.frame.id, File "C:\Python37\lib\site-packages\reportlab\platypus\doctemplate.py", line 890, in _fIdent return f.identity(maxLen) File "C:\Python37\lib\site-packages\reportlab\platypus\tables.py", line 421, in identity tallest = '(tallest row %d)' % int(max(rh)) Exception Type: TypeError at /iw/dataload/ Exception Value: '>' not supported between instances of 'NoneType' and 'float' It seems the error come from the ReportLab library where it is trying to get the max … -
Exclude if any of statement is true
I am building a Simple Blog Post web app, And I am trying to exclude items if any of items is true, But it is checking for all statements, I mean it is checking if all the statements are true which i don't expect. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) body = models.CharField(max_length=30) class Rate(models.Model): by_user = models.ForeignKey(User, on_delete = models.CASCADE) blog_of = models.ForeignKey(BlogPost, on_delete = models.CASCADE) rated_1 = models.BooleanField(default=False) rated_2 = models.BooleanField(default=False) completed = models.BooleanField(default=False) views.py def page(request): queryset = Rate.objects.filter(completed=False).exclude(rated_1=False, rated_2=False) context = {'queryset':queryset} return render(request, 'page.html', context) What's the Output ? It is showing queryset which is completed=False but not excluding if one of the exclude items is true. I have tried many times but it is still not working. Any help would be much appreciated. Thank You in Advance. -
Django CustomUser permissions: Add User & Can add user
I'm using Django 2.2.5. We have just transitioned our application to a CustomUser model. This appears to have changed the permission string for non-superusers. For example: with a CustomUser model, the superuser has these two permissions; Can add User and also Add User. I have an "admin" user role with a subset of the superuser permissions. I'm using the django-role-permissions package to define these roles. For this "admin" role I don't get both of these permissions, the default django user has the permission "Add User", and the CustomUser user has the permission "Can add user". The django-role-permission package can create the "Add User" permission, but not the "Can add user". Is there any way I can configure this behavior in Django 2.2.5? Where could I read up on these two sets of closely related permission names. -
Locking Failed! pipenv install requests
So i am trying to learn python and we were told that we will be using Django. As an advance, I tried setting up the environment, I ran into this problem right after typing in pipenv install requests The result is as follows Installing requests… Adding requests to Pipfile's [packages]… Installation Succeeded Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Locking Failed! Unable to create process using 'c:\.......\python\python39\python.exe"c:/....../python/python39/lib/site- packages/pipenv/resolver.py"' Can anyone help me with this problem please. -
How to POST multiple rows in django using ajax
how can i save multiple rows when click on save button. this is django framework. i have submitted my model and template file. but please help me to find out how to post multiple rows when click on save button this is my model class class Items(models.Model): item_name=models.CharField(max_length=50) item_code=models.CharField(max_length=50) desc=models.CharField(max_length=50) price=models.IntegerField() this is my template class <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AddBills</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <br /> <h2 align="center">Add Items</h2> <br /> <div class="table-responsive"> <form> {% csrf_token %} <table class="table table-bordered" id="crud_table"> <tr> <th width="30%">Item Name</th> <th width="10%">Item Code</th> <th width="45%">Description</th> <th width="10%">Price</th> <th width="5%"></th> </tr> <tr> <td contenteditable="true" class="item_name"></td> <td contenteditable="true" class="item_code"></td> <td contenteditable="true" class="item_desc"></td> <td contenteditable="true" class="item_price"></td> <td></td> </tr> </table> <div align="right"> <button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button> </div> <div align="center"> <button type="button" name="save" id="save" class="btn btn-info">Save</button> </div> </form> <br /> <div id="inserted_item_data"></div> </div> </div> </body> </html> <script> $(document).ready(function(){ var count=1; $('#add').click(function(){ count=count+1; var html_code="<tr id='row"+count+"'>"; html_code+="<td contenteditable='true' class='item_name'></td>"; html_code+="<td contenteditable='true' class='item_code'></td>"; html_code+="<td contenteditable='true' class='item_desc'></td>"; html_code+="<td contenteditable='true' class='item_price'></td>"; html_code+="<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>"; html_code+="</tr>"; $('#crud_table').append(html_code); }); $(document).on ('click','.remove',function(){ var delete_row=$(this).data("row"); $('#'+delete_row).remove(); }); $('#save').click(function(){ var item_name=[]; var item_code=[]; var item_desc=[]; var item_price=[]; $.ajax({ url:"", … -
"def save" - Detect if a field is completely blank - Django
In my Django models, I have a def save function. I need this function to see if a field is left blank completely. I need it to see if a field has been left blank every single entry and then return something to an HTML file. I'll attach my code below but I'm really stumped. I'm not sure how I can set a value in that function and get it all the way to my HTML. Is there an easier way? models.py class Data_Repo1(models.Model): user = models.ForeignKey(User, default=True, related_name="Data_Repo1", on_delete=models.PROTECT) date1 = models.DateField(blank=True, null=True) date2 = models.DateField(blank=True, null=True) class Meta: ordering = ['-pk'] def __str__(self): return self.date1 or 'None' def get_absolute_url(self): return reverse('repo1') def save(self, *args, **kwargs): if self.date1 is None: #Something Here - "self.date1 = NONE" else: return if self.date2 is None: #Something Here - "self.date2 = NONE" else: return super().save(*args, **kwargs) # Call the "real" save() method. views.py def repo1(request): context = {} context['Add_Repo'] = Add_Repo.objects.filter(user=request.user) context['Data_Repo1'] = Data_Repo1.objects.filter(user=request.user) context['Field_Repo1'] = Field_Repo1.objects.filter(user=request.user) if self.date1 is None: #NOT WORKING print('TEST') #NOT WORKING return render(request, 'sheets/list_repo/repo1.html', context) HTML {% for post in Data_Repo1 %} {% if date1 == 'NONE' %} <h1>ITS HERE</h1> {% endif %} <tr> <td><div><a href="{% url 'update_extinguisher' … -
How to place captcha on Django CreateView
I'm working in an existing codebase that uses Django Material. There is a CreateView defined as: class OurModelCreateView(LayoutMixin, CreateView): model = OurModel This view is getting lots of spam signups and so needs to have a captcha. I use Django Recaptcha, and I've set up a number of captchas in the past. However, I've never set one up on a generic view. If I create a Django form and define the captcha field in the form as always done in the past: from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 class OurModelForm(ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV3) class Meta: model = OurModel exclude = () and then specify form_class = OurModelForm on the CreateView, then I get an error stating that fields and the form_class can't both be specified at the same time. This is happening because Django Material's LayoutMixin defines fields: https://github.com/viewflow/django-material/blob/294129f7b01a99832a91c48f129cefd02f2fe35f/material/base.py (bottom of the page) So I think that the only way to do what I need is to dynamically insert the captcha field into the form. The following two attempts do not work: On the CreateView: def get_form(self, form_class=None): form = super(OurModelCreate, self).get_form(form_class) form.fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3) return form def fields(self): fields = [super().fields(*args, **kwargs)] fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3) return [field.field_name …