Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restart Nginx server with Github Action yaml file
I am working on a Django project, I am new in Github Action, I had set up Github action file name: Django CI on: push: branches: [ master ] jobs: build: runs-on: self-hosted steps: - uses: actions/checkout@v3 - name: Install Dependencies run: | virtualenv -p python3 env . env/bin/activate pip3 install -r requirements.txt My file get uploaded but issues is that I had to restart the Nginx server, How I can Restart Nginx server -
How to fix an Sending E-mail error in Django
Im getting an error trying to send an e-mail trough Django that I need to solve it I get this error with this settings.py: "getaddrinfo failed" if DEBUG: EMAIL_HOST = 'stmp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = 96274717 # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' and I get this error with this setting.py ConnectionRefusedError at /django-store-account/register/ I need to find a way to fix sending e-mail in Django for me to verify the accounts if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = 96274717 # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' my urls.py: path('register/', views.account_register, name='register'), views.py: def account_register(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' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email_body = message email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = … -
Using Django Channels (websocket layer consumer) to update a webpage with data from an internal database and external an data source
I have the following django channels class which updates values on a webpage webpage. The class receives data from screen clicks, performs actions (toggling indicdual relays or setting a series of them for a particular use, updates a databse and then updates the webpage via a websocket layer. All this worked fine until I introduced nina. This receives data from a remote source via a curl POST (see below). A curl POST results in the fail: 'TypeError: nina() missing 1 required positional argument: 'request', but if I drop 'self' I don't see how I can call 'update_relays' using its data. import logging import json from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import dbConditions, dbRelays logger = logging.getLogger(__name__) class DomeControlConsumer(SyncConsumer): """#from https://channels.readthedocs.io/en/latest/topics/consumers.html""" def websocket_connect(self, event): """Connects to webpage""" logger.debug("connected - Event: %s", event) async_to_sync(self.channel_layer.group_add)( "dome_control_group", self.channel_name ) # make the group layer for signals to send to self.send({ "type": "websocket.accept" }) self.build_and_send_context() def websocket_receive(self, event): """recives button presses from webpage either 'control_button' or relays 1 through 8""" logger.debug("received: %s from %s", event, event["text"]) self.update_relays(event["text"]) # if the control button was pressed or if a relay button is pressed def websocket_disconnect(self, … -
Adding container commands to elastic beanstalk breaks deployment
I have a django web app hosted via elastic beanstalk Due to the fact that ./platform/hooks/postdeploy migrate command seems to no longer bee working (Django migrations no longer running on aws) I have tried to use container commands in my django.config file instead container_commands: 00_test_output: command: "echo 'testing.....'" 01_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py migrate --noinput" leader_only: true This, however, provokes the error on deployment: 2022-05-25 08:03:36 WARN LoadBalancer awseb-e-g-AWSEBLoa-Q8MLS7VPZA00 could not be found. 2022-05-25 08:03:36 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. This error occurs even if only the 00_test_output command is included. Does anyone have an idea as to why the loadbalancer cannot be found when container commands are added? -
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: table customer_ordermod el has no column named created_on
I want to build a food delivering app, but facing this error. "return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: table customer_ordermod el has no column named created_on" this is the view.py from ast import Return from multiprocessing import context from django.shortcuts import render from django.views import View from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category__name__contains='Appetizer') main_course = MenuItem.objects.filter( category__name__contains='Main Course') desserts = MenuItem.objects.filter(category__name__contains='Dessert') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'appetizers': appetizers, 'main_course': main_course, 'desserts': desserts, 'drinks': drinks, } # render the templates return render(request, 'custormer/order.html', context) def post(self, request, *args, **kwargs): order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price'] item_ids.append(item['id']) order = OrderModel.objects.create(price=price) order.items.add(*item_ids) context = { 'items': order_items['items'], 'price': price } return render(request, 'customer/order_conformation.html', context) this is my model.py from time import strftime from unicodedata import category, name from … -
(Django jwt token) get specific user with user id
Current I am retrieving user data with the UserViewSet like this: class UserViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) What I did was to make a GET request the via the endpoint `http://localhost:8000/account/auth/user/${id}` together with a Bearer jwt Token on the header. However, I realized that I can get the all the user with the same jwt token because of the Account.objects.all(), which is not I wanted at all. I want to get the specific user corresponding to their id with their unique jwt token. Anyone has an idea how to do it? Thanks a lot. -
psycopg2 NotNullViolation on column "ip" for Django/Gunicorn/Nginx system
I have a Django system that has gunicorn hosting the dynamic content and nginx the static, nginx passing through to gunicorn as required via a Unix socket. Every request that requires static content is generating an error like that below. Is this because the request comes from a Unix socket and not via IP? How do I fix this? A Quick "Google" hasn't helped but perhaps I've not found the right question yet :-(. django.db.utils.IntegrityError: null value in column "ip" violates not-null constraint DETAIL: Failing row contains (48, 302, GET, /, 2022-05-25 07:51:28.855717+00, f, f, null, , Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., en-GB,en;q=0.9,en-US;q=0.8,mt;q=0.7, null). Thanks for any suggestions. -
MongoDB driver to support most Django functionality
As per the project requirment, I have to use Django + MongoDB. I am super new to Django (not good in Django's ORM too) but have good experience with MongoDB. My project is about storing a lot of Schemaless data and then making analysis reports or use for machine learning etc. MongoDB states PyMongo as official driver for Python projects but, there are bunch of other drivers also available like mongoengine, djongo, motor etc. After reading a lot of articles, still I can't find simple answer to my question: WHICH DRIVER SUPPORT MOST OF DJANGO FUNCTIONALITY About Djongo, This link states that: because it supports all django contrib libraries. Using Djongo, all we need to do is setting up and changing the models base import, no need to worry about changing serializers, views, and all other modules. If I use PyMongo, will I miss any advantage of Django except ORM? I am open for suggestions and critisism as i just started learning this... -
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