Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get all users with last_login older than 360 days
I'm trying the below code ... from datetime import datetime, timedelta from django.utils import timezone yearago = timezone.make_aware(datetime.today() - timedelta(days=366)) old_users = User.objects.filter(last_login__gt=yearago) old_users.all The output show users that have logged in this year, whereas I want users who's last login was over 366 days ago. So what am I missing? -
render_to_string can't access to a context correctly
I want to use weasyprint to transform a html template to PDF. I'm using Django 5.0. Here is a part of my template (The template works fine, Django renders it correctly): <div> <h1>Tu Pedido está listo, {{request.user.username}}!</h1> </div> <h4>Pedido ID: {{pedido}}</h3> <div class="container text-center" > <table class="table"> <thead class="thead-dark"> <tr> <th>Producto</th> <th>Cantidad</th> <th>Precio</th> </tr> </thead> <tbody> {% for key, producto in carro.items %} <tr> <td> {{producto.nombre}} </td> <td> {{producto.cantidad}} </td> <td> $: {{producto.precio}} </td> </tr> {% endfor %} <tr> <td colspan="3">Total: $: {{total}}</td> </tr> </tbody> </table> </div> <div class="container text-center"> <a href="{% url 'home' %}" class="btn btn-outline-primary me-2">Volver</a> <!--pdf--> <form id="pdf_form" method="post" action="{% url 'generar_pdf' %}" style="display: none;"> {% csrf_token %} <input type="hidden" name="pedido" value="{{ pedido }}"> <input type="hidden" name="carro" value="{{ carro }}"> <input type="hidden" name="total" value="{{ total }}"> </form> <button id="pdf_button" class="btn btn-primary" type="submit">Descargar pdf</button> </div> <!-- send form --> <script> document.getElementById("pdf_button").addEventListener("click", function() { document.getElementById("pdf_form").submit(); }); </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> And here is my views.py: def generar_pdf(request): if request.method == "POST": pedido = request.POST.get("pedido") carro_info = request.POST.get("carro") total_compra = request.POST.get("total") # if I print these 3 variables, the values are ok #--- here is the problem ---# html_string = render_to_string( template_name='exito.html', context={"pedido": pedido, "carro":carro_info, "total": total_compra}, request=request) #------# … -
redirect to the django project
good afternoon, there was a problem when creating the project. the situation is as follows, the built-in view logout does not work correctly. when I log out of the project on the site page on behalf of the user, I will be redirected to http://127.0.0.1:8000/users/logout /. moreover, everything is working properly in another project. below are the variables from the settings file, urls and the button template: urls.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import path from users.apps import UsersConfig from users.views import RegisterView, ProfileView app_name = UsersConfig.name urlpatterns = [ path('', LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(next_page='users:login'), name='logout'), path('register/', RegisterView.as_view(), name='register'), path('profile/', ProfileView.as_view(), name='profile'), ] settings.py AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' template <div class="col-sm-4 offset-md-1 py-4"> <h4 class="text-white">Меню</h4> <ul class="list-unstyled"> <li><a href="{% url 'catalog:home' %}" class="text-white">Главная</a></li> <li><a href="{% url 'catalog:contact' %}" class="text-white">Контакты</a></li> <li><a href="{% url 'blog:blog' %}" class="text-white">Блог</a></li> {% if user.is_authenticated %} <li><a href="{% url 'users:logout' %}" class="text-white">Выйти</a></li> <li><a href="{% url 'users:profile' %}" class="text-white">Профиль</a></li> {% else %} <li><a href="{% url 'users:login' %}" class="text-white">Войти</a></li> <li><a href="{% url 'users:register' %}" class="text-white">Регистрация</a></li> {% endif %} </ul> </div> redirect to the main page -
Django Real time chart when database was updated by MQTT
my Django server receive data from device over MQTT sucessfully. def on_message(mqtt_client, userdata, msg): from lorawan_api.server_processing import SERVER_PROCESSING print(f'Received message on topic: {msg.topic}') # with payload: {msg.payload}') data_processing = SERVER_PROCESSING() data_processing.data_stored(msg.topic,msg.payload) Now i want to display them in real time chart. I found some solution using AsyncWebsocketConsumer. Is that the best way to display real time chart -
Django template, Need 2 values to unpack in for loop; got 1
Been facing issues regarding the error above. I am trying to highlight words based on an ID given by the dictionary in Django <td class="text-center"> {% with background_color=None %} {% for key, value in row.Context.items %} {% if not background_color %} {% for pattern, color in pos_color_map.items %} {% if pattern in value|default:''|lower %} {% with background_color=color %} {% endwith %} {% endif %} {% endfor %} {% endif %} {% endfor %} <span style="background-color: {{ background_color }}"> {{ key }} </span>{% if not forloop.last %}, {% endif %} {% endwith %} </td> -
Why is my Celery configuration not taking effect?
I'm running a Django app with Celery 5.3.4. I'm using Redis as the broker. I want to configure the task_time_limit and task_time_soft_limit options, but I can't get them to take effect when running locally. I've tried setting them very low, and running a slow task that sleeps for 10 seconds: app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 But, when running the Celery worker locally, it completes the slow task and doesn't time out: 2024-03-05T15:46:04.647630Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] received [celery.worker.strategy] 2024-03-05T15:46:14.741217Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] succeeded in 10.093100208323449s: None [celery.app.trace] I've tried configuring Celery in many different ways. Here's my current config, spread out over 2 files: celery.py: import os from celery import Celery from celery.signals import worker_init from django.conf import settings # Set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kosa_api.settings") app = Celery("kosa_api") # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 settings/celery.py (this is imported in my app's settings): from kosa_api.settings.utils import get_safe_redis_url … -
How to create new database table looping through another model in Django
I have a Thermocouple model and I want to create a different model to record Temperatures for each Thermocouple created and save it to database. for thermocouple | Id | name | | 1 | thermocouple_1 | | 2 | thermocouple_2 | | 3 | thermocouple_3 | then TemperatureRecord should be as | id | date | time | user | thermocouple_1 | thermocouple_2 | thermocouple_3 | | 1 | March 5, 2024 | 2:48 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 2 | March 5, 2024 | 2:52 p.m. | 2 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 3 | March 5, 2024 | 2:55 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | Thermocouple model class Thermocouple(models.Model): name = models.CharField(max_length=50, unique=True, help_text="Name of the thermocouple") def __str__(self): return f"{self.name}" class Meta: ordering = ['id'] @classmethod def bulk_create_from_import(cls, data): cls.objects.bulk_create([cls(**item) for item in data]) and i want to create a different database table model named TemperatureRecord consisting id,user,date,time and Thermocouple items. if created 10 thermocouple, need to be 10 column for each Thermocouple to record temperatures (IntegerField) I tried using the following code but didn't work. class TemperatureRecord(models.Model): date = models.DateField() time = … -
hello please help friends solve my problem
[[enter image description here](https://i.stack.imgur.com/3sQfS.png)](https://i.stack.imgur.com/YYUKG.png) tell me how to solve this problem I have already tried everything, nothing helped, if anyone knows how to solve this, I will be grateful for the day I can’t figure out how to fix this error wewewewewewewewewewewe -
I want to create a waybill for my customers who ordered from my website with aramex
the problem that show every time to me in this image it says there is problem with date format this is the code i use: import datetime def send_issue_policy(request): url = "https://ws.sbx.aramex.net/ShippingAPI.V2/Shipping/Service_1_0.svc/json/CreateShipments" headers = { "Content-Type": "application/json", "Accept": "application/json" } payload = { "ClientInfo": { "UserName": "testingapi@aramex.com", "Password": "R123456789$r", "Version": "v1", "AccountNumber": "4004636", "AccountPin": "432432", "AccountEntity": "RUH", "AccountCountryCode": "SA", "Source": 24 }, "Shipments": [ { "Reference1": "", "Reference2": "", "Reference3": "", "Shipper": { "Reference1": "TEst mutli label", "Reference2": "", "AccountNumber": "4004636", "PartyAddress": { "Line1": "Test TEST", "Line2": "", "Line3": "", "City": "riyadh", "StateOrProvinceCode": "", "PostCode": "", "CountryCode": "sa", "Longitude": 0, "Latitude": 0, "BuildingNumber": "null", "BuildingName": "null", "Floor": "null", "Apartment": "null", "POBox": "null", "Description": "null" }, "Contact": { "Department": "", "PersonName": "aramex", "Title": "", "CompanyName": "aramex", "PhoneNumber1": "966512345678", "PhoneNumber1Ext": "", "PhoneNumber2": "", "PhoneNumber2Ext": "", "FaxNumber": "", "CellPhone": "966512345678", "EmailAddress": "test@test.com", "Type": "" } }, "Consignee": { "Reference1": "", "Reference2": "", "AccountNumber": "71500004", "PartyAddress": { "Line1": "Test", "Line2": "", "Line3": "", "City": "riyadh", "StateOrProvinceCode": "", "PostCode": "", "CountryCode": "sa", "Longitude": 0, "Latitude": 0, "BuildingNumber": "", "BuildingName": "", "Floor": "", "Apartment": "", "POBox": "null", "Description": "" }, "Contact": { "Department": "", "PersonName": "aramex", "Title": "", "CompanyName": "aramex", "PhoneNumber1": "966512345678", "PhoneNumber1Ext": "", "PhoneNumber2": "", … -
HTML page is not displaying properly
Here, I extends the base.html to cart.html and then I block the content and end that block at the end of the code. But after I run the code the navbar is not displaying properly and the cart appears to right side of the page. Please help me to fix this issue. Codes on cart.html {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> Responsive Registration Form | CodingLab </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="js/script.js" type="text/javascript"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style media="screen"> body{ background: #ddd; min-height: 100vh; vertical-align: middle; display: flex; font-family: sans-serif; font-size: 0.8rem; font-weight: bold; } .title{ margin-bottom: 5vh; } .card{ margin: auto; max-width: 950px; width: 90%; box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 1rem; border: transparent; } @media(max-width:767px){ .card{ margin: 3vh auto; } } .cart{ background-color: #fff; padding: 4vh 5vh; border-bottom-left-radius: 1rem; border-top-left-radius: 1rem; } @media(max-width:767px){ .cart{ padding: 4vh; border-bottom-left-radius: unset; border-top-right-radius: 1rem; } } .summary{ background-color: #ddd; border-top-right-radius: 1rem; border-bottom-right-radius: 1rem; padding: 4vh; color: rgb(65, 65, 65); } @media(max-width:767px){ .summary{ border-top-right-radius: unset; border-bottom-left-radius: 1rem; } } .summary .col-2{ padding: 0; } … -
display information using django tags
I am writing a site on Django, the purpose of this site is to create a test to assess students' knowledge I need help with outputting options for answers to a question I keep the questions in a list and the answer options in a nested list for example: questions = [ "question1","question2","question3"] answers = [[ "answer1","answer2",answer3 ],["answer1","answer2",answer3,answer4 ] , ["answer1","answer2",answer3 ]]` and I need this data to be displayed in the following format: question1 answer1 answer2 answer3 question2 answer1 answer2 answer3 answer4 question3 answer1 answer2 answer3 here is my code, it does not work very correctly, I know, I have not yet figured out how to implement it in Django tags {% for question in questions %} {{question}} {% for answer in answers %} {% for current in answer %} {{ current }} {% endfor %} {% endfor %} {% endfor %} -
Django: Create form from items in model, where each item in the model has multiple associated questions
I want to ask users multiple questions for each of a list of items in a Django model. As an illustrative example: Suppose I'm collecting data on people's opinions of the Harry Potter films. I want to know if someone has a) watched one of the films, and b) what rating (out of 10) they give said film. Assume that my Django app contains 3 models: Films - to populate the list of films; Users - details on the person who has responded; Reponses - responses for each user. This contains three columns: UserID, FilmID, Rating. It is only populated when a user has given a score for a film (i.e., no blank ratings) The table below shows what kind of answer I'd want to receive: a check of whether they watched the film, and their rating out of 10. Film Watched? Rating HP-1 Y 8 HP-2 Y 9 HP-3 N - HP-4 N - HP-5 N - HP-6 Y 7 HP-7 N - HP-8 N - The HTML of the form would have a similar layout: film name, check box for if it has been watched, and the rating field (dropdown or integer field). This would then load the … -
Can my heroku app store images even after restarting dyno
I have 2 services, backend api on django and frontend on react. My goal is to make django admin page create new food models with pasting new image. On local host everything works fine,images are saving on media/food_images and even after restarting local host they stay there. But when I host them on heroku, make few food models and then restart dyno images dissapear. I checked that when I make new food models in "heroku run bash" there is no media folder. Is there a way to save them for ever? -
How to use count() to get items between specific dates
With this code I am able to get all orders items that is related to Article but here is the problem, I want to get the number of orders that are between two dates that are between the assigned timestamp.How can I do it? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) total_price = models.FloatField(default='0', validators=[MaxValueValidator(99999999999999999999)]) class ArticleSerializer(serializers.ModelSerializer): orders = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = '__all__' def get_orders(self, language): return language.ordersarticle.count() Initial Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 4, // All orders }, Expected Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 1, // Orders between 4th and 7th of march (Example) }, -
Retrieve selected Select Option value
I tried to retrieve the selected unit_selector data for the key, value in for loop in the value_row class. but it didn't work. It just didn't display anything. {% if forloop.first %} <tr class="title_row"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} <th><label for="**unit_selector**"> <select class="master_select" id="**unit_selector**" name="unit_selector"> {% for key, value in b.items %} <option value="{{ value }}" id="{{ key }}">{{ value }}</option> {% endfor %} </select> </label></th> {% endif %} {% endif %} {% endfor %} </tr> {% endif %} <tr class="**value_row **{% if epoch_form.errors %}error{% endif %}"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} {% for key, value in b.items %} {% if unit_selector.key == key %} <td class="_unit" id="{{ key }}">{{ value }}</td> {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </tr> -
Django backend with celery workers - memory threshold
I have a system with some periodic tasks. Each periodic task reads in files and creates objects out of them in the RAM. To prevent data loss, the cached file content is immediately stored from the peridoic task into the database after creating the object out of it. Then the file is deleted from the source. The object is queued into a RabbitMQ and the Celery workers take them for further processing and concurrency. Before caching the next file, the memory usage of the system is fetched with psutil. If it exceeds a threshld, the periodic task stops to read in files and continues with it, when executed the next time. My question is If this is generally a feasible approach if no data must be lost (the files are either stored in the database or still in the source folder) If it is a good approach to keep the synchronisation effort low (files are deleted after reading, the worker operates on objects and does not delete files and there is no sync needed with the periodic task) Which memory threshold is "safe" and fast enough. The file size can be up to 40 MB. -
Signup & Login not working in production in DigitalOcean using DjangoRestFramework and getting server error 500
-I followed the DigitalOcean Documentation to upload my Django app to digitalOcean: https://docs.digitalocean.com/developer-center/deploy-a-django-app-on-app-platform/ And I served my static files and media files using DigitalOcean space and all is good and I can make all of my requests in production but Login & Sign up is only working in my local machine but not in DigitalOcean Server I'm getting server error 500 this is my configuration : settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) # set debug to false by default DEBUG = os.getenv("DEBUG", "False") == "True" ALLOWED_HOSTS = os.getenv( "DJANGO_ALLOWED_HOSTS", "www.aklalatshop.com,https://akalat-shopcsphu.ondigitalocean.app").split(",") # Application definition INSTALLED_APPS = [ # 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'egystoreapp', # For generating / getting access token 'oauth2_provider', 'social_django', ######################################## 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', # for social login 'rest_framework_social_oauth2', # for digitalOcean space 'storages', 'bootstrap4', 'rest_framework', 'rest_framework.authtoken', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'egystores.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'egystores.wsgi.application' DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", … -
Best way to update multiple templates based on form submission?
I'm working on a project that does several calculations based on user input, and I am now trying to create a new form in my variables_input template where the user can retrieve the values used in prior runs, and this works on the variables_input template resulting with the values being displayed on the page. However when the user goes to another page the values displayed are the most recently run calculations. How do I make it so when the user chooses a past run that they don't have to run the calculations but just get the values from the appropriate models to be displayed on the appropriate page? I was wondering if signals could achieve the desired result or if a simpler solution is possible. Below is an example of my project's code. variables_input.html {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" , value="Submit" name="prior_run"> </form> <form action="" method="post"> <h2>Variables Table One</h2> {% csrf_token %} <!-- Table Columns --> <table> <table class="vartable" style="text-align: center;"> <colgroup> <col class="grey"> </colgroup> <thead> <tr> <th>Variable 1</th> <th>Variable 2</th> <th>Variable 3</th> <th>Variable 4</th> <th>Run Name</th> <th></th> </tr> </thead> <tbody> <tr> <div> <td><input type="text" value="{{inputs_list.0}}" name="var_one"></td> <td><input type="text" value="{{inputs_list.1}}" … -
encountering so many errors during web application deployment in firebase
I have successfully deployed my django web application into firebase. But when I did run the hosturl the website I deployed was only able to display html content and images but couldn't display the content as I registered it should in css,js, bootsrap files.it completely could not access these files but it could access the image files which present in the same directory which is static which is within public directory.which is default directory created by firebase during firebase init process.Could you help me in solving this error.or atleast let me know what error could it be. i deployed web application in firebase to host it.for this i put my html file in public directory which basically created by firebase itself during firebase initialization.and i put static files like js,img,css,bootstrap in static directoru which is within the public directory.and the error after the deployement when i did run the hosturl it did not display the website properly means it did nto display as i registered ti should be in js,css,bootstrap files.becoz it could not access that files whereas ti could access the image files which are in same directory where js,css,bootstrap files does exist. -
AttributeError at /login/ 'AnonymousUser' object has no attribute '_meta'
im trying to create my own costume view for the login page and im getting the following error. this is my views: def my_view(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) login(request, user) return reverse_lazy('HomeView') this is the urls: urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('show_todo_list/<int:pk>', ShowToDoView.as_view(), name='Show_To_Do_list'), path('create_task/', CreateTaskView.as_view(), name='Create_Task'), path('change_task/<int:pk>', ChangeTaskView.as_view(), name= 'Change_Task'), path('delete_task/<int:pk>', DeleteTaskView.as_view(), name= 'Delete_Task'), path('login/', my_view, name='login') ] and the error is in line 34: login(request, user) AttributeError: 'AnonymousUser' object has no attribute '_meta' -
MySQLdb.OperationalError: and django.db.utils.OperationalError 1054, "Unknown column" after field rename in Django and MySql
I have django app that is connected to MySql database. I have renamed the field in models.py and succesfuly ran the migration. (the name alteration is written in migrations file) I have also manually altered the field in the MySql, so it's called the same as in models.py (let's say it's called 'newName'); After trying to run new migrations i get MySQLdb.OperationalError: and django.db.utils.OperationalError1054, "Unknown column 'oldName' in 'mysql_tableName'" What should I do? Why does django db connection have oldName of the field? inspectdb shows the new field name in the output; when checking mysql, there is new name of the field, running the sql command in db (SELECT oldName FROM mysql_tableName) works fine. -
Optimizing Image Filtering and Color Selection in Django Product Display
I created three models In Models.py: class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL ,null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" So In my admin pannel Under Product Model it is creating two subparts one is General and other is Product Images--->Product model view and the product images will look like this--->Product Images In the General section I am uploading the main product image <div class="left-column"> {% for p in products %} {% for c in colors %} {% for x in p_image %} <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#1 <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#2 <img data-image="{{c.id}}" class="active" src="{{p.image.url}}" alt=""> #3 {% endfor %} {% endfor %} {% endfor %} </div> And displaying the main image in the frontend by #3 html code and I also want to display other images.My product detail page will … -
why Django upload a file to server failed
if request.method == 'POST': k = request.FILES obj = request.FILES['upload'] t = int(time.time()) jobid = 'jobid'+str(t) job_name = jobid + '_' + obj.name print(job_name) fr = open('prediction/PanPep/upload/' + job_name, 'wb+') i used request.FILES to get a uploaded file and create this file on my server. It was fine when I uploaded the first file. But then i get an error when you i to create the file. this is error: FileNotFoundError: [Errno 2] No such file or directory: 'prediction/PanPep/upload/jobid1709638360_Example_zero-shot.csv' [05/Mar/2024 19:32:40] "POST /panpep/ HTTP/1.1" 500 67598 It seems to be due to some kind of conflict,how to explian this phenomenon and how i fix it. Thanks in advance! -
Page not found (404) Request Method: GET Request URL: http://18.222.182.68/index.html Using the URLconf defined
My main page loads fine, but then when i click a button that's supposed to take me to index.html i get the error posted below. When running this locally it works fine, but when depolying onto AWS (EC2, using nginx and gunicorn) its not working and giving me the error below. im new to using django and AWS, any feedback is appreciated. error: Request Method: GET Request URL: http://18.222.182.68/index.html Using the URLconf defined in LectureLingo.urls, Django tried these URL patterns, in this order: [name='index'] admin/ The current path, index.html, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. views.py code def index_view(request): return render(request, 'index.html') urls.py code from django.urls import path from . import views urlpatterns = [ path('', views.index_view, name='home'), path('index/', views.index_view, name='index'), ] Main urls.py code from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('', include('transcript.urls')), path('admin/', admin.site.urls), ] index.html code {% load static %}<!DOCTYPE html> <html> <head> <title>Chat</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="{% static 'indexstyles.css' %}"> </head> <body> <p id="status">Connection status will go here</p> <div class="custom-tooltip" style="display:none;"></div> … -
Facing error on loading Ml Model through PipelineModel.load(model_location) in Django app
Hello I am using django application which has both asgi and wsgi modes. Now when I load the model in a standalone script it loads without any error but when I load it through an api call in django to perform task it gives an error: File "/mnt/d/InnovativeSolutions/DataAnalytics/DataAnalyticsDataTransformation/env2/lib/python3.10/site-packages/pyspark/ml/param/__init__.py", line 276, in <listcomp> src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)] AttributeError: __provides__ Code: from pyspark.ml import PipelineModel pipeline_model: PipelineModel = await PipelineModel.load(model_location) I have tried making the root method that is loading the ml model into an asynchronous type but still facing the same error. The standalone script loads the model without any error.