Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTML for loop with filter
In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help! Model: class Question(models.Model): question = models.CharField(max_length=240) mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE) type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE) categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1) order = models.IntegerField(default=1) def __str__(self): return self.question class Question_Option(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1) option = models.CharField(max_length=240) correct = models.BooleanField() order = models.IntegerField(default=1) View: class Questions(LoginRequiredMixin, FormView): template_name = "questions.tmpl" def get(self, request, pk): context = { 'pk': pk, 'section': Mission_Section.objects.get(pk = pk ), 'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'), 'questions': Question.objects.filter(mission_section__pk = pk ), 'question_types' : Type_Question.objects.all(), 'questions_categories': Categories_Question.objects.all()} return render(self.request, self.template_name, context) HTML <input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required> <h1>{{ section.name }}</h1> <div id="contentDiv"> <ol> {% for question in questions %} <div name="question" class="form-group" id="question-{{question.id}}" > <form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'> <li><div class="input-group"> {% csrf_token %} {{ form.as_p }} <input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control"> <input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})"> </div> </form> <br> <!-- Options … -
JSON vs. Tables in PostgreSQL
I am trying to make a questionnaire and am considering 2 data structures: JSON: I could use JSON to store the different questions as follows: { "questions": [ { "question": "how old are you?", "type": "input_int", }, "question": "what is your name", "type": "input_string", }, { "question": "how are you today?", "type": "multiple_choice", "options": [ "good", "bad" ] }, ] } Or a table for each type of question: InputIntTable - Question - Order InputStringTable - Question - Order MultipleChoiceTable - Question - Options - Order I am using Django. Which way would be better both computationally, structurally, and cost wise to host. Which would take more storage? Thanks!! -
User model inherit AbstractBaseUser but still get AttributeError: 'User' object has no attribute 'check_passsword'?
I try to create custom model like this: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Create and saves a new User""" user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom User that support using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' and i add this line to my settings.py AUTH_USER_MODEL = 'core.User' Then i try to run this test class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test Creating a new user wint an email is successful""" email = 'test@example.com' password = 'Password123' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_passsword(password)) It still say AttributeError: 'User' object has no attribute 'check_passsword' Then i check this question , it says that the solution was inherit AbstractBaseUser to User model. I have done that, but i still got an error, what should i do? -
Dynamically Switch Database In Django App running inside docker container using environment variable
Problem: I want to switch the Django database after changing environment variables during run time Django app settings.py file PG_DB_USER = os.environ.get('PG_DB_USER', '') PG_DB_NAME = os.environ.get('PG_DB_NAME', '') PG_DB_PASS = os.environ.get('PG_DB_PASS', '') PG_DB_HOST = os.environ.get('PG_DB_HOST', '') PG_DB_PORT = os.environ.get('PG_DB_PORT', '') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': PG_DB_NAME, 'USER': PG_DB_USER, 'PASSWORD': PG_DB_PASS, 'HOST': PG_DB_HOST, 'PORT': PG_DB_PORT, } } There is a docker-compose.yml file where different services are listed along with the respective environment variable. After the successfully running of Docker containers, I am able to see all the environment variables inside containers using printenv or env command. Things I have Tried: I am trying to switch the environment variable using export PG_DB_NAME=**** command inside the container. But after running python manage.py shell and then import os and os.environ commands I am not able to see the changed environment variable PG_DB_NAME=****. Ps: All this command I will execute from a bash script to change the Django database during runtime. Thanks In advance. Any help would be much appreciated. -
How to implement something similar to list_display on generic list view?
I was trying to create a generic list template which would render all defined fields I wanted, just like the list_display from django admin.. I tried obj.values and obj.values_list, along with the specific fields, but these are not suitable when rendering choice fields since they bring a dict and a querysetdict and the get_foo_display is not available.. A managed=False also won't help since there is a filter of a field that can't be shown as well.. the .only() method also did not help because it does not 'cut' the fields from the obj.. I tried to copy the logic behind django admin list_display, but am I missing something in the generic list view? -
SSL Certificate for WSGI application
I have a Django project that I deployed using only the WSGI server provided by Django(no webserver like apache, ngnix ...). The problem is that I want to upload an SSL certificate for the HTTPS version of the website. How can I do it please ? Thank you in advance for your answers. -
Deploying Django to Elastic Beanstalk, migrations failed
I'm trying to deploy a project I've been working on with django. In development, i've been using SQLite, in production i'm trying to use MySQL. Usually when I create the EB instance, everything runs fine, and the console says the status is OK. Upon trying to deploy (running eb deploy in ebcli), I get met with the following error 2020/06/18 15:59:50.357281 [INFO] Copying file /opt/elasticbeanstalk/config/private/rsyslog.conf to /etc/rsyslog.d/web.conf 2020/06/18 15:59:50.358945 [INFO] Running command /bin/sh -c systemctl restart rsyslog.service 2020/06/18 15:59:50.394223 [INFO] Executing instruction: PostBuildEbExtension 2020/06/18 15:59:50.394243 [INFO] No plugin in cfn metadata. 2020/06/18 15:59:50.394252 [INFO] Starting executing the config set Infra-EmbeddedPostBuild. 2020/06/18 15:59:50.394273 [INFO] Running command /bin/sh -c /opt/aws/bin/cfn-init -s arn:aws:cloudformation:eu-west-2:433403353655:stack/awseb-e-qamgvpp7ft-stack/3e6774d0-b17c-11ea-9476-0a5f6fd32d44 -r AWSEBAutoScalingGroup --region eu-west-2 --configsets Infra-EmbeddedPostBuild 2020/06/18 15:59:50.721919 [ERROR] Error occurred during build: Command 01_migrate failed 2020/06/18 15:59:50.721944 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: Container commands build failed. Please refer to /var/log/cfn-init.log for more details. 2020/06/18 15:59:50.721949 [INFO] Executing cleanup logic 2020/06/18 15:59:50.722079 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[]}]} 2020/06/18 15:59:50.722249 [INFO] Platform Engine finished execution on command: app-deploy The culprit seems to be my db migration command, which is as follows, in '.ebextensions', named 'db-migrate.config' container_commands: … -
How to Access values from dictionary in Javascript
I am try to fetch my item_id field from model.py in django in query set form that below <QuerySet [<Item: Shoulder Bag Boys Shoulder Bag (Yellow )>, <Item: Sweeter Cotton Sweeter>, <Item: Shirt Full Sleeves Shirt>, <Item: Jacket Jackson Jacket>, <Item: Yellow Shoes Leopard Shoes>, <Item: Bag Mini Cary Bag>, <Item: Coat Overcoat (Gray)>, <Item: TOWEL Pure Pineapple>, <Item: Coat Pure Pineapple>, <Item: TOWEL Pure Pineapple (White)>]> Here is my JS Code $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true }) .done(function(data) { items = JSON.parse(data) console.log(items) for (var item in items) { console.log(item['product_id']) }; But it print in console `(index):765 {items: "<QuerySet [<Item: TOWEL Pure Pineapple>, <Item: Ba…s Leopard Shoes>, <Item: Jacket Jackson Jacket>]>"} (index):767 undefined` -
Ajax sending data twice in views.py django
I have this form in index.html and two submit button on clicking on one button named .graph-btn I m using jquery and ajax to send data from form to Django. Code: index.html <form action="{% url 'Graph' %}" method="post"> {% csrf_token %} <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <input type="submit" class="btn graph-btn" name="_graph" value="View Graph"> </td> <td> <input type="submit" class="btn predict-btn" formaction="{% url 'Graph' %}" name="_predict" value="Predict Closing Price"> </td> </tr> {% endfor %} </tbody> </table> </form> <script> $(".graph-btn").click(function(e) { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); var name = $text; console.log(name); $.ajax({ type:'POST', dataType: "json", url:'{% url 'Graph' %}', data:{ 'text': name, 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success:function(json){ }, error : function(xhr,errmsg,err) { } }); }); </script> here I want to take data from th row named .comp_name and pass the data to views.py in Django. There is problem is Ajax. views.py def graph(request): if request.method == 'POST': print("testing....") print(request.body) print(request.POST.get('text')) name = request.POST.get('text') context = { 'name': name, } print(context) return render(request, 'StockPrediction/chart.html') else: return render(request, 'StockPrediction/greet.html') I m using Print statement … -
Django create_or_update get changes fields
I'm using Django create_or_update function. In case of update, Is there a way to know the list of changed fields. Obviously I can use the get_or_create function before and in case, after this, I can update the model.. but I'm looking for a way to have this using a single query. Is it possible? -
Overwrite float:left property in span
I want the submit button to appear below the map. I can achieve this by deactivating float:left. How could I achieve this? I tried overwriting the properties of <Span>. <html> <head> <style> input[type=submit] {display: block} span {float:none} </style> {{ form.media }} </head> <body> And modifying the properties of the widget. Neither worked. widgets = { 'Location': OsmPointWidget(attrs={ 'map_width': 300, 'map_height': 300, 'style':'float:none'}), -
How to set href in Django template page
I'm fairly new to Django. I have homepage template that looks like this: {% block content %} {% for link in embededLinks %} <div class="row justify-content-center"> <blockquote class="twitter-tweet"> <p lang="en" dir="ltr">Do you get the impression that the Supreme Court doesn’t like me?</p> &mdash; Donald J. Trump (@realDonaldTrump) <a href="{{%link%}}">June 18, 2020</a> </blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </div> {% endfor %} {% endblock %} The loop runs through a list of links for my website to display embedded tweets correctly. This html will be put in a base template I have. Only problem is I get an error at this line: <a href="{{%link%}}">June 18, 2020</a> The href link is generated in another python file and is of type str. Only thing is I'm not sure how to set the href using Django. -
Password not set for new django users
When a new user signs up for an account, the admin panel shows that a password has not been set for the user (despite saving it via views.py). Another strange thing I noticed is that the password is being saved to the email field in the database. The code appears fine. Not sure where I went wrong. Any help would be greatly appreciated. sign up html template {% if user.is_authenticated %} <h2>currently logged in as {{ user.username }} </h2> {% else %} <h1 class="h5 text-center">Create Account</h1> <h4>{{ error }}</h4> <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" name="username" autocomplete="username" placeholder="Username" id="id_username" required> </div> <div class="form-group"> <label for="password1">Password</label> <input type="password" class="form-control" name="password1" placeholder="Password" autocomplete="new-password" required id="id_password1"> <small>Password must be at least 8 characters</small> </div> <div class="form-group"> <label for="password2">Confirm Password</label> <input type="password" class="form-control" name="password2" placeholder="Confirm Password" autocomplete="new-password" required id="id_password2"> </div> <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password.</li> <li>Your password can’t be entirely numeric.</li> </ul> <!-- <div class="form-group"> <div class="custom-control custom-checkbox text-small"> <input type="checkbox" class="custom-control-input" id="sign-up-agree"> <label class="custom-control-label" for="sign-up-agree">I agree to the <a target="_blank" href="utility-legal-terms.html">Terms &amp; Conditions</a> </label> … -
MultiValueDictKeyError in Django trying to change profile pic
i ve got this . I just want to change profile informations in that request i tried to change first_name and last_name. Here is my views.py. Check my code and tell me what's wrong . I need a solution for my error, i didnt try anything because i dont understand and know django very well And thank you ! views.py def profile(request): if request.method == 'POST': if not request.POST['first_name'] == '' and not request.POST['first_name'] == request.user.first_name: if not request.POST['last_name'] == '' and not request.POST['last_name'] == request.user.last_name: if not request.FILES['image'] == '': User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() User.profile.image = request.FILES['image'] User.profile.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.save() return redirect('profile') elif not request.POST['last_name'] == '' and not request.POST['last_name'] == request.user.last_name: if not request.POST['first_name'] == '' and not request.POST['first_name'] == request.user.first_name: if not request.FILES['image'] == '': User = request.user User.profile.image = request.FILES['image'] User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() User.profile.save() return redirect('profile') else: User = request.user User.first_name = request.POST['first_name'] User.last_name = request.POST['last_name'] User.save() return redirect('profile') else: User = request.user User.last_name = request.POST['last_name'] User.save() return redirect('profile') elif not request.FILES['image'] == '': if … -
How to center Text Under iFrame when text is wrapped around it
I have my iframe floating left and text wrapped around it. I'm trying to put text under it aligned center but everything I've tried seems to not work or mess the whole format up.. I have the code and preview here. https://codepen.io/Religion/pen/QWydbow. and what's on codepen below . Thanks! <style> .container p { font-size:1.2rem; } .container { height:100%; max-height:100%; } </style> <div class = "container"> <iframe style = "float:left;margin:5px 25px 0 0;margin-bottom:20px; width:350px; height:300px;" src="https://embed-fastly.wistia.com/deliveries/7f74ec7de31d90e32a1d465fcebc1d0e12a27d18/file.mp4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <h2 class = "all-headings">Periodontal Maintenance</h2> <p><strong>Periodontal diseases are infections of the gums, which gradually destroy the support of your natural teeth.</strong> There are numerous disease entities requiring different treatment approaches. Dental plaque is the primary cause of gum disease in genetically susceptible individuals. Daily brushing and flossing will prevent most periodontal conditions.</p> <br> <h2 class = "all-headings">Why is oral hygiene so important?</h2> <p>Adults over 35 lose more teeth to gum diseases, (periodontal disease) than from cavities. Three out of four adults are affected at some time in their life. The best way to prevent cavities and periodontal disease is by good tooth brushing and flossing techniques, performed daily.</p> <p>Periodontal disease and decay are both caused by bacterial plaque. … -
Django throws ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
Sorry in advance if my question looks obscure. This is the error thrown by Django when I'm trying to serve multiple Django media(videos) URLs in my React homepage.This is the stacktrace: Exception happened during processing of request from ('127.0.0.1', 5511) File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() Traceback (most recent call last): File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "D:\Django\myproject\app\env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Anshul\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine This is the React snippet: <video preload="metadata" id={this.props.id} muted ref={this.videoRef} onClick={this.play.bind(this,1,this.props.id)} onTimeUpdate={this.updateTime.bind(this,this.props.id)} onCanPlay={this.getReady.bind(this,this.props.id)}> <source src={this.props.source} type="video/mp4"/> </video> where video source refers to django media url provided by drf serializer.E.g this.props.source = 'http://localhost:8000/media/buck_bunny.mp4' The homepage contains multiple videos.The media URLs are fetched through API calls.Its a content feed page.Subsequent API calls to fetch … -
Django admin - make image appear over the django admin list view
Following up on a question from Django Admin - display image on hover. I'm able to make the image appear on hover like I was hoping. However, if the django admin list view only has a few items in it, part of the image appears behind the bottom of the list Here's an example of what it looks like, with some column headers greyed out The image extends beneath the bottom of the list (as hinted at by the appearance of the scroll bar). We'd like it to pop over the top, so the full image is visible regardless of the length of the list Here's the code we have def image_column(self, object) return format_html(text+" "+\ '''<a href="{}"" target="_blank" style="font-size: 18pt; position: relative;" onmouseover="document.getElementById('{}').style.display='block'; position: relative;" onmouseout="document.getElementById('{}').style.display='none';"><div style="position:relative">📷</div> <img id="{}" style="display:none; position: absolute; top: 0px; left: 0px; width:550px; border:5px solid; z-index:1000;" src="{}" /> </a>'''.format( url, img_id, img_id, img_id, url)) I've tried setting the position:absolute in the image tag to position:relative. This makes sure the whole image is displayed when you mouse over (expanding the containing row). However, it affects the the layout of the rest of the document, which is disorienting the user Thank you!!! -
whats is the problem on this code? need help to resolve django search error
Here is the views.py #search def search(request): query = request.GET.get["query"] if len(query)>78: allItem = Item.object.none() else: allItemTitle = Item.object.filter(title__icontains=query) allItemDescription = Item.object.filter(description__icontains=query) allItem = allItem.Title.union(allItemDescription) if allItem.count() == 0: messages.warning(request, "No result found") params = {'allItem': allItem, 'query':query} return render(request, 'home/search.html', params) #search here is the url.py path('search/', views.Search, name='search'), and finally HTML Source code is here {% extends 'base.html' %} {% load static %} {% block content %} <div class="breadcrumb-area section-padding-1 bg-gray breadcrumb-ptb-2"> <div class="container-fluid"> <div class="breadcrumb-content text-center"> <div class="breadcrumb-title"> <h2>Shop 3 Column</h2> </div> <ul> <li> <a href="index.html">Home 01 </a> </li> <li><span> &gt; </span></li> <li class="active"> shop </li> </ul> </div> </div> </div> <div class="shop-area pt-70 pb-100"> <div class="container"> <div class="container"> <h3>Search Results</h3> {% if allItem|length < 1 %} <p>No Search result found</p> did not match any document Your search query:<b>{{query}}</b> {% endif %} <div class="row"> {% for item in object_list %} <div class="col-lg-4 col-md-6 col-sm-6 col-12"> <div class="product-wrap mb-50"> <div class="product-img default-overlay mb-25"> <a href="{{ item.get_absolute_url }}"> <img class="default-img" src="{{ item.image }}" height="463" width="370"alt=""> <span class="badge-black badge-right-0 badge-top-0 badge-width-height-1">{{ item.label }}</span> </a> <div class="product-action product-action-position-1"> <a title="Add to Cart" href="{{ item.link }}" target="_blank"><i class="fa fa-shopping-cart"></i><span>Shop Now</span></a> </div> </div> <div class="product-content-2 title-font-width-400 text-center"> <h3><a href=""></a>{{ item.title }}</a></h3> <div class="product-price"> {% … -
How can I set some value to inherited model class field in Django model?
I made one model(ModelA) in which 2 choices present there, I am inheriting this model, in the other two models CHOICES = (("work", "work"), ("Home", "Home")) class ModelA(models.Model): type_of_address = models.CharField(choices=CHOICES) ... class ForWorkModel(ModelA): type_of_address--->work class ForHomeModel(ModelA): type_of_address--->Home I want to inherit the model and want to set some field values, as I mentioned in the code. Is there any way? -
Django 'holding page' and redirect for background processes
I have a form (IngestFormView), which on submission kicks off multiple background processes (dealing with files uploaded in the form). I also have an API view (IngestStatusView) which shows the status of the various background processes. Finally, I have a second form (IngestCompletionFormView) which is dynamic, based on the results from the various background processes I need users to be redirected to IngestCompletionFormView, but not until the aforementioned processes have concluded. I am really quite new to JavaScript, but I know I need to do something with AJAX/JQuery to show the user the, regularly updated, status from IngestStatusView, before redirecting the user to IngestCompletionFormView. Does anyone have any recommendations for how to achieve this? I don't think I can do anything on IngestFormView as I need that to deal with form errors, so adapting it could become complex. So I had wondered if I should created a separate view to sit between the two form views. This view will then use AJAX/JQuery to call IngestStatusView and update the user on progress. Then, based on a field in IngestStatusView, it would identify that all background tasks have concluded, and redirect to IngestCompletionFormView. Thank you for any thoughts. -
Lists are currently not supported in HTML Input
I am having this problem with my browsable API: "Lists are not currently supported in HTML input." Here are my models: class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos', null=True, blank=True) My Serializers: class ImageSerializer(serializers.ModelSerializer): class Meta: model = BreedImage fields = ['id', 'breedImage'] class BreedSerializer(serializers.ModelSerializer): BreedImages = ImageSerializer(many=True, allow_null=True, required=True) class Meta: model = Breed fields = ['name', 'BreedImages'] My view: class BreedList(generics.ListCreateAPIView): parser_classes = (MultiPartParser,) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None -
Does LiClipse admit Django Templates?
I am new to Django/Python and LiClipse (Django 3, Python 3.8, Liclipse 6.1.0), and when writing the html templates, I find that the Django blocks seem to interfere with the html correction. For instance, this code in base.html: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <meta name="generator" content="Bootply" /> <title>Report</title> <title>Este es un título</title> </head> <body> <h4>Home page de prueba de cjg</h4> </body> </html> Everything is fine, but if I add {% load static %} <!-- CSS --> {% block css %} {% endblock %} <!-- JAVASCRIPT --> {% block js %} {% endblock %} right after the title I get errors like Stray end tag “head”. for /head and An “body” start tag seen but an element of the same type was already open. Seems that the editor won't recognize django blocks. Is there any configuration I should make or some plugin I should add?. Thanks in advance for your help. -
How to split a queryset in several tranches to implement a "load more" logic using Django/jQuery to build a blog?
I am building a blog and display the 10 latest blog posts from the query which fetches the last 100 blog-posts from the database. I then want to implement a "load more" button to display another 10 blogposts and so on and so forth until all 100 are displayed. So my basic idea is that I fetch all 100 in the view and then populate the DOM using jQuery on each "load more" click. How can I accomplish this? Do I need Ajax calls to trigger a view for each button click? And how to handle the DOM since it is populated with Django variables. I guess I somehow have to re-trigger the for-in / end-for Django loop to make the new posts append and not overwrite the existing DOM? From a tutorial I tried to approach a paginator solution but I don't know how to link this to jQuery/make the magic on the frontend. blog.views def render_blog(request, template="blog.html"): category_count = get_category_count() # Display last 10 blog posts on landing page, make pagination in 10x steps via button click most_recent = Post.objects.order_by('-timestamp')[:99] post_list = Post.objects.all() paginator = Paginator(post_list, 10) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except … -
ORA-00904: "TOOL_WEBPAGE"."ID": invalid identifier
I have a preexisting database which I am trying to access. I have already ran the command python manage.py makemigrations dashboard and python manage.py migrate, however I am getting an error when trying to migrate -> Unable to create the django_migrations table (ORA-2000: missing ALWAYS keyword) -
How to update the django model after useing filter or order_by?
I wanna make a website that users can update the information. here is part of my website But I have a problem here, the update only works when it is in the normal order, it won't work when I order by price or order by rank or after I filter by some choice (e.g Dell, N2840). Here is my code view.py. if request.method == 'POST' and 'update_bt' in request.POST: i = 0 asin = [] alldata = Output.objects.all() for i in alldata: asin.append(i.asin) while i < len(request.POST.getlist('brand')): Output.objects.filter(asin = asin[i]).update(List = request.POST.getlist('list')[i]) Output.objects.filter(asin = asin[i]).update(brand = request.POST.getlist('brand')[i]) Output.objects.filter(asin = asin[i]).update(cpu = request.POST.getlist('cpu')[i]) Output.objects.filter(asin = asin[i]).update(screen = request.POST.getlist('screen')[i]) Output.objects.filter(asin = asin[i]).update(ram = request.POST.getlist('ram')[i]) Output.objects.filter(asin = asin[i]).update(Type = request.POST.getlist('type')[i]) Output.objects.filter(asin = asin[i]).update(model = request.POST.getlist('model')[i]) Output.objects.filter(asin = asin[i]).update(os = request.POST.getlist('os')[i]) Output.objects.filter(asin = asin[i]).update(DVD = request.POST.getlist('DVD')[i]) Output.objects.filter(asin = asin[i]).update(keyboard = request.POST.getlist('keyboard')[i]) Output.objects.filter(asin = asin[i]).update(security = request.POST.getlist('security')[i]) Output.objects.filter(asin = asin[i]).update(vc = request.POST.getlist('vc')[i]) i += 1 alldata = Output.objects.all() return render(request, 'polls/base.html', {'alldata': alldata}) I understand why it only works in this way, but I just don't know how to make it work in every possible situation. I am new to Django. Does anyone know how to make it work? Thank you.