Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: request.GET.get('x') does not fetch selected item in dropdown. Error: None
I have the combobox countries (def trip_selector) dependent on the combobox trips (def trips). In the comboboxes I display the item correctly. If I click on the button I would like to print the selected item in the textarea (def result). The problem is that I can't extract the selected item in the trips combobox, I get the error: None. I use selected = request.GET.get('trips') also because trips is the name in select name="trips" id="id_trip" in the trips.html page. The selected item to print does not send data, it only displays it. I can't figure out why it doesn't work. Can you help me please? IMPORTANT: i specify one important thing in case you want to help me: I don't want to move selected = request.GET.get('trips') inside the def test1() function or inside the def result() function, at most create another function if necessary. def test1 is just one of many functions I'm going to create, so it's pointless to move selected = request.GET.get('trips') into each function test1, test2, test3, test4, etc. These functions will be displayed in textarea (def result) which must remain only a viewer because it will display various functions (and not just one). views.py from django.shortcuts … -
Dynamic filtering on the FastAPI site
I need to implement filtering on the site, I use MongoDB. The thing is, I have multiple arrays. old_fliters, where you use different values of all filters, there are arrays of filters, where available filters should be available, when I had only two age and brand filters, then the following logic worked if brand and age were selected: in the catalog by brand announcement and age in the catalog by brand announcement or age when the filters became more than two of these, the logic stopped working, please help solve a specific problem, what kind of logic should be used, but massive filters are presented in bold (available for selection), the old_fliters array for comparison with filters, that is, what is not in the filters array, but is in the old_fliters array on the frontend is obscured. Here is a good example: I choose a material from cardboard, the country is China, and with such logic as above, the age remains 0+, which either China or cardboard has, but if you cross all three filters, there are no such products. from math import ceil from fastapi import HTTPException, APIRouter, Query route_catalog_test = APIRouter() from database import my_collection from enum import … -
Is it possible to disable datatables' default custom search builder draw?
My Django webapp uses datatables with serverside processing and custom search builder. I am trying to change the URL to include the query parameters from the searchbuilder for bookmarking purposes. Using the ajaxSucesss settings.url object and the HTML history.pushState method, I can get the necessary parameters and append them to the URL. The issue is, each time an ajax request is made, datatabels adds a "&&" followed by a deafault draw to the request. Is there a way to disable the default datatables draw? In the Django html template: $( document ).on( "ajaxSuccess", function( event, xhr, settings ) { // collect everything in the URL after the "?" draw_string = settings.url.split("dt-json/?")[1] // split the original URL at the "&&" and keep only the first half. // the second half is the default dt draw let query_string = draw_string.split("&&")[0] // if the datatable is filtered. if (draw_string.split('&&').length === 2 && !draw_string.split('&&')[1].includes("draw=1&")) { // replace the string with the second draw query_string = draw_string.split('&&')[1]; } url_params = "/?" + query_string // and replace the URL with the new URL without reloading the page. history.pushState(null, "", url_params) } ); In views, to to process the ajax request: def query_string_to_dict(query_string_arg): # When adding params … -
No backend data is publishing from fullcalendar in Django
I am attempting to use the fullcalendar package with Django for calendar implementation. I am able to display the calendar, create and save a model to the database, but I am having issues bringing it into the template. I can bring in context event information, as for bringing it onto the actual calendar, I am missing the target and hitting a wall. My belief is how I am calling on the URL to bring back the JSON response data. All assistance is appreciated models.py class CalendarEvents(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=50, choices=EVENT_CHOICES) name = models.CharField(max_length=145,null=True, blank=True) location = models.CharField(max_length=100, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) urls.py path("calendar", view=apps_calendar_view, name="calendar"), path('calendar/all_events/', view=apps_calendar_all_events, name='calendar.all_events'), views.py def apps_calendar_view(request): all_events = CalendarEvents.objects.all() context = { "events":all_events, } return render(request,'apps/apps-calendar.html', context) def apps_calendar_all_events(request): all_events = CalendarEvents.objects.all() out = [] for event in all_events: out.append({ 'type':event.type, 'title': event.name, 'location':event.location, 'id': event.id, 'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"), 'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"), }) print(out) return JsonResponse(out, safe=False) apps-calendar.html <div class="col-xl-9"> <div class="card card-h-100"> <div class="card-body"> <div id="calendar"> </div> </div> </div> </div> <script> import { Calendar } from '@fullcalendar/core' import dayGridPlugin from '@fullcalendar/daygrid' const calendarEl = document.getElementById('calendar') const calendar = new Calendar(calendarEl, { plugins: [ dayGridPlugin // … -
Django intermediate many-to-many model
I wonder if I can create intermediate model for many-to-many field without specifying related_name but rather just put ManyToManyField on both Models. I was watching some tutorial on Django ORM and instructor explicitly said we can't use ManyToManyField on both Models (while I think that is true if Django creates own table, I am not sure if it is if we specify custom intermediate model). So this is the code: class Category(models.Model): products = models.ManyToManyField("Product", through="CategoryProduct") name = models.CharField(max_length=255, unique=True) class CategoryProduct(models.Model): category = models.ForeignKey("Category", on_delete=models.CASCADE) product = models.ForeignKey("Product", on_delete=models.CASCADE) class Meta: unique_together = ("category", "product",) class Product(models.Model): categories = models.ManyToManyField("Category", through="CategoryProduct") attribute_value = models.ManyToManyField("AttributeValue", related_name="products") name = models.CharField(max_length=255, unique=True) I tested it with dummy data and this code works for me: p = Product.objects.get(id=1) c = Category.objects.get(id=1) p.categories.add(1, 2, 3) c.products.add(1, 2, 3) -
Serialize list of a specific field of Many To Many relation in Django
What I want is to have a list of a specific field from a ManyToMany relation instead of a list of dictionaries that the field is in. For example, with the following code, I get the result shown below # models.py from django.db import models class Bar(models.Model): title = models.CharField(max_length=255) class Foo(models.Model): title = models.CharField(max_length=255) bars = models.ManyToManyField(Bar, related_name="foos") # serializers.py from rest_framework.serializers import ModelSerializer from .models import Bar, Foo class BarSerializer(ModelSerializer): class Meta: model = Bar fields = ("title",) class FooSerializer(ModelSerializer): bars = BarSerializer(many=True) class Meta: model = Foo fields = ("title", "bars") # views.py from rest_framework.generics import ListAPIView from .serializers import FooSerializer from .models import Foo class FooAPIView(ListAPIView): queryset = Foo.objects.prefetch_related("bars") serializer_class = FooSerializer Result: [ { "title": "foo 1", "bars": [ { "title": "bar title 1" }, { "title": "bar title 2" }, { "title": "bar title 3" } ] }, { "title": "foo 2", "bars": [ { "title": "bar title 4" }, { "title": "bar title 5" }, { "title": "bar title 6" } ] }, { "title": "foo 3", "bars": [ { "title": "bar title 7" }, { "title": "bar title 8" }, { "title": "bar title 9" } ] } ] But what I … -
Connecting to AS400 with Django using ibm-db-django
I am trying to connect my newly created django project to an AS400 system that already has a lot of data stored on it. The only documentation I can find on how to configure your Django project is on this github page and goes over how to set up your virtual environment and get all necessary dependencies and versions. Currently I have my package versions set up according to that documentation as seen here Package Version ----------------- -------- asgiref 3.7.2 Django 3.2 ibm-db 3.1.4 ibm-db-django 1.5.2.0 pip 22.0.4 pyodbc 4.0.39 pytz 2023.3 regex 2023.6.3 setuptools 58.1.0 six 1.16.0 sqlparse 0.4.4 typing_extensions 4.7.1 My current python version is also Python 3.10.4. I also have the my database setting within my settings.py folder set up like this DATABASES = { 'default': { 'ENGINE' : 'ibm_db_django', 'NAME' : '_____', 'USER' : '_____', 'PASSWORD' : '_____', 'HOST' : '_____', 'PORT' : '_____', 'PCONNECT' : True, } } And I know all the values for these settings are in fact connect since I am able to connect to the AS400 system when using the PYODBC library which requires a connection string with the same data in order to access the AS400 system. # Define the … -
Advanced Python Stopwatch
I'm thinking about creating an advanced stopwatch as a Python project. The way I want it to work is like this: Stopwatch Starts If stopwatch paused a "rest" stopwatch begins When stopwatch is started again initial stopwatch begins and the rest stopwatch is paused. This cycle continues until stopwatch time is ended. I haven't started writing this because I'm unsure of how it would work. I'm not sure how to manage the stopwatch times as they are pausing and starting. If it makes any difference I'm thinking of implementing this into a Django app. Thanks, Mitchell -
Could not get Response when i uplaod video on server in python django
I am having a problem with uploading videos using the Django rest framework. When I upload locally, it works fine and stores in S3. However, when I upload through the server, it does not respond. Even when I change the timeout limit of the reverse proxy, Postman gives me the error "could not get a response." I have tried all possible solutions but still need guidance from the developers. -
"Database Error when Deploying Django Project with Free MongoDB on Render Testing Platform
enter image description here Hello, I'm having issues using the free MongoDB database in a Django project. I managed to create a simple CRUD (Create, Read, Update, Delete) to list and add tasks. However, when I deploy the project to the free testing platform 'Render' and try to add a task there, it doesn't work and gives a database error. enter image description here enter image description here Perfectly Functional in Testing Environment, but Fails Upon Deployment on Render enter image description here requirements : Django>=3.2.4 djangorestframework>=3.12.4 djongo>=1.3.6 I dont know how to resolve this. -
Django separate own log from library log?
I have django project which print the log such as below. import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) . . . . logger.debug("test") However I am using boto3 library. so, there are many debugging information on console from boto3 libraru. I want to check my own log message. Is there any good method to do this?? my debug setting is like this below. DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s a', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } -
How to show a user's favourites on a profile page using Django
I'm relatively new to Django and am attempting to build a website where a user can view products and favourite them. I then want the user to be able to login and see their list of favourites. FYI I've largely been using/following this django-blog tutorial to create this: https://www.youtube.com/playlist?list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi I currently have two apps setup; Products and Customers. In the Products app I have a model called Product with a field likes which is a ManytoMany field. I've got the like/unlike button all setup, but I'm just a bit confused about how to actually pull all the liked products attached to a user. Any help much appreciated! Code below... Product model: class Product(models.Model): created_on = models.DateTimeField(auto_now_add=True) main_image = CloudinaryField('image', default='placeholder') item_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(default="", null=False) price = models.DecimalField(max_digits=8, decimal_places=2) category = models.CharField(max_length=50) description = models.TextField(default='placeholder', blank=True, max_length=1000) colours = models.TextField(default='Ivory', blank=True, max_length=500) sizes_avail = models.TextField(default='Enquire in store', blank=True, max_length=500) likes = models.ManyToManyField(User, related_name='blog_post') def __str__(self): return self.item_name Customer model: lass Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = CloudinaryField('image', default='placeholder') date_of_wedding = models.DateField(default='2024-12-31') website_url = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('home') Views to like/unilike product: def LikeView(request, pk): product = get_object_or_404(Product, id=request.POST.get('product_id')) … -
accesing many to many fields in django
i am trying to build a clothes online store as a fun side project while studying django, i have products each of these products has multiple instances where each instance has a color and a size, like one usually sees in a clothes store, i am using many to one relationship to represent the relation between product and its multiple instances also, i am using many to many relationship to represent the relation between each instance and its color and size because many instances of a product could have many colors and a color could have many products, the same goes for the size. i have tried many solutions that i have found online but none have worked, here is my implementation. model.py class Size(models.Model): size_name = models.CharField(max_length=10) def __str__(self): return self.size_name class Color(models.Model): color_name = models.CharField(max_length=20) def __str__(self): return self.color_name class Product(models.Model): product_name = models.CharField(max_length=100) sub_category = models.ForeignKey(Sub_category, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=0) def __str__(self): return self.product_name class productInstanceDetail(models.Model): product = models.ForeignKey( Product, related_name="product_instance", on_delete=models.CASCADE ) size = models.ManyToManyField(Size, related_name="product_instance_size") color = models.ManyToManyField(Color, related_name="product_instance_color") in_stock = models.PositiveBigIntegerField(default=0) sold = models.PositiveBigIntegerField(default=0) def __str__(self): return self.product.product_name views.py def product_detail_view(request, category_id, sub_category_id, pk): template_name = "hareswear/product.html" category = get_object_or_404(Category, id=category_id) sub_category = get_object_or_404(Sub_category, … -
Why am i getting module error in pythonanywhere
Help me to solve this 2023-07-30 16:14:46,244: Error running WSGI application 2023-07-30 16:14:46,249: ModuleNotFoundError: No module named 'cloudinary' 2023-07-30 16:14:46,249: File "/var/www/garritech_pythonanywhere_com_wsgi.py", line 89, in <module> 2023-07-30 16:14:46,249: application = get_wsgi_application() 2023-07-30 16:14:46,249: 2023-07-30 16:14:46,249: File "/usr/local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-07-30 16:14:46,249: django.setup(set_prefix=False) 2023-07-30 16:14:46,249: 2023-07-30 16:14:46,249: File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 19, in setup 2023-07-30 16:14:46,250: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2023-07-30 16:14:46,250: 2023-07-30 16:14:46,250: File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 87, in __getattr__ 2023-07-30 16:14:46,250: self._setup(name) 2023-07-30 16:14:46,250: 2023-07-30 16:14:46,250: File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 74, in _setup 2023-07-30 16:14:46,250: self._wrapped = Settings(settings_module) 2023-07-30 16:14:46,250: 2023-07-30 16:14:46,250: File "/usr/local/lib/python3.10/site-packages/django/conf/__init__.py", line 183, in __init__ 2023-07-30 16:14:46,251: mod = importlib.import_module(self.SETTINGS_MODULE) 2023-07-30 16:14:46,251: 2023-07-30 16:14:46,251: File "/home/garriTech/Yulav_Backend/yulav/settings.py", line 6, in <module> 2023-07-30 16:14:46,251: import cloudinary I already pip install cloudinary but it is not working -
Django websocket website returning an empty JSON/dictionary when I try to reference the user's username
I am building a django website where users can chat with each other and I am using channels for its development. I intended on programming it in such a way that the user's profile pic would be beside their message with their username on top of their message. But right now, I am not seeing their profile photo nor their username. I am just getting the alt text instead of their profile photo, and a '{}' beside their username. I have added console.log() and print() statements in various places inside of my code for debugging it which I will show in the output. The following is routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()) ] The following is views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse from django.http import JsonResponse from django.contrib.auth.models import User from users.models import Profile def home(request): context = { } return render(request, 'common_anime_chat/index.html', context) def about(request): return render(request, 'common_anime_chat/about.html') def room(request, room_name): if request.user.is_authenticated: return render(request, 'common_anime_chat/chatroom.html', { 'room_name':room_name }) else: messages.success(request, f'You need to log in to start conversations.') return redirect('login') def get_user_profile_pictures(request): # Get all users profiles = Profile.objects.all() # Create a … -
Can't figure out how to get rid of field required message on Django form submission
I have a model form that has a name field and when I submit the form, I get the 'field required' message even when the name field is filled out. models.py from django.db import models from user.models import User class Image(models.Model): """This model holds information for user uploaded images""" # Status of the image class Status(models.TextChoices): PUBLIC = 'public', 'Public' PRIVATE = 'private', 'Private' name = models.CharField(max_length=150) image = models.ImageField(upload_to='images/') status = models.CharField( max_length=7, choices=Status.choices, default=Status.PUBLIC) upload_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='photos') def __str__(self) -> str: return self.name class Meta: indexes = [ models.Index(fields=['name'], name='name_idx'), models.Index(fields=['user'], name='user_idx') ] ordering = ['-upload_date'] forms.py from django import forms from .models import Image from utils.forms.widgets import text_input, select_input, image_input class ImageUploadForm(forms.ModelForm): """Use this form to upload images""" class Meta: model = Image fields = [ 'name', 'image', 'status', ] widgets = { 'name': text_input, 'image': image_input, 'status': select_input, } The Error that I'm getting That's after trying to submit the form with an image selected and the name filled out. I have tried using the clean_name method to see if returning the name of the image would fix it but to no avail. -
Custom Form Wizard bootstrap 5
I currently develop custom form wizard using bootstrap 5 and jquery. Not using any plugin. Here my html code : <div class="card-inner"> <form action="{% url 'toTANewPrj' %}" method="post" id="frmNewPrj" class="form-validate is-alter"> {% csrf_token %} <div class="row"> <div class="col-md-4"> <ul class="custom-stepper"> <li class="custom-step active" data-step-number="1"> <div> <div class="lead-text">Intro</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> <li class="custom-step" data-step-number="2"> <div> <div class="lead-text">Profiles</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> <li class="custom-step" data-step-number="3"> <div> <div class="lead-text">Intro</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> </ul> </div> <div class="col-md-8"> <div class="custom-step-content active"> page 1 </div> <div class="custom-step-content"> <h5>Project Details</h5> <div class="row g-3"> <div class="col-12"> <div class="form-group"> <label class="form-label" for="PrjName">Project Name</label> <div class="form-control-wrap"> <div class="input-group"> <input type="text" class="form-control" id="PrjName" name="PrjName" placeholder="Name your project here" required> <div class="input-group-append"> <span class="btn btn-success btn-dim" data-bs-toggle="tooltip" data-bs-placement="top" title="Get from Teammate" onclick="showModalPrjTM()"> <em class="icon ni ni-download"></em> </span> </div> </div> </div> </div> </div> </div> </div> <div class="custom-step-content"> page 3 </div> <div class="navigation-buttons"> <button class="btn btn-dim btn-success" id="prevBtn" onclick="prevStep()">Previous</button> <button class="btn btn-success" id="nextBtn" onclick="nextStep()">Next</button> <button type="submit" class="btn btn-success" id="submitBtn">Submit</button> </div> </div> </div> </form> </div> And here my css : .custom-stepper { list-style-type: none; padding: 0.5rem; display: flex; flex-direction: column; } .custom-stepper > *.custom-step { … -
Store adresses in database
I'm doing a project on Django and I need to store addresses in the database (country, city, street, house). What is the best way to do this? I was thinking of storing the country, city, street and house separately. Are there any other ways to do this? -
How to properly dynamically add ModelForm fields with django-modeltranslation enabled?
I'm attempting to dynamically add translatable fields for my forms.ModelForm, depending on whether the customer has enabled the language or not. However, the translated value isn't saved to the model. class DefaultModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if user := self.request and self.request.user: company = user.company app_setting = company.settings default_lang = settings.MODELTRANSLATION_DEFAULT_LANGUAGE # "en" default_search = f"_{default_lang}" to_add = [] """Set field_order to the same order as set in Meta.fields, unless already set""" if self.field_order is None: self.field_order = list(self.Meta.fields) for modelfield in self._meta.model._meta.fields: """If we found a default translation field, add it to the list""" if ( (formfield := self.fields.get(modelfield.name, None)) and modelfield.name.endswith(default_search) and isinstance(modelfield, TranslationField) ): to_add.append( { "position": self.field_order.index(modelfield.name), "formfield": deepcopy(formfield), "name": modelfield.name.removesuffix(default_search), # "description" "languages": app_setting.get_additional_language_codes, # ["es"] } ) for addable in to_add: for lang in addable.get("languages"): field_name = f"{addable.get('name')}_{lang}" # "description_es" formfield = addable.get("formfield") formfield.label = formfield.label.replace(f"[{default_lang}]", f"[{lang}]") formfield.required = False formfield.initial = getattr(self.instance, field_name, "") self.fields[field_name] = formfield self.field_order.insert(addable.get("position", 0) + 1, field_name) self.order_fields(self.field_order) This code allows me to render the fields accordingly. If the customer has selected to show e.g. "es" (Spanish), the translatable field ("description_en") will be copied and I create a new field ("description_es") in the right position inside … -
Django is not sending email with the SMTP server of mail.ru
I am facing with a problem of sending emails on Django. I think that my settings, views and model is correct, but despite of that mail is not sending. There is no problem when I try this on console Django version == 4.2.1 Python version == 3.10 settings.py: `EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.mail.ru' EMAIL_PORT = 465 EMAIL_HOST_USER = 'storedjango@mail.ru' EMAIL_HOST_PASSWORD = '*****' EMAIL_USE_SSL = True` models.py: `class EmailVerification(models.Model): code = models.UUIDField(unique=True) user = models.ForeignKey(to=User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiration = models.DateTimeField() def __str__(self): return f'Email verification for user {self.user.email}' def send_verification_email(self): link = reverse('users:email_verification', kwargs={'email': self.user.email, 'code': self.code}) verification_link = f'{settings.DOMAIN_NAME}{link}' subject = f'Verification for {self.user.username}' message = f'Click to the link to verify your account {self.user.email} {verification_link} ' send_mail( subject=subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[self.user.email], fail_silently=False ) def is_expired(self): return True if now() >= self.expiration else False` views.py: `class EmailVerificationView(TemplateView): template_name = 'users/email_verification.html' def get(self, request, *args, **kwargs): code = kwargs['code'] user = User.objects.get(email=kwargs['email']) email_verifications = EmailVerification.objects.filter(user=user, code=code) if email_verifications.exists() and not email_verifications.first().is_expired(): user.is_verified_email = True user.save() return super(EmailVerificationView, self).get(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('index'))` forms.py: ` def save(self, commit=True): user = super(UserRegistrationForm, self).save(commit=True) expiration = now() + timedelta(hours=48) record = EmailVerification.objects.create(code=uuid.uuid4(), user=user, expiration=expiration)` What could be causing as the … -
Not able to access image uploaded through HTML forms
This is my class that I have created in models.py. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) vegetarian = models.BooleanField(default='True') created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='uploads/',blank=True,null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) This is my forms.py from django.forms import ModelForm from product.models import Product class ProductForm(ModelForm): class Meta: model = Product fields = ['category','image','name','description','price'] This is my form in html file: <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is uppercase">Submit</button> </div> </div> </form> But when I run server, I am not able to see the image of my product while I am able to see the other details that I want as given in this frontpage.html file: {% for product in products %} <li>{{product.name}}</li> <li>{{product.price}}$</li> <li>{{product.description}}</li> <li><figure><img src="{{ product.get_thumbnail }}"></figure></li> {% endfor %} Please explain why so? I want to see images on my frontpage too. When I fill the form to add products, I upload the image and fill other details, but only text details are visible and not image. -
How to solve TypeError at /AddUser/ AddUser() got an unexpected keyword argument 'username' Error for accessing Django Database
I am getting this error: TypeError at /AddUser/ AddUser() got an unexpected keyword argument 'username' when trying to connect to Django Database enter image description here My views.py File enter image description here Urls.py enter image description here Models.py enter image description here Base.html enter image description here Settings.py enter image description here enter image description here Full Traceback: C:\Users\Riya\PycharmProjects\pythonProject2\venv\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\Riya\PycharmProjects\pythonProject2\venv\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\Riya\PycharmProjects\pythonProject2\career\career\views.py, line 13, in AddUser new_user = AddUser (username=username,password=password,phone=phone) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars What should i do to solve this error? I tried making changes in views.py file but its still showing me the same error -
Django+Htmx: get the selected item of a combobox (created with Htmx) and print it?
I need to get the selected element of the combobox with function def trips. Then use it in the def result function which is used to print the selected item in textarea. The button request is only used to display the data (in the textarea). P.S: If you're wondering, the trip_selector function is that of the first combobox that is dependent. views.py def trip_selector(request): countries = Trip.objects.values_list('country', flat=True).distinct() trips = [] # no trips to start with return render(request, 'form.html', {"countries": countries, "trips": trips}) def trips(request): country = request.GET.get('country') trips = Trip.objects.filter(country=country) return render(request, 'trips.html', {"trips": trips}) def result(request): test_print_in_result = trips return render(request,"result.html", {"test_print_in_result": test_print_in_result}) In the other files everything is ok, I need help only in views.py UPDATE form.py {% extends 'base.html' %} {% block content %} <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country" hx-get="{% url 'trips' %}" hx-swap="outerHTML" hx-target="#id_trip" hx-indicator=".htmx-indicator" hx-trigger="change"> <option value="">Please select a country</option> {% for country in countries %} <option value="{{ country }}">{{ country }}</option> {% endfor %} </select> <!-- Second Combobox ??????? (non lo so)--> <label for="id_trip">Trip</label> {% include "trips.html" %} <!-- Textarea--> {% include "result.html" %} <!-- Button--> <button type="button" class="mybtn" name="btn" hx-get="{% url 'result' %}" hx-swap="outerHTML" hx-target="#id_result" hx-indicator=".htmx-indicator">Button 1</button> … -
Bootstrap : nav menu toggle blocked unrolled
I am creating a project using several things : psycopg2 to query a SQL database pandas to model the data bokeh to create graphics django for the back-end bootstrap for the front-end I'm discovering the front-end, using the system of links in or tags to retrieve the CSS and JS elements needed to make bootstram work, as indicated on the offical website. However, I don't understand why : The menu that appears when the screen size shrinks opens but I can't close it. The only thing that work to untoggle it is to reload the page... Do you know what the problem could be? Here are the elements I've added, as indicated in the section: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My Website</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> </head> And at the end of the body section: <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS" crossorigin="anonymous"></script> </body> This is what it actually look like, on small screen (mobile like) : https://ibb.co/6DyXLhb With the toggle menu unrolled, I can't collapse it. The dropdown menu corresponding to "dashboards" doesn't work whatever the screen size.: https://ibb.co/hRbbrhL -
Django ORM returns all data in many-to-many key relationship
I am facing this problem when i apply .filter() on Django model it return all the sales data which i dont want, I am trying to filter data based on date and want data of the entered date only Sales Model: class Sales(models.Model): Amount = models.FloatField(blank=True, null=True) Date = models.DateField() updated_at = models.DateTimeField(auto_now=True) VAT = models.BooleanField(default=True) Machine Model: class Machine(models.Model): name = models.CharField(max_length=50) Sales = models.ManyToManyField(Sales, blank=True) ...... API: class MachineDateData(APIView): def post(self, request): target_date = date(2023, 5, 1) data = Machine.objects.filter(id=524).filter(Sales__Date=target_date) serializer = MachineReadOnlySerializer(data, many=True) return Response(serializer.data) Serializer: class MachineReadOnlySerializer(serializers.ModelSerializer): class Meta: model = Machine depth = 1 fields = ('id','name', 'Sales') Result: [ { "id": 524, "name": "Résidhome Marseille Saint Charles ", "Sales": [ { "id": 67274, "Amount": 45.12327285161129, "Date": "2023-05-01", "updated_at": "2023-07-29T19:08:07.702463Z", "VAT": false }, { "id": 67275, "Amount": 43.24381640146215, "Date": "2023-05-02", "updated_at": "2023-07-29T19:08:07.725326Z", "VAT": false }, { "id": 67276, "Amount": 85.53046658140136, "Date": "2023-05-03", "updated_at": "2023-07-29T19:08:07.747431Z", "VAT": false }, ...more results here } ] I am looking for a result that looks like this, Inner join to both tables, I have tried to on SQL and on SQL it works fine and shows result, but in Django ORM it does show all the data [ { "id": …