Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django setup model with multi value integer field
How can we setup a field in a model to accept more than on value? We simply can make relation fields using foreign key or many to many but in case of simple int or float or any simple variable type , how can we achieve multi value field? -
I want any radio button upon selection, to be saved into the database. What do I need to do in order to achieve that?
enter image description here I want to select and save an option in the database from the given 4 options. These options are being called from the database itself through the models file. Any help would be great! -
How to share database details in Github correctly, using Django and PostgreSQL?
I have an assignment in which I need to set up a database server using Python Django and PostgreSQL. I need to assign the project in Github, and the grader will use my repository to check my project. In my setting.py file I have the following lines: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'CourseDB', 'USER': 'postgres', 'PASSWORD': '123', 'HOST': 'localhost', 'PORT': '5432' } } What to do so the details on my file will be correct for the grader's side? Will they have to create a database with the given name, user and password like the ones in my file? I think that maybe for the database name, I can add in the readme to run CREATE DATABASE CourseDB first. But then again, I don't know their user and password on their machine, So I don't know what should be written in my file in order for my code to work on their machine. I followed this tutorial on YouTube to create my file. -
Order and OrderItem Logic
I'm working on an inventory management project for a warehouse selling items in bulk. I'm a having hard time figuring out the logic for my orders (Dumb me). What I have at the moment is an Order model and an OrderItem model, the basic idea is that a single order, might contain multiple items with default or custom pricing. Here's my Order model class Order(models.Model): creation_date = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) paid_amount = models.IntegerField(default=0) def __str__(self): return f'{self.creation_date.strftime("%Y%m%d")} - {self.customer.full_name}' def get_absolute_url(self): return reverse('order-detail', kwargs={'pk': self.pk}) @property def is_fully_paid(self): # Couldn't figure out how to write the rest. Here's my OrderItem model class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) custom_single_product_price = models.IntegerField(blank=True, null=True) def __str__(self): return f'{self.creation_date.strftime("%Y%m%d")} - {self.customer.full_name} - {self.product.title}' Here's my Product model class Product(models.Model): creation_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=128) sku = models.CharField(max_length=30, blank=True, null=True) photo = models.ImageField(upload_to='product_photos/', blank=True, null=True) number_of_boxes = models.IntegerField(default=1) number_of_products_per_box = models.IntegerField(default=1) single_product_price = models.IntegerField(default=1000) def __str__(self): return self.title def get_absolute_url(self): return reverse('product-detail', kwargs={'pk': self.pk}) a product already has a single_product_price which should be used as the default price at checkout, however, managers at the warehouse are able to customize that default to something else entirely … -
Deceptive site ahead google chrome when i tried to open the ngrok url
recently I came across this issue when I exposed my port via ngRok. I simply forwarded it but when I tried to open the ngRok url I got Deceptive site ahead warning. Here is the image of the warning. It was a django server with graphql and I wanted to test graphiql. (this point might not be necessary for the reader but more info is always better than no info) -
django zappa and aws lambda : any way to set the database as a static asset?
Im looking into hosting a django website with zappa on aws lambda or digital ocean function. Regarding the database, do i need to pay a service to host the database if the website is only very small and the database will not be big? Could I declare the database as a static asset? How could i do that ? thank you best, -
How to add a verbose_name in forms.py Django?
class ApplicationForm(BaseForm): class Meta: model = Application fields = ['referencenumber', 'name', 'description', 'owner'] I have the above form from models.py. However I want to put labels on the form that are different than the verbose_name of models.py. I can't edit models.py since we are too far into development. Any way to do this in forms? Please help! -
ListView with different outputs depending on POST or GET
My app is a db of entries that can be filtered and grouped in lists. Index page should show all entries properly paginated, with no filters, and a search form to filter by entry name and types. Is there a way to do this with one ListView and one template, changing behaviors depending if the page was accessed from index (with GET) or from a search (with POST)? If so, how can I change template page title to "Index" or "Search results" accordingly? -
Django Search Filter
I want to search full text (multiple keyword) with regex for any column in Django. i know in django already there is filtering full text search with search vector but can i combine with regex? or perhaps there is any way to search with regex for any column with multiple keyword. -
how to authenticate user in Django rest framework using http only cookie
I am using Django and Django Rest Framework for the backend and Next JS for the frontend. I am using JWT authentication. When Requesting from the frontend I am issuing a http only cookie to store in the frontend. My Question is how I can authorize a private endpoint to use that cookie? Code for Generating Cookie def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class LoginView(APIView): def post(self, request, format=None): data = request.data response = Response() email = data.get('email', None) password = data.get('password', None) user = authenticate(username=email, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie(key='token', value=data["access"], httponly=True, samesite='None', secure=True, expires=settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']) response.data = data return response else: return Response({"detail": "This account is not active!!"}, status=status.HTTP_404_NOT_FOUND) else: return Response({"detail": "Invalid username or password!!"}, status=status.HTTP_404_NOT_FOUND) Code for the Login Component in the Frontend interceptor .post("/token/", data, { withCredentials: true, }) .then((res) => { router.query?.from ? router.push(router.query?.from) : router.push("/admin"); }) Other Private Route API class BlogTagsView(generics.ListCreateAPIView): """ List of Blog Tags """ permission_classes = [apipermissions.IsSuperUser] queryset = models.TagModel.objects.all() serializer_class = serializers.TagSerializers settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': … -
Django-ordered-model doesn't let me update models
I was trying to figure out Django and the ordered model but when I updated my model 'something' from models.Model to OrderedModel things got weird. So I had a variable TextField under my model 'something' which already had migrations and stored data, but due to the update from models.Model to OrderedModel the existing data presented issues with the migration. The error is as shown-- You are trying to add a non-nullable field 'order' to a resource without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Can you help me out? I don't want to lose my data. -
Docker-compose python3 mysqlclient pip install error
I've been using docker-compose to containerise my Django web app, every time I try to run docker-compose, it comes up that python setup.py egg_info did not run successfully within the mysqlclient package. Here is the full error output: #0 14.79 × python setup.py egg_info did not run successfully. #0 14.79 │ exit code: 1 #0 14.79 ╰─> [16 lines of output] #0 14.79 mysql_config --version #0 14.79 /bin/sh: mysql_config: not found #0 14.79 mariadb_config --version #0 14.79 /bin/sh: mariadb_config: not found #0 14.79 mysql_config --libs #0 14.79 /bin/sh: mysql_config: not found #0 14.79 Traceback (most recent call last): #0 14.79 File "<string>", line 2, in <module> #0 14.79 File "<pip-setuptools-caller>", line 34, in <module> #0 14.79 File "/tmp/pip-install-pmudu0sw/mysqlclient_47f69dea011449a8a2de262e86e628d2/setup.py", line 15, in <module> #0 14.79 metadata, options = get_config() #0 14.79 File "/tmp/pip-install-pmudu0sw/mysqlclient_47f69dea011449a8a2de262e86e628d2/setup_posix.py", line 70, in get_config #0 14.79 libs = mysql_config("libs") #0 14.79 File "/tmp/pip-install-pmudu0sw/mysqlclient_47f69dea011449a8a2de262e86e628d2/setup_posix.py", line 31, in mysql_config #0 14.79 raise OSError("{} not found".format(_mysql_config_path)) #0 14.79 OSError: mysql_config not found #0 14.79 [end of output] #0 14.79 #0 14.79 note: This error originates from a subprocess, and is likely not a problem with pip. #0 14.80 error: metadata-generation-failed #0 14.80 #0 14.80 × Encountered error while generating package metadata. … -
Ajax checkbox values are not taking from the form and saved to django database
enter image description here`I want to save checkbox value 1 for True and 0 for False.But in this case checkbox values are always saved to 0. Here is my Html form,script.js and views.py -
ImportError: cannot import name 're_path' from 'django.conf.urls'
I'm following a Django tutorial and trying to update a urls.py file with the following code: from django.contrib import admin from django.urls import path from django.conf.urls import re_path, include urlpatterns=[ path('admin/', admin.site.urls), re_path(r'^',include('EmployeeApp.urls')) ] When I run the server with python manage.py runserver I get the following error: ImportError: cannot import name 're_path' from 'django.conf.urls' (C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\conf\urls\__init__.py) I'm running version 4.0.4 of Django: py -m django --version # Prints: 4.0.4 -
Django: This queryset contains a reference to an outer query and may only be used in a subquery
I have a queryset which returns an error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I need a little help to know that what I am doing wrong. Below is my query def get_queryset(filters: dict) -> QuerySet: return JobDest.objects.filter( line__j_id=filters["j_id"] ).annotate(c_count=(Value(Subquery(Candidate.objects.filter(job=filters["j_id"], is_d=False, stage=OuterRef('id')).count())))) -
how to create custom flag like is_staff and is_anonymous in django
There are some Boolean fields in django User Model, for example is_staff, is_anonymous. how can in create my own Boolean for example is_student and add it into django User model -
How to activate an account that has been registred trough e-mail with Django
I want to when my user is registred to generate a token and that token to be sent to e-mail to when I click the link verify the account code: def register_account(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' email_body = 'i dont know to do do it' email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to], fail_silently=False //////////////////// def activate_account: if the link is clicked: check the link than activate the account -
digital ocean django website deployment in a function
I'm designing a website and I would like to use digitalocean hosting. I have seen the tutorials to set up django on a server or on the app platform but i havent seen anything to set up django as served by a function (like aws lambda). I'm looking for documentation on the subject or for a step by step tutorial. Can anyone provide feedback on this? Thank you -
Django and Vue: I keep geetting "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" in my website
I'm doing this project using Vue and Django, but when I run my code, I keep getting this error "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yellow-jacket-with-no-zipper:1" I kept reloading and waited 30 minutes for this error to go away, but it keeps appearing. I don't know if there is a problem in my javascript, because I don't have any errors when I run the vue project. Here's my code I think has the problem. Back end: urls.py module in Products package urls.py module in product package: from django.urls import path, include from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>', views.ProductDetail.as_view()), ] Front end: Product.vue script: <template> <div class="page-product"> <div class="columns is-multiline"> <div class="column is-9"> <figure class="image mb-6"> <img v-bind:src="product.get_image"> </figure> <h1 class="title">{{ product.name }}</h1> <p>{{ product.description }}</p> </div> <div class="column is-3"> <h2 class="subtitle">Information</h2> <p>Price: <strong>{{ product.price }}</strong></p> <div class="field has-addons mt-6"> <div class="control"> <input type="number" class="input" min="1" v-model="quantity"> </div> <div class="control"> <a class="button is-dark">Add to Carts</a> </div> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'Product', data() { return { product: {}, quantity: 1 } }, mounted() { this.getProduct() }, methods: { getProduct() … -
How To maintain two sessions at a time in django using sso and custom login
User should have two logins: 1.Microsoft sso login using djano which will generate session id and set cookie 2.custom login to custom page after sso is generating again session id and set cookie. 3. we need to logout only from custom login when logout(request) called. but logging out from both custom login and sso login. Any help will appreciable. -
why does set_all() attribute is not taking values(message_set()
I am new with Django, in this view .i planned to show the name of the message sender in the template.so in the view i created a room message variable. in the template section i used a loop for alliterating the values. but the loop is not alliterating. view def room(request, pk): room = Room.objects.get(id=pk) **room_messages = room.message_set.all()** context = {'room': room, 'room_messages': room_messages} return render(request, 'room.html', context) models class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() update = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] template {% block content %} <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3>Conversation</h3> <hr> **{%for message in room_messages%}** <div> <h1>{{message.user}}</h1> </div> {%endfor%} </div> {% endblock %} the loop is not alitrating, -
django-s3direct multibytes uploading error
When uploading the multibyte file such as (テスト.jpg) with django-s3direct This error comes in browser console. Uncaught (in promise) TypeError: n.includes is not a function (s3direct.js:51) at m.warn (s3direct.js:51:2581) at S.y.error (s3direct.js:44:28150) If you don't use multibytes there is not error occurs. Is there a any setting I should do for S3 or django-s3direct ? -
Django: My attempt to update an instance instead creates a new instance
Description: I'm fairly certain I'm misunderstanding something obvious here, but I've stripped the code back to its basics and for whatever reason I can't find the problem. It actually worked in an earlier iteration (following the advice of other S/O posts), but evidently I broke something when editing my code at some point. Note: I've removed code that seems extraneous to this topic. Expected behaviour/s: If the user selects the "Edit" button on the index.html page they are taken to edit_booking.html where the CustomerForm is populated by the selected Customer instance. (This appears to work as expected. I think it's possible that there's a fault with my mental model, but I'm not sure what.) If the user selects the "Save" button on the edit_booking.html page, the selected Customer instance is updated/replaced by whatever the user has entered (or was already in) the form. (This does not work as expected. Instead, when the user selects the "Save" button, a new Customer instance is created from the contents of the edit_booking.html form.) What I've tried: I replaced the passing of the customer variable in views.edit_customer (and edit_customer.html) with just the customer_id instead (i.e., "customer_id": customer_id), but that didn't help. I mean I … -
Building Web Applications with Django
File “C:\Users\ASUS\vidly\movies\admin.py”, line 2, in from .models import Genre, Movie ImportError: cannot import name 'Movie' from 'movies.models' (C:\Users\ASUS\vidly\movies\models.py) How to solve this problem? [admin.py] : https://i.stack.imgur.com/tHm6q.png -
from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 ImportError: attempted relative import with no known parent package
This problem arose when I tried to run the views.py file of the Django template.When I run python manage.py runserver on terminal. I got from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 ImportError: attempted relative import with no known parent package image This is a face_recognition attendance system.