Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UpdateView with modelform object wont render summernotewidget
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class NewUpdateForm(forms.ModelForm): class Meta: model = PostForNewsFeed fields = ['title','content','pic','tags'] widgets = { 'content': SummernoteWidget(), } class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['title','content','pic','tags'] template_name = 'feed/create_post.html' def form_valid(self, form): if form.is_valid(): data = form.save(commit=False) data.user_name = self.request.user data.save() messages.success(self.request, f'Posted Successfully') return redirect('home3') <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form.media |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form> -
Change the location of a file uploaded via HTML form on submit
I have a form that asks for various inputs one of which is a file input. I want the uploaded files to be stored inside /media/images which is the case when I upload files from the admin console since I specified the upload location in models.py. How can I do the same and store the files that are uploaded via HTML forms in /media/images instead of /media? games.html: {% block body %} <div id="new_game_form" style="display:none; margin: 20px;"> <form class="row g-3" action="{% url 'new_game'%}" method="post"> {% csrf_token %} <div class="col-md-6"> <label class="form-label"><strong>Title</strong></label> <input type="text" class="form-control" id="title" name="title"> </div> <div class="col-md-6"> <label class="form-label"><strong>Sub Title</strong></label> <input type="text" class="form-control" id="sub_title" name="sub_title"> </div> <div class="col-12"> <label class="form-label"><strong>Description</strong></label> <input type="textarea" class="form-control" id="description" name="description"> </div> <div class="col-12"> <label class="form-label"><strong>Thumbnail</strong></label> <input type="file" class="form-control" id="thumbnail" name="thumbnail"> </div> <div class="col-12"> <label class="form-label"><strong>Platform</strong></label> <input type="text" class="form-control" id="platform" name="platform"> </div> <div class="col-12"> <label class="form-label"><strong>Game Link</strong></label> <input type="url" class="form-control" id="game_link" name="game_link"> </div> <div class="col-12"> <label class="form-label"><strong>Launch Date</strong></label> <input type="date" class="form-control" id="launch_date" name="launch_date"> </div> <div class="col-12"> <input type="submit" class="btn btn-dark" id="submit" value="Submit" style="margin-top: 10px;"> </div> </form> </div> views.py: def new_game(request): if request.method == "POST": title = request.POST["title"] sub_title = request.POST["sub_title"] description = request.POST["description"] image = request.POST["thumbnail"] platform = request.POST["platform"] game_link = request.POST["game_link"] launch_date = … -
ImportError: cannot import name 'force_text' from 'django.utils.encoding'
I'm working on a Django GraphQL-JWT project and everything seems working until I pip install django-graphql-auth and then add graphene_django in my INSTALLED APPS that's when I get this error when I try python manage.py migrate or runserver. -
Django Templates - How to display parent object when child is null within a forloop on the child
I am looking to list child model objects that have a foreign key to the parent and are related to request.user. This is working fine. The problem I have is when, I want to list the parent model object when there is no child attached to request.user. And I want to do this in my django template. In my case, I am using a boolean field (completed in the model to identify whether the child exists. I am stuck on how to pull out the parent object alone. I suppose there is two questions: How do I express in my nestedfor loop that if the child object is null then only show parent object. When child object is null and only show parent object - how do I get the parent object to be rendered only once? I thought maybe something like {%if modela.modela_related_name == None%} (if there is no child object) then do something else would work. Unfortunately, it looks like I already need to be in the forloop to find out whether modela.modela_related_name == None A header Another header Another header Parent_1 Parent_Child_1 Parent_Child_1 Parent_2 Parent_2Child_1 Parent_2Child_1 Parent_3 Parent_3Child_1 Parent_3Child_1 Parent_4 (empty) Parent_4 views def list_quests(request): q = … -
Django - Order by Ascending with None Last with second level order for Nones
As per the title I'd like to order the Fastest Lap values in ascending times with any Nones at the end sorted by Laps Complete descending. My first attempt was .order_by(F('best_lap_time').desc(nulls_last=True), "-laps_complete") which returns the correct order except that Fastest Lap times are descending: So on the basis of Model Meta options - Ordering we attempt to change the Fastest Lap order by swapping desc/asc to .order_by(F('best_lap_time').asc(nulls_last=True), "-laps_complete") and this returns where the None values are now at the top: Its almost like asc exists before the second order by is completed. -
how can I redirect user to public profile in django
I have a model called Product that has a user field, and a Profile model that also has a user field. What i want is: When user A post something from a Product model, and user B also post something from the Product model, I want to redirect visitors or others user to the public_profile page of the user who created that Product model object. For Example: In Stack Overflow, when the user ask a question, you can see their username on that question and anyone in the world can go to that profile page of that user that created that question. urls: path('/<slug:slug>/', views.public_profile, name='Public-Profile'), views: def public_profile(request, slug): return render(request, 'public_profile.html') my template: {% for product in products %} <div class="col-md-3"> <div class="card my-2 shadow-sm bg-body"> <div class="card-head"> I want add the url to this `a` tag <a href="{% url 'Public-Profile' %}"> <span class="material-symbols-outlined"> account_circle </span> {{ user.username }} </a> </div> {% endfor %} my models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='product-image') price = models.FloatField(max_length=11) category = models.ForeignKey(Category, on_delete=models.CASCADE) phone_number = PhoneNumberField() created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=100, unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def … -
Not able to divide forloop.counter in django template?
I am using django 4.1.5, and i am trying to divide the current forloop counter with 3. Problem is, i tried so many different syntax, but nothing is working <h3> {{ forloop.counter|div:3 }} </h3> Exception Value: Invalid filter: 'div' <h3> {{ forloop.counter|div:"3" }} </h3> Exception Value: Invalid filter: 'div' <h3> {{ forloop.counter//3 }} </h3> Exception Value: Could not parse the remainder: '//3' from 'forloop.counter//3' <h3> {{ forloop.counter/3 }} </h3> Exception Value: Could not parse the remainder: '/3' from 'forloop.counter//3'\ how can i get the divided value? -
How to use mysql database with django_tenants?
When i run migrations for tenant i got error **Error : ** if connection.schema_name == public_schema_name: AttributeError: 'DatabaseWrapper' object has no attribute 'schema_name' I have tried to use below settings for database engine but it did not work DATABASES = { 'default': { 'ENGINE': 'django_tenants.mysql_backend', # .. } } it was working fine for PostgreSQL db I used below setting i was getting error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'portals', 'USER':'root', 'PASSWORD':'root', 'HOST': '127.0.0.1', 'PORT': '3306' } } MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ] DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "client.Client" TENANT_DOMAIN_MODEL = "client.Domain" -
Hello I ran into a problem when I was coding a store site with Django
I have the Reverse error for 'single_product' with no arguments not found. 1 pattern(s) tried: ['product/product/(?P<pk_latin_name_product>[-a-zA-Z0-9_]+)\Z'] I got it when I was doing my store project when I wanted to exit the page Be my single product html: <a class="product-thumb" href="{% url 'single_product' category_list.pk_latin_name_product %}"> <img src="{% static 'assets/img/products/07.jpg' %}" alt="Product Thumbnail"> </a> view: def single_product(request, pk_latin_name_product): pk_latin_name_product = get_object_or_404(Products, pk=pk_latin_name_product) product_spicials = Specials.objects.all().filter(pk_latin_name=pk_latin_name_product) print(product_spicials) context = { 'category_titles': Category_Titles, 'menus': Menus, 'category_subheadings': Category_Subheadings, 'product_pks': pk_latin_name_product, 'product_spicials': product_spicials, } return render(request, 'product/single-product.html', context=context) urls: path('product/<slug:pk_latin_name_product>', single_product, name='single_product'), I also read some things, but I did not get the right answer Like this question Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)\\/$'] -
Django Modelform DateTime Picker
I would like to get a date AND time picker for my django model form. model: class ServiceBooker(models.Model): regnr = models.CharField(max_length=255) namn = models.CharField(max_length=255, null=True, blank=True) telnr = models.CharField(max_length=255) email = models.EmailField(max_length=255) service_date = models.DateTimeField() booked_date = models.DateTimeField(auto_now=True) kommentar = models.TextField() service_name = models.ForeignKey(ServiceType, on_delete=models.CASCADE) noteringar = models.TextField(default='') forms.py: class ServiceBookerForm(forms.ModelForm): service_date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput( format='%d/%m/%Y %H:%M', attrs={'class': 'form-control'})) class Meta: model = ServiceBooker fields = '__all__' exclude = ('noteringar',) But on the website it doesn't show the datetimepicker. I know how to fix the date picker with: 'service_date': widgets.DateInput(attrs={'type': 'date'}) but I would like to get a date AND time picker. Can anyone help me? :-) Thanks! -
best name for class of types (options)
i have app in my project for types that user can define or change types. for example: it hold gender types, education types to use in HTML options for more versatility. i don't want to name it options or types (conflict with language keyword). what is another names you can suggest -
Best approach of storing files with a django model
I'm trying to figure out how which approach will be a more suitable way of storing files for the model described below: def user_directory_path(instance, filename): return f"books/{instance.slug}/{filename}" class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=150, verbose_name="Title") slug = models.SlugField(unique=True, max_length=100, verbose_name="URL") cover = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="Cover" ) epub = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="EPUB" ) pdf = models.FileField( upload_to=user_directory_path, null=True, blank=True, verbose_name="PDF" ) The folder structure of this approach looks like this: mediafiles/ books/ <instanse.slug>/ <cover> <epub> <pdf> And the only problem I have here is that when I delete the entity of a book in the database, the <instanse.slug> folder is still there. I don't know what other issues could be here if there are any. So I'd like to know what could be a more practical solution for this particular model. -
How to add dynamic content using django
I am developing a web app using Django. This can be used by teachers to keep track of all their classes. When a teacher creates a new class using this app, the teacher can specify the details of the class like semester, students enrolled, etc. I need to create a success page for this that will show the details using Django -
Django template use custom filter in CSS
@register.filter(name='cf') def cf(amount): # Format the amount as an integer with commas formatted_amount = f"{int(amount):,}" # Determine the CSS class based on the sign of the amount if amount < 0: css_class = "red-text" else: css_class = "green-text" print(formatted_amount) # Generate the HTML markup with the CSS class and formatted amount return f'<span class="{css_class}">{formatted_amount}</span>' I am using the custom_filter inside the HTML, and the output is <span class="green-text">5,492</span> I just need '5,492' in green color, but it prints as above Please guide me to rectify it. -
How to fetch hierarchical entries from database using python
I have 3 interdependent dropdowns in a django project, Level1, Level2 and Level3. These levels may increase. The mapping of these dropdowns is available in below format: Table Name is LevelMapping From the above mapping, I want to create a mapping as follows: Team | Level1 | Level2 | Level3 How to get the mapping using recursion in python django? -
How to upload profile picture in Django using bootstrap modal
I am doing a web app project where users can update profile picture and their firstname, lastname, bio, url and username. I am using bootstrap 4 modal in the user_update.html for the profile picture update implementation. user_update.html {% extends 'users/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block maincss %} <link rel="stylesheet" type="text/css" href="{% static 'users/stylesheet/main.css' %}"> {% endblock maincss %} {% block updateprofilecontent %} <main role="main" class="container"> <div class="row"> <div class="col-md-8"> <div class="content-section"> <div class="media"> <a href="#" data-toggle="modal" data-target="#profilePicModal"> <img class="rounded-circle account-img" src="{{ user.profile_picture.url }}"> </a> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile</legend> {{ u_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> </div> </div> </main> <!-- Modal --> <div class="modal fade" id="profilePicModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Choose Profile Picture</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ p_form|crispy }} </div> </div> </div> </div> {% endblock updateprofilecontent %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path('user/update/', user_views.userUpdate, name='user-update'), ] if settings.DEBUG: urlpatterns += … -
How to upload profile picture in Django using bootstrap modal
I am doing a web app project where users can update profile picture and their firstname, lastname, bio, url and username. I am using bootstrap 4 modal in the user_update.html for the profile picture update implementation. user_update.html {% extends 'users/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block maincss %} <link rel="stylesheet" type="text/css" href="{% static 'users/stylesheet/main.css' %}"> {% endblock maincss %} {% block updateprofilecontent %} <main role="main" class="container"> <div class="row"> <div class="col-md-8"> <div class="content-section"> <div class="media"> <a href="#" data-toggle="modal" data-target="#profilePicModal"> <img class="rounded-circle account-img" src="{{ user.profile_picture.url }}"> </a> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile</legend> {{ u_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> </div> </div> </main> <!-- Modal --> <div class="modal fade" id="profilePicModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Choose Profile Picture</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ p_form|crispy }} </div> </div> </div> </div> {% endblock updateprofilecontent %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path('user/update/', user_views.userUpdate, name='user-update'), ] if settings.DEBUG: urlpatterns += … -
How to make case-insensitive serach to Cyrillic letters django
I tryid to create search in django and make it case-insensitive. I created it, but it doesn't work with cyrillic (russian) letters. # views.py class QuestionsAPIView(generics.ListCreateAPIView): search_fields = ['name_tm', 'name_ru', 'name_en'] filter_backends = (filters.SearchFilter,) queryset = Product.objects.all() serializer_class = ProductSerializer # urls.py urlpatterns = [ path('', views.QuestionsAPIView.as_view()), ] With latin letter it works: But with russian letter not works: -
Django Bad request error when trying to log in
I created a LoginAPIView in my django project and it works as intended but it says "Bad Request: /login/" and I'm worried since it may cause some problems in the future. views.py: class LoginAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = LoginAPISerializer http_method_names = ['get', 'post'] def get(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializer.py: class LoginAPISerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() http_method_names = ['get', 'post'] def validate(self, data): username = data.get('username') password = data.get('password') if not username or not password: raise serializers.ValidationError('Username and password are required') user = authenticate(username=username, password=password) if not user: raise serializers.ValidationError('Invalid credentials') data['user'] = user return data def create(self, validated_data): user = validated_data['user'] token, created = Token.objects.get_or_create(user=user) return {'token': token.key} I looked up for solutions but I couldn't find one. Please help, thanks. -
What is the name of Django application's default server(Built in server)?
I am writing a synopsis for one of the Academic Django project, which is going to run on localhost(no deployment). Now, in synopsis I want to mention server name. I know Django has built in server, what is the name of that server? can anyone sort it out? Thank you. -
OpenSearch connection times out with Django using docker containers
I'm trying to figure out why my docker container running Django times out when trying to communicate with a docker container running OpenSearch. I'm testing out DigitalOcean for containerising my web services. It's set to use 2x vCPUs and 4GB RAM. The Django app container is using gunicorn which is accessed via an nginx reverse proxy. The OpenSearch container is launched via the developer docker compose file provided on their website. If I launch all containers, all Django's pages that don't require any interaction with the django-opensearch-dsl package load and operate fine. I can also launch a Django shell and query the database etc. If I try to run an OpenSearch related command though, such as trying to create an index, it will timeout. For example, running docker exec -it myapplication-webapp python manage.py opensearch index create results in Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn conn = connection.create_connection( File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection raise err File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection sock.connect(sa) TimeoutError: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py", line 398, in _make_request conn.request(method, … -
How to let the users download JSON & CSV File in django?
On my Django project, I have scraped data in a JSON & CSV format. I want to let the users download the JSON and CSV files. The below code generates the files in my django project directory. views.py final = json.dumps(sorted_result, indent=2) with open("webscraping_dataset.json", "w") as outfile: outfile.write(final) df = pd.DataFrame({"Name": name, "Price": price, "URL":URL}) df.to_csv("data.csv") How should I implement it in my Django project so that the users can download those files? Thanks. -
When Django is started by uWSGI, it does not write logs to the log file
I started Django by the command python manage.py runserver. Django wrote logs to the file my_django_project/log/django.log. So far so good. I started Django by the command uwsgi --ini uwsgi.ini. I expected Django write logs to the file my_django_project/log/django.log. It created the file, but did not write any content to it. I have the following setup for my Django project named my_django_project. Project layout: - my_django_project/ - uwsgi.ini - manage.py - my_django_project/ - __init__.py - settings.py - wsgi.py - log/ - django.log settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "[{asctime}] [{name}] [{levelname}] [{filename}:{funcName}:{lineno}] {message}", 'datefmt': "%Y-%m-%d %H:%M:%S", "style": "{", }, }, "handlers": { "console": { 'level': 'DEBUG', "class": "logging.StreamHandler", "formatter": "verbose", }, "django_file": { "level": "DEBUG", "class": 'logging.handlers.RotatingFileHandler', "formatter": "verbose", "filename": "log/django.log", 'maxBytes': 10 * 1000 * 1000, # 10 MB 'backupCount': 3, }, }, "loggers": { "django": { "handlers": ["console", "django_file"], "level": "DEBUG", }, }, } wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_project.settings') application = get_wsgi_application() uwsgi.ini: # uwsgi.ini file [uwsgi] module=my_django_project.wsgi master=true processes=1 http=:8000 vacuum=true pidfile=/tmp/project-master.pid logto=./log/uwsgi.log log-maxsize=10000000 enable-threads=true thunder-lock=true uwsgi.log (replaced some private information with XXXX): *** Starting uWSGI 2.0.21 (64bit) on [Sun Apr 9 12:35:36 2023] *** compiled with … -
How do I create a specific version of Django Project in Pycharm( virtual environment)
such as My Python is 3.6.8,I want to create Django 1.11.8 project In virtual environment?How should I do? Used virtualenv 1、I create Django Project Under virtual environment in Pycharm,the Django version is auto latest 2、I try Create Django Project by Bash line,but when I open the Project by Pycharm,that is not in virtual environment -
Django User Panela as Django Admin?
Django has a powerfull Admin resource, its amazing and fast to create and teste the models. We have some similar resource that allow us to generate an User app fast like as in admin panela? I quanto know If haver a fazer way tô create our app as Django admin