Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WAMP icon turns orange after adding mod_wsgi-express module-config results in httpd file
i am trying to deploy my django app on windows using wamp and mod_wsgi. the probleme is that the icone turns orange once i configure the httpd file and add the following lines resulting from the mod_wsgi-express module-config command : LoadFile "c:/users/zakaria/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/zakaria/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/zakaria/appdata/local/programs/python/python39" the error in the appache error log is stating : Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.base_exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.exec_prefix = 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39' sys.path = [ 'C:\\Users\\ZAKARIA\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', '.\\DLLs', '.\\lib', 'C:\\wamp64\\bin\\apache\\apache2.4.46\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Did you guys went trough a similar situation? Thanks in advance. -
Slugfield not working if field name is different from slug
Good evening, Django is completely new for me and it's my first question here. I'm trying to create a Webapp. I'm using Django, Python and MariaDB. I created a project with two apps and I have a model for each app. In the fist one I used "slug" as field name and everything is working fine. In the second one I wanted to differentiate that field giving a different name (bk_slug) defined as SlugField. I tried to use the same kind of instructions lines and modifying them for the filed name it seems not working. I cannot have the right URL (Class based ListView) and cannot acces to the DetailView.... Thanks in advance for your support. -
Why does React not seem to recognize Heroku's PORT env variable?
I am trying to deploy a frontend react application with a django backend. I am able to get Heroku's PORT environment variable just fine for the Django backend, but no matter what I do or try, process.env.PORT keeps returning undefined. I have tried adding a temporary variable that begins with REACT_APP that just reads the PORT variable in the procfile. Env files won't work because the PORT variable is dynamically allocated. Every resource I have found have said to either try a .env file or exporting the variable, but like I said, that is unrealistic because Heroku dynamically allocates the port. Any ideas? -
Add a skip parameter to Django CursorPagination
I'm looking to implement in Django 3(.1.7) something equivalent to the MongoDB cursor.skip() method. What I'm after is an additional query parameter to provide to my cursor-paginated REST endpoints in order to skip a given amount of items from the result of the query. I can't seem to find any example to obtain this result and I'd like not to reimplement the whole pagination class just to add this small addition. What's the right way to implement this? -
Event Listener for form submit is not working
What is the problem in the addEventListener method here? The code works until prepending the new_img, but when I am trying to make a form submit, the method is not even called. const reportForm = document.getElementById("report-form"); const img = document.getElementById("img"); reportBtn.addEventListener("click", () => { console.log("clicked"); new_img = document.createElement("img"); new_img.setAttribute("class", "w-100"); new_img.src = img.src; modalBody.prepend(new_img); reportForm.addEventListener("Submit", (e) => { e.preventDefault(); console.log("ajax method call"); const formData = new FormData(); formData.append("csrfmiddlewaretoken", csrf); formData.append("name", reportName.value); formData.append("remarks", reportRemarks.value); formData.append("image", new_img.src); $.ajax({ type: "POST", url: "reports/save/", data: formData, success: function (response) { console.log(response); }, error: function (error) { console.log(error); }, processData: false, contentType: false, }); }); }); The form is generated by django templates and placed inside the body of a modal like this: <input type="hidden" name="csrfmiddlewaretoken" value="FinPb8ZYsMj2RSHECGqKdMpLaLSofvs94LB5O7lcFOJpvLB4gUJn5ERaQz0a4DTz"> <div id="div_id_name" class="form-group"> <label for="id_name" class=" requiredField"> Name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="name" maxlength="200" class="textinput textInput form-control" required id="id_name"> </div> </div> <div id="div_id_remarks" class="form-group"> <label for="id_remarks" class=" requiredField"> Remarks<span class="asteriskField">*</span> </label> <div class=""> <textarea name="remarks" cols="40" rows="10" class="textarea form-control" required id="id_remarks"></textarea> </div> </div> <br> <button type="button" class="btn btn-info">Save</button> -
How can i get unlimited SMS in django?
I want to send unlimited SMS to user in my django project. I currently using twilio service provider with limited number of SMS. -
Unable to create a user at django admin panel
Well, I'm not really sure that this problem is widespread. When I try to add a user from django's admin panel, I get the error about: The module in NAME could not be imported: django.contrib.main.password_validation.UserAttributeSimilarityValidator. Check your AUTH_PASSWORD_VALIDATORS setting From the body of the mistake I learned that: Exception Value: The module in NAME could not be imported: django.contrib.main.password_validation.UserAttributeSimilarityValidator. Check your AUTH_PASSWORD_VALIDATORS setting. Exception Location: C:\Users\Dmitriy\PycharmProjects\FileTime\venv\lib\site-packages\django\contrib\auth\password_validation.py, line 29, in get_password_validators The main problem is that there's nothing about 'get_password_validators' in that line (29) in that file (password_validation.py). The interesting thing is that I can create a user from command line. So, what can I do to solve this problem? -
query URL (query string) problem about "paginator" and "filter" in Django
my views.py: def subcategory(request, category_url): category = get_object_or_404(Category, category_url=category_url) subcategories = Subcategory.objects.filter(category=category) products_list = Product.objects.filter(product_category=category) subcatid = request.GET.getlist('subcategory') print(subcatid) if subcatid: ids = [int(id) for id in subcatid] subcategories1 = Subcategory.objects.filter(category=category, id__in=ids) products_list = Product.objects.filter(product_category=category, product_subcategory__in=subcategories1) else: subcategories1 = None products_list = Product.objects.filter(product_category=category) page = request.GET.get('page', 1) paginator = Paginator(products_list, 2) try: pass products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if request.user.is_authenticated: wishlist = get_object_or_404(Wishlist, user=request.user.profile) else: wishlist = None ctx = {'products':products, 'products_list':products_list, 'wishlist':wishlist, 'subcategories':subcategories, 'category':category, 'subcategories1':subcategories1} return render(request, 'products/subcategory.html', ctx) my paginator html : <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if products.number|add:'-4' > 1 %} <li class="page-item"> <a class="page-link" href="?page={{ products.number|add:'-5' }}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"></span><< </a> </li> {% endif %} {% if products.has_previous %} <li class="page-item "> <a class="page-link page-link-prev" href="?page={{ products.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link page-link-prev" href="" aria-label="Previous" tabindex="-1" aria-disabled="true"> <span aria-hidden="true"><i class="icon-long-arrow-right"></i></span>قبلی </a> </li> {% endif %} {% for i in products.paginator.page_range %} {% if products.number == i %} <li class="page-item active" aria-current="page"><a class="page-link" href="">{{ … -
how to effectively use UUID model field with django
If someone had to build a similar web application like Instagram using Django and expect a large user base as the start up grow, i am wondering if indexing the UUID model field while using postgres as a database would be a good idea after having modified the initial User model provided by django. class User(AbstractUser): id = models.UUIDField(primary_key=True, index=True, default=uuid.uuid4, editable=False) settings.py AUTH_USER_MODEL = "users.User" I have mentioned Instagram as an example to consider Read and Write of the database field in the application. I look forward to hear from anyone familiar with database and django good practices. Thank you -
Load a Django Form into Template using jQuery and stay on same page after submitting?
I am using Django function based views with a single template which contains multiple tabs. Depending on which tab is selected I hide/show certain elements on the page by catching .click() event using jQuery. I populate the visible elements using Ajax requests to certain view functions. I added a new tab to submit data via a form. Currently I have an additional template containing the form. When the tab is clicked, I load the template into an element using jQuery.load(upload.html). The form populates and posts to a Django view through a modelForm. It works alright however I can't seem to figure out how to stay on the same form tab after posting. Any redirect from Django causes the main template to reload to the default starting tab. Also, if the user navigates to main_template/upload.html the form is loaded outside of the main template page. I would like to avoid this. Am I going about this wrong ? main_template.html <div id="myForm"></div> $("#tabButton").click(function(){ $("#myForm").load("upload.html"); }); upload.html <form method="post" enctype="multipart/form-data" action="{% url 'core:upload' %}"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} {% bootstrap_button "Upload" button_type="submit" %} </form> urls.py urlpatterns = [ url('upload', views.upload, name='upload'), ] views.py def upload(request): if request.method == 'POST': … -
How can I avoid duplicate SQL queries with Django model forms?
I have the following models: from django.db import models class Author(models.Model): name = models.CharField(max_length=30) class Article(models.Models): author = models.ForeignKey(Author, on_delete=models.CASCADE) text = models.TextField() and a generic CreateView from django.views.generic.edit import CreateView urlpatterns += [ path("", CreateView.as_view(model=models.Article, fields="__all__")) ] with the following template (article_form.html) <form action="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit"> </form> I am using Django Debug Toolbar to list the performed SQL queries for each web request. My question is: Why is the following SQL query for the author list performed twice for each request? And how can I avoid the duplicate query? SELECT "myapp_author"."id", "myapp_author"."name" FROM "myapp_author" Moreover, the debug toolbar says that the first query took only 0.5 ms, whereas the second took 42 ms! Almost 100x longer. How can this be? I am using Django 3.2 with an SQLite database. Thank you! -
How to display N number of Movies the staffs has and the N number of Staffs the Movies has in Django Rest-framework api
I'm Creating a site where I Have models.py like below class Staff(models.Model): staff_name = models.CharField("Staff Name", max_length=25) staff_dob = models.DateField("Staff Date of Birth", help_text="Staff Born Date") staff_gender = models.IntegerField(choices=GENDER, help_text="Staff's Gender") staff_about = models.TextField("About the Staff") staff_pic = models.ImageField(upload_to="Anime/Staff/images/") class Movies(models.Model): author = models.CharField(help_text="Author name of the movie", max_length=50) country_of_origin = models.CharField("Country Of Origin", max_length=20) start_date = models.DateField("Start Date") end_date = models.DateField("End date") status = models.IntegerField(choices=RELEASE_STATUS, help_text="Current status of the movie") staffs = models.ForeignKey(Staff, on_delete=CASCADE) I want to display N number of Movies the Staffs have and N number of Staffs the Movie have. I'm new to Django and rest_framework. Thanks in advance. -
django RelatedObjectDoesNotExist error while creating
models: class FullNameMixin(models.Model): name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True) first_name = models.CharField(max_length=255, default=None, null=True) last_name = models.CharField(max_length=255, default=None, null=True) class Meta: abstract = True class Meta: db_table = 'fullname' class User(FullNameMixin): id = models.BigAutoField(primary_key = True) username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) token = models.CharField(max_length=255, unique=True, null=True, blank=True) password = models.CharField(max_length=255) role = models.IntegerField(default=1) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.username class Meta: db_table = 'cga_user' class Profile(FullNameMixin): id = models.BigAutoField(primary_key = True) birthday = models.DateTimeField(null=True, blank=True) country = models.CharField(max_length=255, null=True, blank=True) state = models.CharField(max_length=255, null=True, blank=True) postcode = models.CharField(max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, null=True, blank=True) profession_headline = models.CharField(max_length=255, null=True, blank=True) image = models.ImageField(upload_to=get_upload_path, null=True, blank=True) profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True) cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile") gender = models.CharField( max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES ) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: db_table = 'profile' When i am creating Profile from django admin panel getting below error. e filename = self.upload_to(instance, filename) File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path instance.user, File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user. [24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997 … -
therw is an error of circular import how to resolve the error?
Django.core.exceptions.ImproperlyConfigured: The included URLconf 'travelproject1.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to display questions based on subcategory using Django Rest Framework?
I want to display all questions based on subcategory. This is my code : models.py class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) subcategory = models.CharField(max_length=40) class Meta: managed = True db_table = 'subcategory' def __str__(self): return self.subcategory class Question(models.Model): question_id = models.BigAutoField(primary_key=True) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) question = models.TextField() answer = models.CharField(max_length=255) class Meta: managed = True db_table = 'question' def __str__(self): return self.question serializers.py class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('subcategory_id', 'subcategory') class QuestionSerializer(serializers.ModelSerializer): subcategory = serializers.StringRelatedField() class Meta: model = Question fields = ('question_id', 'subcategory', 'question', 'answer') view.py @api_view(['GET', 'POST', 'DELETE']) def question_list(request): # GET list of question, POST a new question, DELETE all question if request.method == 'GET': questions = Question.objects.all() question = request.GET.get('question', None) if question is not None: questions = questions.filter(question__icontains=question) questions_serializer = QuestionSerializer(questions, many=True) return JsonResponse(questions_serializer.data, safe=False) # 'safe=False' for objects serialization elif request.method == 'POST': question_data = JSONParser().parse(request) questions_serializer = QuestionSerializer(data=question_data) if questions_serializer.is_valid(): questions_serializer.save() return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': count = Question.objects.all().delete() return JsonResponse({'message': '{} Questions were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT) /api/subcategory : [ { subcategory_id: 1, subcategory: "Mathematics" }, { subcategory_id: 2, subcategory: "History" } ] /api/questions : [ { question_id: 1, subcategory: 1, question: "10 … -
Django data in tables not showing up
My tables in my django don't show up , the titles for the table do but the data itself does not. can someone tell me what is wrong with my code dashboard.html {% extends 'accounts/main.html' %} {% block content %} {% include 'accounts/status.html' %} <div class="col-md-16"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="">Create Order</a> <table class="table table-sm"> <tr> <th>Title</th> <th>Language</th> <th>Rating</th> <th>Type of Media</th> <th>Genre</th> <th>Review</th> <th>Notes</th> <th>Date</th> <th>Update</th> <th>Remove</th> </tr> {% for media in mediass %} <tr> <td>{{media.title}}</td> <td>{{media.language}}</td> <td>{{media.rating}}</td> <td>{{media.type_of_media}}</td> <td>{{media.genre}}</td> <td>{{media.review}}</td> <td>{{media.notes}}</td> <td>{{media.date}}</td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} </table> </div> </div> {% endblock %} models.py from django.db import models class Media(models.Model): CATEGORY = ( ('Movie', 'Movie'), ('Tv Show', 'Tv Show'), ('Drama', 'Drama'), ('Other', 'Other'), ) NUMBER = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) GROUP = ( ('Action', 'Action'), ('Anime', 'Anime'), ('Comedy', 'Comedy'), ('Crime', 'Crime'), ('Fantasy', 'Fantasy'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Other', 'Other'), ) title = models.CharField(max_length=200, null=True) language = models.CharField(max_length=200, null=True) rating = models.CharField(max_length=200, null=True, choices=NUMBER) type_of_media = models.CharField(max_length=200, null=True, choices=CATEGORY) genre = models.CharField(max_length=200, null=True, choices=GROUP) review = models.CharField(max_length=1000, null=True) notes = models.CharField(max_length=1000, null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return … -
Django not finding The Project module:
Everyone This is my first Django project for university, our project name is Hotel and every time I run: python manage.py runserver I get : ModuleNotFoundError: No module named 'Hotel' The traceback is: Traceback (most recent call last): File "C:\python3\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\python3\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\python3\lib\site-packages\django\conf\__init__.py", line 82, in getattr self._setup(name) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\python3\lib\site-packages\django\conf\__init__.py", line 170, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\python3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Hotel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 22, in <module> main() File "C:\Users\LENOVO\Desktop\Hotel\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() … -
How can I get a username from django User Model
I have the following where a comment is posted via a POST request urlpatterns = [ path("recipes/comments/", RecipeCommentView.as_view(), name="post_comment"), # POST ] Views.py @permission_classes([AllowAny]) class RecipeCommentView(generics.CreateAPIView): queryset = models.RecipeComment.objects.all() serializer_class = RecipeCommentSerializer Serializers.py class UserSerialiser(serializers.ModelSerializer): class Meta: model = models.User fields = ["username"] class RecipeCommentSerializer(serializers.ModelSerializer): published_by = UserSerialiser(read_only=True) class Meta: model = models.PublishedRecipeComment fields = ["recipe", "published_by", "content", "created_at"] ordering = ["position"] Models.py class RecipeComment(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name="comments") published_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True) content = models.CharField(max_length=2500) created_at = models.DateTimeField(auto_now_add=True) I am using the User model from django.contrib.auth.models, how can I have the username of the currently logged in user attached to the published_by field? -
django uploading audio file returns null
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' class CreateSongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = ['title', 'audio_file', 'genre'] views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import parser_classes from rest_framework.parsers import FileUploadParser class SongView(APIView): def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) class PostSong(APIView): # here is the class <------------ serializer_class = serializers.CreateSongSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): title = serializer.data.get('title') genre = serializer.data.get('genre') filename = serializer.data.get('audio_file') song = models.Song(title=title, audio_file=filename, genre=genre) return Response(serializers.CreateSongSerializer(song).data, status=status.HTTP_200_OK) return Response({'Bad Request': 'Invalid Data'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs'), path('add-song/', views.PostSong.as_view(), name='add-song') ] Response { "title": "123", "audio_file": null, "genre": "123" } Everything works fine expect for when I try to upload a file it becomes null, I tried implementing the parser_class but that was getting rid of the form so I couldnt actually post data, how can … -
fetching data from models in django
i am bulding a ecommerce site i which i created two model name categoreis and subcategories in which subcategorie is related to categories with foreign key so a category name merch can have so many sub categories like shirt, tshirt, hoddies etc so what i want to achieve a navbar which which contain all the categories and all of them are dropdown when i click to that category i can see all the subcategories of it in dropdown menu here is my models.py class Categories(models.Model): name = models.CharField(max_length=100, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name here is my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() return render (request, 'home.html', {'category_list': category_list }) this is what i tried i know this not gonna work but it atleast all the categories in the nav bar here is what i want to achieve i hope you understan very well with this -
how to pass object from attr of button in django template to js
I want to pass a Python object to JavaScript via the HTML attribute. I used the following codes, but I did not get an answer. html code : <button style="margin: 7px" type="button" class="btn btn-primary user-button-edit" user-arg="{{ user|safe }}" data-toggle="modal" data-target="#exampleModalCenter"> js code : $(".user-button-edit").click(function() { var user = $(this).attr("user-arg"); console.log(user); console.log(user.name); $("#Userpermissions_6").prop("checked",true); }) the user.name --> undefined Due to the presence of ' in user object, it does not convert to Jason and gives an error. Does anyone have a solution? (I do not want to create an attribute for each data.) -
Django add dynamic fields with dynamic name attributes to front end and then insert it to Model
I have a Model which consists of almost 500+ fields. I want to take data through the front-end Form. But the issue is I can’t display all the 500 fields. what I want is I will add the fields which I need. like on day-1 I will add 3 fields. food = 230 , petrol = 500, rent = 700. on the second day, fields may vary. I can add 20 fields on the second day. on the third day data may be of different fields. like petrol = 200, cement= 5000 , steel = 100 etc etc and so on! Simple Solution is: I displayed all fields in HTML and submitted it to view and received in View function through Post Request! and then save() . But i want it to be dynamic! if request.method == 'POST': print("this is post") # print() food_expense=request.POST['food'] petrol_expense=request.POST['petrol'] easyload_expense=request.POST['easyload'] labour_expense = request.POST['labour'] equipments_expense = request.POST['equipments'] rent_expense = request.POST['rent'] cement_expense = request.POST['cement'] steel_expense = request.POST['steel'] other1_expense = request.POST['other1'] other2_expense = request.POST['other2'] other3_expense = request.POST['other3'] ..... .... fields upto 500+ # expense_paidby = request.POST['paid_by'] expense_paidby_id = request.POST['paid_by'] paidby= PaidBy.objects.get(id=expense_paidby_id) # expense_paidby = PaidBy.objects.get(name__icontains = request.POST['paid_by']) projectname_id= request.POST['pname'] project_in_which_expenses_made=ProjectName.objects.get(id=projectname_id) # project_in_which_expenses_made = request.POST['project_name'] date = request.POST['date'] … -
Why my Django Ajax form submit doesn't work?
I wrote a script that works perfectly when i put it bottom of html file but when copy code and paste it in dataforms.js file and of course put correct link in my html it doesn't work. HTML: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8" /> <title>Adminto - Responsive Bootstrap 4 Landing Page Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta content="A fully featured admin theme which can be used to build CRM, CMS, etc." name="description" /> <meta content="Coderthemes" name="author" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- App favicon --> <link rel="shortcut icon" href="images/favicon.ico"> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!--Material Icon --> <link href="{% static 'css/materialdesignicons.min.css' %}" rel="stylesheet"> <!--pe-7 Icon --> <link href="{% static 'css/pe-icon-7-stroke.css' %}" rel="stylesheet"> <!-- Magnific-popup --> <link href="{% static 'css/magnific-popup.css' %}" rel="stylesheet"> <!-- Custom sCss --> <link href="{% static 'css/style.css' %}" rel="stylesheet"> </head> <body> <!--Navbar Start--> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-bottom sticky sticky-dark"> <div class="container-fluid"> <!-- LOGO --> <a class="logo text-uppercase" href="index.html"> <img src="images/logo-dark.png" alt="" class="logo-dark" height="18" /> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <i class="mdi mdi-menu"></i> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto navbar-center" id="mySidenav"> <li class="nav-item active"> <a href="#home" class="nav-link">Introductions</a> </li> … -
Am using Python Django and I want to validate a NVarchar variable
I want to validate the 1st letter of the NVarchar and identify if it starts with 'P' or 'I' and then respectively switch between href tags. [This is the jobseqno from DB][1] [This is the actual condition that i want to modify][2] [1]: https://i.stack.imgur.com/PqtWc.png [2]: https://i.stack.imgur.com/UgnFW.jpg Thanks in Advance!! -
@property doesn't store value in DB
My model is like this: class Cart(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False,blank=False) total = models.FloatField(null=False,blank=False) @property def total(self): return self.quantity * self.product.price The total appears in my admin dashboard but when I inspect the db from the shell I don't get the total value, I get the other values: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2}]> Expected output: <QuerySet [{'id': 42, 'product_id': 11, 'quantity': 2, 'total': 29.00}]>