Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I tie user behavior on Django website to a specific user?
Note: I would prefer to avoid JavaScript and 3rd party services. I am implementing my own logging and would like to track user actions so I can better understand why exceptions are being thrown. I was initially using a session variable in middleware to later pull a request.session.session_key to identify a user. def CreateSessionMiddleware(get_response): def middleware(request): request.session['sentinel'] = 'value' return middleware However, when the user logs out, the entire session is flushed, including my sentinel key and I lose track of this user. I have also seen the concept of "fingerprinting" a browser, but I'm not sure if enough detailed information about the user is available through request.headers. I'm currently in development and don't have any experience with tracking users in a production environment. Are there any pure Django solutions to following users' journeys through a website? Thanks! -
How to avoid repeated code in views in Django?
I have several function based views in a django project, and I noticed that they have some repeated code, in fact, they all do the same thing: def my_view(request): form = MyForm(request.POST or None) if requqest.POST: if form.is_valid(): do_somethin() and_something_else() return redirect('another:page') return render(request, 'my/tempalate.html', {'form': form}) The only thing that is different is the url where the user is redirected to in case of a succcesful form validation, the template, and maybe the form in the future. Is it a good idea to use something like this to avoid that repetition?: def a_view(request, success_redirect_url, template): form = MyForm(request.POST or None) if request.POST: if form.is_valid(): do_something() and_something_else() return redirect(success_redirect_url) return render(request, template, {'form': form}) and then reuse it in other views that have the repeated code? like: def my_view1(request, url='another_page', template='my/template.html'): return a_view(request, url, template) -
Simplest way to add a view to my Django admin UI?
What is the simplest way to add a view to my Django admin UI? That is, add a URL mysite.com/admin/my-view so that visiting that URL acts like the rest of admin (in particular, requires similar permissions). There is a whole page on this, but it's not obvious to me how to piece it together. https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#adding-views-to-admin-sites says you can add a get_urls to your AdminSite class. Okay, so I need my own AdminSite class. And I need to register it in apps, maybe? I did this: class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path('my-view', self.my_view, name='my-view') ] return my_urls + urls def my_view(self, request): # do something .. admin_site = MyAdminSite(name='my_admin') and this in urls.py: from .admin import admin_site urlpatterns = [ path('admin/', admin_site.urls), and this in unchanged in INSTALLED_APPS in settings: 'django.contrib.admin', But, now it only shows the admin for the one app, instead of for all the apps. So how do I get it to auto-discover all the apps like it used to? Or is there a simpler way? P.S. There is also a question on this, but the answer didn't have enough detail for me to use it. -
Permissions in React and Django
I have a web application built with HTML/CSS/JS/Django which is now being converted to a React.js/DRF project. I would like to slowly integrate React.js so I will be converting one page at a time. This is a SaaS LMS platform. There will be different levels of permissions for each page (e.g. can_edit_video, can_view_video, etc) which I have already implemented in Django but have not ever coded in React.js. Where should the permissions be handled on the front-end? What I mean is, I could make this a MPA and have Django fully handle permissions at the view level (seems easiest) when serving the template or I could make it a SPA and handle permissions on the backend, then pass the user permissions to React to display the appropriate content/components. What should be the deciding factor on approach to take? -
supervisor: couldn't exec start_daphne.bash: ENOENT supervisor: child process was not spawned (daphne )
I'm trying to make the supervisor call a script to run daphne, here's what' i get in the log file (daphne.access.log) when i start the supervisor (sudo supervisorctl restart daphne): supervisor: couldn't exec /home/mfatfouti/Apps/Tunnel/start_daphne.bash: ENOENT supervisor: child process was not spawned and here's the script i'm calling (start_daphne.bash): #!/bin/bach NAME="Tunnel-daphne" DJANGODIR=/home/mfatfouti/Apps/Tunnel DJANGOENVDIR=/home/mfatfouti/Apps/venv echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/mfatfouti/Apps/venv/bin/activate source /home/mfatfouti/Apps/venv export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Start daphne exec ${DJANGOENVDIR}/bin/daphne -p 8001 Tunnel.asgi:application and this is the supervisor (daphne.conf): [program:daphne] command=/home/mfatfouti/Apps/Tunnel/start_daphne.bash user=mfatfouti numprocs=1 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/var/log/daphne.access.log stderr_logfile=/var/log/daphne.error.log stdout_logfile_maxbytes=50MB stderr_logfile_maxbytes=50MB stdout_logfile_backups=10 stderr_logfile_backups=10 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 any idea what i'm doing wrong ?? -
How to set a custom value for model field in django RetrieveUpdateDestroyAPIView?
I have this RetrieveUpdateDestroyAPIView class in my api views and on update it doesn't automatically update a data field named as published. I want to manually update when the PUT request is sent. How can I do that. Here is the code models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = ( ('published', 'Published'), ('draft', 'Draft') ) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=100) excerpt = models.TextField(null=True) content = models.TextField() slug = models.SlugField(max_length=250, unique_for_date=True) published = models.DateField(null=True, default=timezone.now) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts', default=1) status = models.CharField( max_length=10, choices=options, default='published') objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-published',) def __str__(self): return self.title view.py from rest_framework import generics from blog.models import Post from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = Post.postobjects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer -
Run Python function from within CherryPy webpage with djgano
My project is a client/server model project with Python, CherryPy and Django. The Python program has various server like functions (adding/removing/editing stuff from/to the database, running commands, etc). It's a SQLite database so I would want the server to be the one solely charge of writing to the database and the client WebApp is just a portal into what the database has as far as values and telling the server what to do. When the python program starts one of its tasks is to initializes a CherryPy server that hosts a Django website as sort of a GUI to the server app. I use the following thread to start the CherryPy Web server: class ClientThread(object): HOST = get_setting_val('BindIP') # Function to read "BindIP" from an ini file. PORT = int(get_setting_val('Port')) # Function to read setting from ini file DIR = get_setting_val('InstallDir') # function to read setting from ini file. STATIC_ROOT = DIR + '/static/' def mount_static(self, url, root): """ :param url: Relative url :param root: Path to static files root """ config = { 'tools.staticdir.on': True, 'tools.staticdir.dir': root, 'tools.expires.on': True, 'tools.expires.secs': 86400 } cherrypy.tree.mount(None, url, {'/': config}) def run(self): cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True, }) self.mount_static(settings.STATIC_URL, … -
The error was: <lambda>() missing 1 required positional argument: 'collation'
when i try to run: python manage.py inspectdb > models.py this error occur in tha models.py , the database is mssql -
for loop in html template and saving values in a variable
i have a html template where i am sending a list(array) from my python file. now i am running a loop in html file and its showing the list perfectly but i want to save every element in a global variable of html and then use this variable. my code is: ''' {%for i in title_list%} {{i}} <br> <br> {%endfor%} ''' here title_list is the list and i want to save the variable i in a new declared variable. how to declare a variable in html and store such type of value in it? -
How to add email and name fields into SendMail upon user creation in Django
I made a signal that triggers SendMail when I create a user. Only superusers can create users from the Admin site, the users can't register themselves. This is important form me. So the signal works well and when I create a new user it sends the email. My problem is that in the Django Admin when I create a user I am not able to add the email address and first and last name until I save the user. But when I save it sends the mail without the mentioned fields because that moment those are blank. How can I do that the signal wait for the second saving or modifying when I fill the email and name fields? models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) ... """I extended the User model with a Profile""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() """and here is the mail sending signal""" @receiver(post_save, sender=User) def send_new_user_data_email(sender, instance, created, **kwargs): # if a new user is created, compose and send the email if created: username = instance.username subject = 'Subject line' message = 'User: … -
Integrating Selenium Bot into Django
I have a chatbot that I made with selenium. This chatbot should work on multiple users. At the same time, I need to pull and push data from the chatbot. And I want users to be able to command the bot whenever they want. Closing the bot, Writing a message, etc. When the button is pressed from the panel, I want to raise the bot to its feet. I thought of many ways to do this. Django Celery build, Heroku, Docker Container or Aws Lambda Container . With which platform can I ensure that the bot works perfectly, that the communication takes place and that the cost is the least? Do you have a previous source? -
Django - [Errno 2] No such file or directory for Img.open(`image_path`)
I have a blog where users can upload and edit posts. I wanted to resize any uploaded image to a max. of 500*500px. For this purpose I created an if statement before save models.py def _upload_path(instance, filename): return instance.get_upload_path(filename) class Post(models.Model, HitCountMixin): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) image = models.ImageField(blank=True, null=True, upload_to=_upload_path) def __str__(self): return self.title def get_upload_path(self, filename): return "posts/images/" + str(self.user.username) + "/" + filename def save(self, *args, **kwargs): # resize image if self.image: img = Image.open(self.image.path) # Open image using self if img.height > 500 or img.width > 500: new_img = (500, 500) img.thumbnail(new_img) img.save(self.image.path) # saving image at the same path return super(Post, self).save(*args, **kwargs) Unforunalty the image path gets not recognized and I get an error [Errno 2] No such file or directory: '/Users/vic/Desktop/django_project/media/postimage1.jpg' This path is wrong! The upload-path is defined within the get_upload_path() function and should lead to /Users/vic/Desktop/django_project/media/posts/images/username/postimage1.jpg I tried to change the open path to img = Image.open(str(settings.MEDIA_URL) + self.get_upload_path(self.image.name)) or to hardcoded URL with localhost:8000... but nothing worked. If I remove the if statement the file gets uploaded in the correct path so the error must be at img definition. -
Returning error None Django html responding?
I am trying to make a to-do app in Django, Whenever I input a date in either string or Date, then it returns none to the todo list app model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) deadline = models.CharField(max_length=200) def __str__(self): return f'{self.title} {self.deadline}' class Meta: order_with_respect_to = 'user' task_list.html {% extends 'base/main.html' %} {% block content %} <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> <div class="header-bar"> <div> <h1>Hello {{request.user|title}}</h1> <h3 style="margin:0">You have <i>{{count}}</i> incomplete task{{ count|pluralize:"s" }}</h3> </div> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} </div> <div id="search-add-wrapper"> <form method="GET" style="display: flex;"> <input type='text' name='search-area' placeholder="Search your task" value="{{search_input}}"> <input class="button" type="submit" value='Search'> </form> {% if tasks|length > 0 %} <a id="add-link" href="{% url 'task-create' %}">&#x2b;</a> {% endif %} </div> <!-- Hidden form. Form submits new item positions --> <form style="display: none;" id="reorderForm" method="post" action="{% url 'task-reorder' %}"> {% csrf_token %} <input type="hidden" id="positionInput" name="position"> </form> <div id="tasklist" class="task-items-wrapper"> {% for task in tasks %} <div class="task-wrapper" data-position="{{task.pk}}"> <div class="task-title"> {% if … -
DRF DateField - error when saving form: Date has wrong format. Use one of these formats instead: YYYY-MM-DD
I'm POSTing a form to my Django Rest Framework backend. There is a DateField I am using which is optional depending on the form type the user is looking at. When the user can see the DateField and select the date, it submits appropriately and there are no issues. When the DateField is hidden, I am getting a formatting error when I submit the form (but shouldn't) The form renders the elements appropriately via HTML: When the date is VISIBLE: <div class="mt-2 text-center"> <input type="hidden" name="summative" value="127" id="id_summative"> <input type="hidden" name="evaluation_type" value="31" id="id_evaluation_type"> <div id="id_evaluation_levelFormGroup" class="form-group"> <label class="form-label" for="id_evaluation_level">Evaluation level</label> <select name="evaluation_level" class="form-control" required="" id="id_evaluation_level"> <option value="" selected="">---------</option> <option value="41">Formal</option> <option value="42">Informal</option> </select> </div> <div id="id_evaluation_dateFormGroup" class="form-group"> <label class="form-label" for="id_evaluation_date">Evaluation date</label> <input type="date" name="evaluation_date" value="2021-09-08" class="form-control" id="id_evaluation_date"> </div> </div> When HIDDEN: <div class="mt-2 text-center"> <input type="hidden" name="summative" value="127" id="id_summative"> <input type="hidden" name="evaluation_type" value="33" id="id_evaluation_type"> <input type="hidden" name="evaluation_level" value="43" id="id_evaluation_level"> <input type="hidden" name="evaluation_date" id="id_evaluation_date"> </div> The evaluation_date is not a required field, the model attribute looks like this: evaluation_date = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True ) My Serializer looks like this (includes the validation method for the date): class EvaluationSerializer(serializers.ModelSerializer): def validate_evaluation_date(self, attrs): # Get the date string date_string = self.context["request"].data["evaluation_date"] … -
Why isn't my ChoiceField rendering from my Django form onto the template?
I'm using django forms and trying to render the name of the form object stored in the dictionary key and its corresponding value stores a form.ChoiceField to display on the website. For some reason, it is only displaying the object location in memory e.g. <django.forms.fields.ChoiceField object at 0x04B304D8> rather than the dropdown itself. These dropdowns are just a selection from 0 up to N where N is the quantity of the item available in the database. Here is my Form Code name = forms.CharField(label="Employee Name", max_length = 200, required = False) jobsite = forms.CharField(label="Jobsite", max_length = 200, required = True) date_needed = forms.DateField(initial = now, required = True) SundryFields = {} def __init__(self, *args, **kwargs): sundries = kwargs.pop('sundries') super(CreateNewOrder, self).__init__(*args, **kwargs) # ? it works i guess ? for sundry in sundries: quantity_list = [(i, i) for i in range(sundry.quantity_available + 1)] self.SundryFields[sundry.name] = forms.ChoiceField(choices=quantity_list) Here is my View ```def orders(response): if response.method == "POST": form = CreateNewOrder(response.POST, sundries = Sundry.objects.all()) # holds information from form if form.is_valid(): cleaned_data = form.cleaned_data order = Order(name=cleaned_data["name"], jobsite=cleaned_data["jobsite"], date_needed=cleaned_data["date_needed"]) order.save() # delete these from the order -- no longer needed once an order object is created del cleaned_data["name"] del cleaned_data["jobsite"] del cleaned_data["date_needed"] # … -
Pybars does not compile jinja if condition and for loop
I am using saleor platform on a project. Im trying the compile emails having jinja templates syntax using pybars. But the pybars is not parsing the if condition and the for loop syntax. Please guide me on parsing this two. Thanks! context = { "site_name": "site_name", "order": { "items": [ "one", "two", "three", ] }, } source = """ {% if True %} <div> {{ site_name}} </div> {% endif %} <div> {% for line in order.items %} <tr> {{ line }} </tr> {% endfor %} </div> <div> <p><small>This email was sent to <a href="mailto:{{site_name}}">{{site_name}}</a>.</p> </div> """ from pybars import Compiler compiler = Compiler() template = compiler.compile(source) template(context) Output that i am getting is as below. '\n {% if True %}\n <div>\n site_name\n </div>\n {% endif %}\n\n\n <div>\n {% for line in order.items %}\n <tr>\n \n </tr>\n {% endfor %}\n </div>\n\n <div>\n\n <p><small>This email was sent to <a href="mailto:site_name">site_name</a>.</p>\n\n </div>\n\n' -
ModuleNotFoundError: No module named 'typing_extensions'
i am working in a blog site with django. my project urls.py code: from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name="home"), path('login/',views.authlogin,name="login"), path('signup/',views.signup,name="signup"), path('contact/',views.contact,name="contact"), path('about/',views.about,name="about"), path('logout/',views.authlogout,name='logout'), path('dashboard/',views.dashboard,name='dashboard'), path('updatepost/<int:id>',views.update_post,name='updatepost'), path('addpost/',views.add_post,name='addpost'), path('delete/<int:id>',views.delete_post,name='deletepost'), ] but it shows me File "C:\Users\ABU RAYHAN\Desktop\projects\miniblog\blog\urls.py", line 3, in <module> from.import views File "C:\Users\ABU RAYHAN\Desktop\projects\miniblog\blog\views.py", line 1, in <module> from typing_extensions import Required ModuleNotFoundError: No module named 'typing_extensions' i am new here pardon my mistake. -
I need to extract data from database using ajax in django
I need to extract data from the database and view the results on a chart in the view, the charts should change dynamically when the values in the database change(the model is done to get the data of users after submitting a survey Here is my model. class Survey(models.Model): gender=models.CharField(max_length=200) Age = models.CharField(max_length=200) Nationality=models.CharField(max_length=200) Gorvernate = models.CharField(max_length=200) Maritalstatus=models.CharField(max_length=200) Employmentstatus=models.CharField(max_length=200) children=models.CharField(max_length=200) Education =models.CharField(max_length=200) IncomePerMonth=models.CharField(max_length=200) class Meta: db_table = 'form_surey' I tried this in the view: <script> $.ajax({ type: 'GET', url: "{% url 'pie-chart' %}", data: {{gender}}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("Success"); } }, error: function (response) { console.log(response) } }); const labels = ['Male','Female']; const data = { labels: labels, datasets: [{ label: 'Gender', backgroundColor: ['rgb(255, 99, 132)', 'rgb(54, 162, 235)', ], borderColor:[ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', ], data: {{gender|safe}}, }] }; const config = { type: 'bar', data: data, options: {} }; // === include 'setup' then 'config' above === var myChart = new Chart( document.getElementById('myChart'), config ); </script> -
I'm using Django ImageField but I can't access the images in my posts.html page
I'm using ImageField in Django but when I try to access them in my html pages, it's not working. Here is my model: class Post(models.Model): headline = models.CharField(max_length=200) sub_headline = models.CharField(max_length=200, null=True, blank=True) thumbnail = models.ImageField(null=True, blank=True, upload_to="images", default="placeholder.png") body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, null=True) Here is how am trying to access the images in posts.views {% for post in posts %} <div> <div class="post"> <img class="thumbnail" src="{{post.thumbnail.url}}"> <div class="post-preview"> <h6 class="post-title">{{post.headline}}</h6> <p class="post-intro">{{post.sub_headline}}</p> <a href="{% url 'post' post.id %}">Read More</a> <hr> {% for tag in post.tags.all %} <span class="tag">{{tag}}, </span> {% endfor %} </div> </div> </div> {% empty %} <h3 align="center">No posts found...</h3> {% endfor %} For more information: views.py def posts(request): posts = Post.objects.filter(active=True) context = {'posts': posts} return render(request, 'base/posts.html', context) urls.py urlpatterns = [ path('', views.home, name="home"), path('posts/', views.posts, name='posts'), ] posts.html {% extends 'base/main.html' %} {% load static %} {% block content %} <div class="main-container"> <h3 align="center">Posts</h3> <div class="post-wrapper"> {% for post in posts %} <div> <div class="post"> <img class="thumbnail" src="{{post.thumbnail.url}}"> <div class="post-preview"> <h6 class="post-title">{{post.headline}}</h6> <p class="post-intro">{{post.sub_headline}}</p> <a href="{% url 'post' post.id %}">Read More</a> <hr> {% for tag in post.tags.all %} <span class="tag">{{tag}}, </span> … -
Return Nonze for Date Django submit
I am trying to make a to-do app in Django, Whenever I input a date in either string or Date, then it returns none to the todo list app model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) deadline = models.CharField(max_length=200) def __str__(self): return f'{self.title} {self.deadline}' class Meta: order_with_respect_to = 'user' task_list.html {% extends 'base/main.html' %} {% block content %} <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> <div class="header-bar"> <div> <h1>Hello {{request.user|title}}</h1> <h3 style="margin:0">You have <i>{{count}}</i> incomplete task{{ count|pluralize:"s" }}</h3> </div> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} </div> <div id="search-add-wrapper"> <form method="GET" style="display: flex;"> <input type='text' name='search-area' placeholder="Search your task" value="{{search_input}}"> <input class="button" type="submit" value='Search'> </form> {% if tasks|length > 0 %} <a id="add-link" href="{% url 'task-create' %}">&#x2b;</a> {% endif %} </div> <!-- Hidden form. Form submits new item positions --> <form style="display: none;" id="reorderForm" method="post" action="{% url 'task-reorder' %}"> {% csrf_token %} <input type="hidden" id="positionInput" name="position"> </form> <div id="tasklist" class="task-items-wrapper"> {% for task in tasks %} <div class="task-wrapper" data-position="{{task.pk}}"> <div class="task-title"> {% if … -
Crispy form don't look so pretty in django with bootstrap4?
i create a sell template in a good way , with just div class container and simple row with just a shadown, in column i add {{form|crispy}} of caulse i add {% load crispy_forms_tags %} tag, and again add CRISPY_TEMPLATE_PACK = 'bootstrap4' to setting, yeah i use bootstrap 4. the problem the form crispy not range good, look the photo so please help me! this my sell template {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block title%}{% endblock%} {% block content %} <!--container --> <div class="container"> <!-- row --> <div class="row"> <!-- column --> <div class="col-lg-2"> </div> <!-- end column --> <!-- column --> <div class="col-lg-8 shadow p-3 mb-5 bg-white rounded"> <div class="text-center" style="margin-bottom: 2em;"> <h3>Star sell your product</h3> <p>Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies</p> </div> <form action="/publish/" class ="put" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group "> {{ form.media }} {{ form|crispy}} <h5 class="m-2"> Add More Images</h5> </div> <button type="submit" class="site-btn">Next</button> </form> </div> <!-- end column --> <!-- column --> <div class="col-lg-2"> </div> <!-- end column --> </div> <!-- end row --> </div> <!-- end container --> {% endblock %} -
Django - error while saving an object in `TabularInline` while the primary key is a string and is readonly
I have the following models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) The Child model has a primary key (ID) of type string. Now I'm trying to display the children in a TabularInline inline inside the Parent admin form and I want the ID field to be readonly: class ChildMemberLinkAdmin(admin.TabularInline): model = Child extra = 0 fields = ("id", "name") readonly_fields = ("id",) @admin.register(Parent) class ParentAdmin(admin.ModelAdmin): fields = ("name",) inlines = (ChildMemberLinkAdmin,) I created a parent and a child in Django Shell, and verified each has an ID and name. They're displayed correctly in Django Admin. However, when I click the Save button in the Parent form (even without changing anything) I get an error "Please correct the errors below.". When I debugged it I noticed that child's id is somehow missing, which is weird because my Child instance already has an ID which is displayed as readonly in the TabularInline in the form. When I remove id from the ChildMemberLinkAdmin.readonly_fields everything works correctly. Any idea how to fix this? I'm using the latest Django version: 3.2 -
Filter booked appointments by business working hour
Business working hours(TimeField) are stored for everyday in UTC time. BusinessHours table business = models.ForeignKey(Business) day = models.CharField(max_length=10) opening_time = models.TimeField() closing_time = models.TimeField() Appointment table appointment_time = models.DateTimeField() I'm trying to get particular day's appointments for the stored business hours range(between opening_time and closing_time). Here is the query appointments = models.Appointments.objects.filter(service_start_time__week_day=3, service_start_time__gte=datetime.utcnow(), service_start_time__time__range=(day_obj.opening_time, day_obj.closing_time)) Sometimes the closing_time may be greater than the opening_time. Above query is not getting the records due to this reason. For 03:00(opening) Indian standard Time to UTC is 22:30 and 20:00(closing) corresponding UTC is 14:30. In this case closing time seems greater than closing time. Query doesn't filter anything even though appointments available. How to solve this problem? -
Create a django program where data is input in a form, a python code creates a graph using the data, and the graph is displayed beneath the same form
I'm very new to Django and wish to write a program that does the following. The user gives inputs into a form. On clicking submit a graph is displayed underneath the form (the user must not be redirected to a different page). This graph must be created by a python code using the inputs that were originally submitted in the form. So far I've been able to make a program where the graph is created and displayed in a different html page. But I want it to be displayed in the same page underneath the form. I'm using matplotlib to make the graph. The graph is saved as a png image. Is there some way to go about this using only django? Thanking all responses in advance. -
Django JS autocomplete with Materialize
I'm trying to get the Materialize autocomplete function to work with a django. But for some reason the content won't show I did allot of debugging but I can't seem to find why it is not working and showing the options. Im using the following view: def search_companies(request): """ Search for relations on company names basis. """ companies = Relation.objects.all() data = [] for company in companies: data.append(company.company_name) return JsonResponse({'data': data}) And the following JavaScript in the template function autocompleted(){ fetch('/orders/search_companies/') .then(response => response.json()) .then(data => { var my_data = data.data; let myConvertedData = {}; $.each(my_data, function (index, value) { myConvertedData[value] = null; }); document.addEventListener('DOMContentLoaded', function () { const inputField = document.querySelector('.autocomplete'); M.Autocomplete.init(inputField, { data: myConvertedData, limit: 50, minLength: 1, }); }); }); } autocompleted();