Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Multiselect Filed showing List Index Out Of range Error in Window
I was working with Django and it's throwing an error IndexError: list assignment index out of range and the same code is working fine on Linux production, I used pip install django-multiselectfield for multiselect in Django, I am using this DATA= (('0', 'Small'),('1', 'Medium'),('2', 'Large,) and my field name is clients = MultiSelectField(choices=DATA, null = True, blank= True)this, but this is not working and throwing me list index out of range error on window power shell, please let me know how I can solve this issue. -
Cookies are being sent by Django but not received by frontend
I'm attempting to send a cookie to the front end using django middleware. In the middleware I'm seeing that the cookie is getting created and then attached to the response. But once I'm on the frontend (React) I'm not finding the cookies with .get('Set-Cookies') and can't figure out why. Middleware (python) class DeviceCookieMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) new_customer = None if 'device' not in request.COOKIES: new_customer = Customer.objects.create() response['Set-Cookie'] = f'device={new_customer.device}; Max-Age=3600; Secure; HttpOnly; SameSite=None' request.new_customer = new_customer print(response.headers) return response Frontend (Javascript) export async function fetchProductsBySlugs(slugs, setterFunc, startDate, endDate, dateChange) { const [start, end] = parseDates(startDate, endDate) try { const response = await fetch(`${SERVER_ADDRESS}/api/products/products/list/?slugs=${slugs.join(',')}&${datesUrlString(start,end,dateChange)}`); const cookies = response.headers.get('Set-Cookie') console.log(cookies) const products = await response.json(); setterFunc(products); return products; } catch (error) { throw error; } } Things I've Tried: I've looked around and attempted reordering my middleware in Django settings as I've heard that can cause issues based on the order in which it's processed. I've also tried different browsers. Firefox clued me into the fact there was no SameSite setting and that could be the issue. But once I updated that, it still will not appear. I tried using the response.set_cookie() … -
Not Null Constraint Failed in Django DateTime field with auto_now_add=True
I have a model in which there is datetime field. The structure is similar to the below one class ModelName(models.Model): uid = models.CharField(max_length = 50, default="") ordercreated = models.DateTimeField(auto_now_add = True) So when I am trying to create a entry in this field. Most of the times it is working fine. But sometimes it is throwing a Not Null Constraint Failed error. One more thing to note, more than one entry can be made in this model at the same time as I am using celery. Since, I have set the auto_now_add = True. So I was not expecting this kind of issue on creation. -
Django outputs verbose_name in quotes and parentheses in admin panel
My problem is the following. Code: ... class Meta: verbose_name = 'сайт', verbose_name_plural = '1. Сайт', ... Result: Why Django outputs verbose_name in quotes and parentheses in admin panel? -
Is creating a custom email while extending 1to1 from django's user but not using its own email a bad practice?
class Teacher(models.Model): full_name = models.CharField(max_length=90) bio = models.TextField() phone = models.CharField(max_length=16) facebook = models.URLField() twitter = models.URLField() address = models.CharField(max_length=50) image = models.ImageField(default='default_pics/default_teacher.jng', upload_to='teacher_pics') email = models.EmailField(unique=True, null=False) # Using 1-1 with Django's built-in User, instead of creating a custom User user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.full_name This is my teacher model. Now, I know that django's user has an optional email field which I can use but I want to make it required and also unique. I search through the internet and most of it says that if I want to do that I have to create a custom user but imo creating an entire custom user just to accomodate this bit of change is just too much of a hassle. So I create my own email field for the teacher, still take what i need from the built-in user but keep the user's email and teacher's email seperate. Is this bad practice? -
How can I apply VSCode language specific settings to files created in Django projects in virtual environment?
When I create django project in virtual environment, language specific settings does not apply to files newly created in the project. Here is relevant part of settings.json: { ... // language specific settings "[html]": { "editor.tabSize": 2, "editor.defaultFormatter": "esbenp.prettier-vscode", }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.tabSize": 2 }, "[css]": { "editor.suggest.insertMode": "replace", "cSpell.fixSpellingWithRenameProvider": false, "editor.tabSize": 2, }, "[python]": { "editor.tabSize": 4, "editor.insertSpaces": true, "editor.wordBasedSuggestions": false, "editor.formatOnType": true }, ... } Here are the steps that I take when I create project: python -m venv venv . venv/bin/activate pip install django==3.2.18 pip freeze > requirements.txt django-admin startproject TheProject . python manage.py startapp app_1 python manage.py startapp app_2 I add application names to INSTALLED_APPS list, give BASE_DIR / 'templates' for TEMPLATES["DIR"] in settings.py. Then I create an html file : code templates/base.html base.html has 4 spaces for a tab. Trying it without virtual environment didn't work. The setting is properly applied to html files created outside the project: They have 2 spaces for a tab. What is going on? How can I make language specific settings properly applied to files inside django project? -
View class in Django views
Python always use the DRY approach and also motivates programmers to keep there code DRY. Python also provides support to keep its DRY principle intact. But when we see in API of Django we come across class based view, View which is super class of all the views. But the same View class is defined in two different packages. class django.views.generic.base.View class django.views.View Why? This architecture violates the python DRY principle. -
django library management problem with user module
i have to create library management system where we have to create two different modules first is library where admin can add the book and user module which can issue and return the book in django. how to create two different module and which user we have to take .django provide default auth.user models or we have to create different one. i have to create library management system where we have to create two different modules first is library where admin can add the book and user module which can issue and return the book in django. how to create two different module and which user we have to take .django provide default auth.user models or we have to create different one. -
Prevent creation of new model object if another one was created less than 24 hours ago in Django
I am trying to prevent a model object to be created, if another one was created say less than 24 hours ago. There is a trick however. This rule does not apply to ALL model objects and will dependent on a set of rule laid out in a different model. To be more specific, if Venue_1 has a RuleModel set to 1, then when creating a new MyModel object the database would check if a previous MyModel object had been created within less than 1 day ago. If true then new MyModel object is not saved, if false MyModel object is saved. However if Venue_2 does not have any rule, then MyModel objects can be created without any time restrictions. After some research on this forum, it looks like I need to override the save function in the model. This is not working at present. Not error message. models.py class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class RuleModel(models.Model): venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) timeframe = models.IntegerField(verbose_name='timeframe during which more points cannot be reclaimed', null=True, blank=True) class MyModel(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, blank=True, … -
Vue.js does't work in HTML with Django, please assist me
The code run: Here is the code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src='../static/js/vue.min.js'></script> <script src='../static/js/axios.min.js'></script> <script src="../static/js/jquery-3.6.1.min.js"></script> <!--Css--> <link rel="stylesheet" href='../static/css/home.css'> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet"> <!--Bootstrap 5--> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <div id="register"> <div class="container my-5"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <form method="post"> {% csrf_token %} <a href="{% url 'home' %}"> <h2 class="text-center mb-4" style="text-decoration: none; color: black; font-size:2em;"> MoHome </h2> </a> <div class="mb-3"> <label for="username" class="form-label">User Name</label> <input v-bind:value="username" type="text" class="form-control" id="username" required="required"> </div> <h3>{[ 10/2 ]}</h3> <div class="mb-3"> <label for="firstname" class="form-label">First Name</label> <input v-bind:value="firstname" type="text" class="form-control" id="firstname" required="required"> </div> <div class="mb-3"> <label for="lastname" class="form-label">Last Name</label> <input v-bind:value="lastname" type="text" class="form-control" id="lastname" required="required"> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input v-bind:value="email" type="email" class="form-control" id="email" required="required"> </div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input v-bind:value="password" type="password" class="form-control" id="password" required="required"> </div> <div class="mb-3"> <label for="confirmPassword" class="form-label">Confirm Password</label> <input v-bind:value="confirmPassword" type="password" class="form-control" id="confirmPassword", required="required"> </div> <div class="text-center"> <button type="submit" class="btn btn-primary" v-on:click="register">Register</button> </div> </form> </div> </div> </div> </div> </div> </div> </body> <script> var register = new Vue({ el: '#register', data: { firstname: "", lastname: "", username: "", email: "", password: "", confirmPassword: "", … -
Django Forbidden (CSRF cookie not set.), solve without @csrf_exempt
I am getting this error when I call a route in localhost for my django app, http://127.0.0.1:8000/api/calculator/score/. This POST route sends data to a Flask app hosted on aws, and gets back a "score" from there. The route works if I have the decorator @csrf_exempt, but that seems like a bandaid/temporary/bad solution. However, this is the solution that most other similar posts on Stack Overflow suggest. How do I allow the request to process without using @csrf_exempt? I have listed the route in my settings.py like: CSRF_TRUSTED_ORIGINS = [ '<<my flask/amazon url here>>', "http://127.0.0.1:8000", "http://localhost:8000" ] and here is the code for the route in views.py: def post_for_score(request): body_unicode = request.body.decode('utf-8') body_dict = json.loads(body_unicode) flask_url = '<<my flask/amazon url here>>' res = requests.post(flask_url, json=body_dict) if res.status_code == 200: rj = res.json() print("rj: ", rj) return JsonResponse( rj ) else: return JsonResponse({ "error": str(res.content) }) Again, this works with the @csrf_exempt decorator, but I don't want to use that, as it seems unsafe in production. What are other ways to fix the problem? -
How to prevent django fields from being wrapped in a div?
If I use the below to generate multiple radio buttons: from django import forms class MCQCollectionForm(forms.Form): user_input = forms.ChoiceField( widget=forms.RadioSelect, label='', choices=enumerate(['option 1', 'option 2']) ) I get: <div id="id_user_input"> <div> <label for="id_user_input_0"><input id="id_user_input_0" name="user_input" required="" type="radio" value="0"> option 1</label> </div> <div> <label for="id_user_input_1"><input id="id_user_input_1" name="user_input" required="" type="radio" value="1"> option 2</label> </div> </div> but I want it to be only the below, nothing else: <label class="user-item"> <input name="user_input" type="radio" ... > <span>Lorem ipsum dolor q1</span> </label> <label class="user-item"> <input name="user_input" type="radio" ... > <span>Lorem ipsum dolor q1</span> </label> is there a simple way to do so without having to use JS and manually make the desired changes? -
Storing access_token and refresh_token in Django from a gapi response
I have an LMS application made with Django REST and Vue.js. To authenticate users, I use Google OAuth2 the following way: on the backend, I use drf-social-oauth2 and Google as my authentication backend on the frontend, I use this wrapper around gapi The way it works is the following: the user clicks on the login button and is redirected to the account selection page in Google which, when completed, returns an access token. The frontend makes a request to an endpoint on the backend which uses the convert-token function provided by drf-social-oauth2 to exchange the Google access token with an in-house token that the frontend can use from then on to authenticate requests. I recently added a Google Classroom integration to my application which makes some requests on the students' behalf to Classroom, which requires using their access tokens. The problem is that with this procedure, I don't actually keep the Google issued token on my backend; I just use it to generate the in-house token. How can I modify the procedure I outlined so that I can keep users' access tokens? I thought I had a plan but apparently it's not quite what I need: I created this model … -
URL in django admin
I have problem to display clickable link in django admin panel next to 'icon' field or add help_text witch will be clickable and if i click on it, it must open this 'https://fonts.google.com/icons?icon.set=Material+Icons' website in new window of browther . enter image description here link example : https://fonts.google.com/icons?icon.set=Material+Icons I tried this but nothing happens, it shows just normal models without link and text. **admin.py ** from .models import RaffleGame from django.utils.html import format_html from django.urls import reverse from django.contrib import admin class RaffleGameAdmin(admin.ModelAdmin): list_display = ('icon', 'link_to_google') def link_to_google(self, obj): url = 'https://fonts.google.com/icons?icon.set=Material+Icons' link_text = 'click me for more info' return format_html('<a href="{}">{}</a>', url, link_text) link_to_google.short_description = 'Mehr Icons findest du hier' admin.site.register(RaffleGame, RaffleGameAdmin) models.py class RaffleGame(models.Model): class GameStatus(models.TextChoices): scheduled = 'scheduled' announced = 'announced' draw_day = 'draw_day' drawn = 'drawn' finished = 'finished' class IconColor(models.TextChoices): red = 'red' yellow = 'yellow' black = 'black' green = 'green' title = models.CharField(max_length=500, default='PiA-Gewinnspiel', verbose_name='Titel') status = models.CharField(max_length=100, choices=GameStatus.choices, default=GameStatus.scheduled, verbose_name='Status', editable=False) announcement_date = models.DateField(verbose_name='Spiel ankündigen ab') draw_date = models.DateTimeField(verbose_name='Zeitpunkt der Auslosung') finished_date = models.DateField(verbose_name='Gewinner anzeigen bis') icon = models.CharField(max_length=100, default='park', verbose_name='Icon') icon_color = models.CharField(max_length=100, choices=IconColor.choices, default=IconColor.black, verbose_name='Icon Farbe') icon_outlined = models.BooleanField(default=False, verbose_name='Icon outlined') class Meta: db_table = "RaffleGame" def __str__(self): return … -
Gunicorn related error: ModuleNotFoundError: No module named 'django'
Below is my error log. I am running this command in the same folder as manage.py.... I have ensured that I am in a virtual environment and that Django is installed as a part of it. I don't understand why have issues with the following command -> gunicorn --bind 0.0.0.0:8000 ctfWebsite.wsgi (djangodev) jordangethers@jordangethers-VirtualBox:\~/FSU-CTF-Website-main/FSUweb/x_ctfWebsite$ gunicorn --bind 0.0.0.0:8000 ctfWebsite.wsgi \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Starting gunicorn 20.1.0 \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Listening at: http://0.0.0.0:8000 (9894) \[2023-03-22 18:06:08 -0400\] \[9894\] \[INFO\] Using worker: sync \[2023-03-22 18:06:08 -0400\] \[9895\] \[INFO\] Booting worker with pid: 9895 \[2023-03-22 18:06:08 -0400\] \[9895\] \[ERROR\] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 384, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return \_bootstrap.\_gcd_import(name\[level:\], package, level) File "\<frozen importlib.\_bootstrap\>", line 1050, in \_gcd_import File "\<frozen importlib.\_bootstrap\>", line 1027, in \_find_and_load File "\<frozen importlib.\_bootstrap\>", line 1006, in \_find_and_load_unlocked File "\<frozen importlib`your text`.\_bootstrap\>", line 688, … -
anybody acn help me solved problev ModelForm has no model class specified
I'm learne django and i'm beginner.I don't understand what the problem is in my code. I get problem, ModelForm has no model class specified, when i try create reviews. And i'm realy don't understand wheare problem. def createreview(request, movie_id): movie = get_object_or_404(Movie, pk=movie_id) if request.method == 'GET': return render(request, 'createreview.html', {'form':ReviewForm(), 'movie': movie}) else: try: form = ReviewForm(request.POST) newReview = form.save(commit=True) newReview.user = request.user newReview.movie = movie newReview.save() return redirect('detail', Review.movie.id) except ValueError: return render(request, 'createreview.html', {'form':ReviewForm(), 'error':'bad data passed in'}) class ReviewForm(ModelForm): def __init__(self, *args, **kwargs): super(ModelForm, self).__init__(*args, **kwargs) self.fields['text'].widget.attrs.update({'class':'form-control'}) self.fields['watchAgain'].widget.attrs.update({'class':'form-check-input'}) class Meta: models = Review fields = ['text', 'watchAgain'] labels = {'watchAgain': ('Watch Again')} widgets = {'text': Textarea(attrs={'rows': 4}), } class Review(models.Model): text = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) watchAgain = models.BooleanField() def __str__(self): return self.text Please help solve it's problem -
why do i get this error mssg- Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings
I already have the latest version of python3 installed in my computer, why do i get this error message "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases". This is the command am trying to run on Pycharm terminal window - "python3 manage.py runserver". I am using a window PC. It supposed to give me my development web server -
Django Selenium running tests in particular order
I'm having a problem running tests in a registration system using Django and Selenium since it starts testing my last written test in app/tests.py. I'm testing a registration system so I first wrote the user registration tests which it pass, then I wrote the login tests but when running ./manage.py test myapp it tries first to log in before registering a user. Any idea how to organize tests to run one before another, and, why is it running my last test before, any clues? -
How to loop to add event handler to buttons?
I have made my scripts.js and my html page and have successfully linked them together, however, the loop to add event listeners to my buttons doesn't seem to be applying. I have tried re writing the code and have tried to get a different value but nothing comes out as the output. JavaScript JavaScript console.log('Successful Connection!') var updateBtns = document.getElementsByClassName("update-cart") for (let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productID = this.dataset.product var action = this.dataset.action console.log('product id:', productID, 'action', action) }) } HTML {% extends 'pages/home.html' %} {% block content %} <h3>Video Games</h3> <h6>Name | Publiser | Price | Rating</h6> {% for game in video_games %} <div class="card col-sm product" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{game.name}}</h5> <h6 class="card-subtitle mb-2 text-muted">This game is rated {{game.age_rating}}</h6> <h6 class="card-subtitle mb-2 text-muted">{{game.publisher}}</h6> <h6 class="card-subtitle mb-2 text-muted">${{game.price}}.00</h6> <h6>{{game.id}}</h6> <button onclick="" data-product="{{game.id}}" data-action="add" class="update-cart btn add-btn">Add to cart</button> </div> {% endfor %} {% endblock content %} -
Django AJAX can't find url
I'm using AJAX request to delete comment from product page, but django can't find url (I'm getting this log ). Box url: path('box/<int:id>', views.box, name='box') , delete url: path('delete-comment/<int:id>', views.delete_comment, name='delete_comment'),. My AJAX call: comment.addEventListener("click", () => { fetch(`delete-comment/${comment.dataset.comment_id}`, { method: "DELETE", headers: { "X-Requested-With": "XMLHttpRequest", } }) }); And view: def delete_comment(request, id): if request.headers.get("X-Requested-With") == "XMLHttpRequest": if request.method == 'DELETE': comment = Comment.objects.get(id=id) if comment.user == request.user: comment.delete() return HttpResponseBadRequest('ok') else: return HttpResponseBadRequest('Invalid request') I think there is something wrong with url. Why is django looking for /box/delete-comment/id, shouldn't it look for /delete-comment/id or /box/box-id/comment/id? I tried some options but none of them worked. I also couldn't find any similar problem. I even can't identify problem properly. Can you help me? -
Generated // in the URL (Django)
Somehow my program generated two slashes // when I tried to add a new Menu item. Don't know how to fix that Page not found (404) Request Method:POSTRequest URL:http://127.0.0.1:8000/restaurant/menu/desserts-menu//add_menuItem/ Using the URLconf defined in WAD_Group_Project.urls, Django tried these URL patterns, in this order: [name='index'] restaurant/ [name='index'] restaurant/ about/ [name='about'] restaurant/ menu/<slug:menu_name_slug>/add_menu_item/ [name='add_menu_item'] restaurant/ menu/<slug:menu_name_slug>/ [name='show_menu'] restaurant/ menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/ [name='show_menu_item'] restaurant/ add_menu/ [name='add_menu'] restaurant/ menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/add_review/ [name='add_review'] restaurant/ restricted/ [name='restricted'] admin/ accounts/ ^media/(?P<path>.*)$ The current path, restaurant/menu/desserts-menu//add_menuItem/, 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. Urls.py from django.urls import path from restaurant import views app_name = 'restaurant' urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name = 'about'), path('menu/<slug:menu_name_slug>/add_menu_item/', views.add_menu_item, name='add_menu_item'), path('menu/<slug:menu_name_slug>/', views.show_menu, name='show_menu'), path('menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/', views.show_menu_item, name='show_menu_item'), #Template shows form but without any functionality path('add_menu/', views.add_menu, name="add_menu"), path('menu/<slug:menu_name_slug>/<slug:menuItem_name_slug>/add_review/', views.add_review, name="add_review"), path('restricted/', views.restricted, name='restricted'), ] Views.py def show_menu(request,menu_name_slug): context_dict = {} try: menu = Menu.objects.get(slug=menu_name_slug) menuItems = MenuItem.objects.filter(menu=menu) context_dict['menuItems'] = menuItems context_dict['menu'] = menu except Menu.DoesNotExist: context_dict['menu'] = None context_dict['menuItems'] = None return render(request, 'restaurant/menu.html', context=context_dict) def show_menu_item(request, menu_name_slug, menuItem_name_slug): context_dict = {} try: menu = Menu.objects.get(slug=menu_name_slug) menuItem = MenuItem.objects.get(slug=menuItem_name_slug) … -
best way to generate statistical data in python for django objects
so i have 3 models; Employee, Products and Sale the Sale object has a JSON string of products sold in this sale, a category field, datetime of the sale and a reference to the Employee object who completed the sale i need to create graphs on demand where the user would specify the time period and intervals for the graph's X axis and choose what to display in the Y axis (choices are amount, total, ..etc for all sales or for a specific employee or product) what is the most efficient way to generate graph data for all these objects? for example i want to create a sales per day for a specific employee or a profit per day or hour or month that would count how many sales this employee made per day for a specified time period or create a profit per day for a specific category or product(which is saved as json in sale objects) problems arise when i want to calculate the graph data for a specific product because it is saved as json data in the Sale object. what i am looking for is an efficient way to generate all these graphs and tips for … -
Django ImageField specific directory is full (maximum number of files in linux dir)
While having this: profile_pic: ImageField = models.ImageField( _("profile_picture"), upload_to='profile_pic', blank=True, null=True) And 23M record I found out that profile_pic is "full" ("no space left on device") while having 300GB free. I thought of splitting the the files to folders with the first 3 letters, but how can I achieve that in the django ? REF: https://askubuntu.com/questions/1419651/mv-fails-with-no-space-left-on-device-when-the-destination-has-31-gb-of-space https://pylessons.com/django-images -
I can't find and fix the error in the code
I'm a beginner and I'm creating my first website on DJANGO and when writing the code I get this error products.append(Product(body,'red','100 pcs','9999 rub','4500 gramm')) ^^^^^^^^^^^^^^^ AttributeError: 'Product' object has no attribute 'append' please help me find what the code error is and fix it from django.shortcuts import render from django.http import HttpResponse,HttpRequest import random class Product: __MAX_ID = 0 def __init__(self, name:str, color: str, availability: str, cost: str, weight: str): self.id = Product.__MAX_ID self.name = name self.color = color self.availability = availability self.cost = cost self.weight = weight Product.__MAX_ID += 1 def __str__(self): return ( f'{self.name}\n' + f'color: {self.color}\n' + f'availability: {self.availability}\n' + f'cost: {self.cost}\n' + f'weight: {self.weight}\n' ) products=Product('nuke','red','100 pcs','9999 rub','4500 gramm') def test(request:HttpRequest): body=request.body.decode('UTF-8') products.append(Product(body,'red','100 pcs','9999 rub','4500 gramm')) return HttpResponse('\n'.join(str(product) for product in products))` I tried to change the product, but alas, nothing happened.maybe I have poor programming knowledge -
can not display form in django
i made a from , but for some reason it not show up when i try to display it. my forms supposed to collet information for blood donation. i did it by tutorial, and in the tutrial it just showed up, same as in any other tutorial i saw after. my models.py from django.db import models from django.contrib.auth.models import User class donate(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) doner_ID = models.CharField(max_length=9) blood_types = [ ('A+','A+'), ('B+','B+'), ('AB+','AB+'), ('O+','O+'), ('A-','A-'), ('B-','B-'), ('AB-','AB-'), ('O-','O-'), ] blood_type = models.CharField( max_length=3, choices=blood_types, default=blood_types[0], ) donation_date = models.DateField(auto_now_add=True) def __str__(self): return self.first_name my forms.py from django import forms from django.forms import ModelForm from .models import donate class donationForm(ModelForm): class Meta: model = donate fields = ('first_name', 'last_name', 'doner_ID', 'blood_type') my views.py from .forms import donationForm from .models import donate def donation(request): form=donationForm if request.method == 'POST': return render(request, 'main\donation.html', {'from':form}) else: return render(request, 'main\donation.html', {'from':form}) the donation.html page {% extends 'main\design.html'%} {% block design %} {{ errors }} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-outline-danger btn-block">Submit</button> </form> {% endblock %}