Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Postgresql RDS instance "does not exist" with docker-compose and Django
My RDS and web container are not connected. But I did all the database-related settings in Django's settings, and I also set up AWS RDS properly. What should I do more? This is DATABASES of settings file of Django. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env("SQL_DATABASE"), "USER": env("SQL_USER"), "PASSWORD": env("SQL_PASSWORD"), "HOST": env("SQL_HOST"), "PORT": env("SQL_PORT"), } } I skipped the docker-compose.yml with enginx-proxy or TLS. When I tested in local, I made and mounted DB containers on docker-compose, butin prod environments, I didn't make DB containers because I use RDS. Will this be a problem? Please help me. (ps.All of PROJECT_NAME replaced the actual project name.) This is my docker-compose.yml version: '3.8' services: web: build: context: . dockerfile: prod.Dockerfile image: project:web command: gunicorn PROJECT_NAME.wsgi:application --bind 0.0.0.0:8000 env_file: - envs/.env.prod volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 entrypoint: - sh - config/docker/entrypoint.prod.sh volumes: static_volume: media_volume: This is what I've got error from docker Waiting for postgres... PostgreSQL started Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", … -
Django deploy error Heroku push , at least twice. One common cause of this behavior is attempting to deploy code from a different branch?
PS C:\Users\xxx\PycharmProjects\CV_Web> heroku push master » Warning: heroku update available from 7.53.0 to 7.59.0. » Warning: push is not a heroku command. Did you mean ps? [y/n]: » Error: Run heroku help for a list of available commands. PS C:\Users\xxx\PycharmProjects\CV_Web> git push heroku master Enumerating objects: 79, done. Counting objects: 100% (79/79), done. Delta compression using up to 4 threads Compressing objects: 100% (69/69), done. Writing objects: 100% (79/79), 1.31 MiB | 363.00 KiB/s, done. Total 79 (delta 11), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 66ba671891644a7496996ccf36aa72631f6d2aec remote: ! remote: ! We have detected that you have triggered a build from source code with version 66ba671891644a7496996ccf36aa72631f6d2aec remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! … -
Creating a index for a Django Full Text Search
I'm implementing full text search on a blog using Django 3.2 and PostgreSQL 12.8. I have a database with 3.000 posts and my searchbar searches through post_title, post_subtitle and post_text. This search has weights, is ranked and is paginated. The search is working like a charm, but its somewhat slow. The exact query Django is doing is: SELECT "core_post"."id", "core_post"."blog_name", "core_post"."post_url", "core_post"."post_title", "core_post"."post_subtitle", "core_post"."post_text", ts_rank(((setweight(to_tsvector(COALESCE("core_post"."post_title", '')), 'A') || setweight(to_tsvector(COALESCE("core_post"."post_subtitle", '')), 'B')) || setweight(to_tsvector(COALESCE("core_post"."post_text", '')), 'C')), plainto_tsquery('Angel')) AS "rank" FROM "core_post" WHERE ts_rank(((setweight(to_tsvector(COALESCE("core_post"."post_title", '')), 'A') || setweight(to_tsvector(COALESCE("core_post"."post_subtitle", '')), 'B')) || setweight(to_tsvector(COALESCE("core_post"."post_text", '')), 'C')), plainto_tsquery('Angel')) >= 0.3 ORDER BY "rank" DESC LIMIT 15 When I explain analyse it, I get this: Limit (cost=26321.90..26323.63 rows=15 width=256) (actual time=662.709..664.002 rows=15 loops=1) -> Gather Merge (cost=26321.90..26998.33 rows=5882 width=256) (actual time=662.706..663.998 rows=15 loops=1) Workers Planned: 1 Workers Launched: 1 -> Sort (cost=25321.89..25336.60 rows=5882 width=256) (actual time=656.142..656.144 rows=12 loops=2) Sort Key: (ts_rank(((setweight(to_tsvector((COALESCE(post_title, ''::character varying))::text), 'A'::"char") || setweight(to_tsvector(COALESCE(post_subtitle, ''::text)), 'B'::"char")) || setweight(to_tsvector(COALESCE(post_text, ''::text)), 'C'::"char")), plainto_tsquery('Angel'::text))) DESC Sort Method: top-N heapsort Memory: 33kB Worker 0: Sort Method: top-N heapsort Memory: 32kB -> Parallel Seq Scan on core_post (cost=0.00..25177.58 rows=5882 width=256) (actual time=6.758..655.854 rows=90 loops=2) Filter: (ts_rank(((setweight(to_tsvector((COALESCE(post_title, ''::character varying))::text), 'A'::"char") || setweight(to_tsvector(COALESCE(post_subtitle, ''::text)), 'B'::"char")) || setweight(to_tsvector(COALESCE(post_text, ''::text)), 'C'::"char")), plainto_tsquery('Angel'::text)) >= … -
Using previous data of a model in the creation view class to store in other model
I'm working on an app, where I store information about fuel consumption of vehicles, the goal is every time a vehicle refuels to calculate the consumption per km of fuel and storing it. my models are: class Refuel(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name=_("responsable_user"), default=1) vehicle = models.ForeignKey("vehicle.Vehicle", blank=True, null=True, on_delete=models.PROTECT) gaz_station = models.ForeignKey( GazStation, related_name=_("Refuel_Station"), blank=True, null=True, on_delete=models.PROTECT ) odometer_reading = models.PositiveIntegerField(_("Compteur KM"), blank=True, null=True) snitch = models.PositiveIntegerField(_("Mouchard KM"), blank=True, null=True) fuel_quantity = models.DecimalField(_("Quantitée en Litres"), max_digits=5, decimal_places=1) fuel_unit_price = models.DecimalField(_("Prix en DH"), max_digits=6, decimal_places=2) note = models.CharField(_("Remarque"), max_length=255, blank=True, null=True) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) is_active = models.BooleanField(default=True) @property def total_price(self): total_price = self.fuel_quantity * self.fuel_unit_price return total_price class Meta: ordering = ["gaz_station", "-created_at"] def __str__(self): return self.vehicle.serie class FuelConsumption(models.Model): vehicle = models.ForeignKey("vehicle.Vehicle", blank=True, null=True, on_delete=models.PROTECT) gaz_station = models.ForeignKey( GazStation, related_name=_("Station_consuption"), blank=True, null=True, on_delete=models.PROTECT ) Controlor_id = models.ForeignKey( User, blank=True, null=True, on_delete=models.PROTECT, limit_choices_to={"is_controlor": True, "is_active": True}, ) driver = models.ForeignKey( User, related_name=_("Vehicle_Driver_consuption"), blank=True, null=True, on_delete=models.PROTECT ) consumption = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) is_active = models.BooleanField(default=True) class Meta: ordering = ["vehicle", "-created_at"] def __str__(self): return self.vehicle.serie I have a view for Refuel model, … -
Which software to use to build scalable web site that supports forums, e-commerce, and collaboration?
I am not sure where to ask this question, hope you guys don’t mind I post it here. Which open source software that has most built-in support to build a web site with the following characteristics: Users can form sub-groups and a user can belong to multiple sub groups. Each group has more than one moderator with majority needed to delete postings. Reputation rating for users A user can view list of other users that meet specified characteristics Private messages between any users or set of users A user has his/her own web pages and tools to manage them. Discussion topics that viewable to all or sub-groups Live discussion (while looking at common document) that viewable to all or sub-groups Transaction support between any two users Scalable (to support more users) by essentially adding more hardware with minimal programming if possible. With my extremely limited knowledge, it seems something based on WordPress, Django-CMS, or phpBB are the choices. Although it seems none of them support all/most of the above spec. Many thanks for your thought. -
What is the usage of 'quaryset' attribute of the Django 'CreateView'?
I was wondering what is the usage of 'quaryset' attribute of the Django 'CreateView'? The official documentation was not satisfying the question and google isn't helpful enough! I am quite skeptic whether anything obvious is missing from my eyes. Thanks. -
Using two tables or single table with multiple rows?
I have two functions one is used for "requesting documents" (it can be more than 3) and another function is "Sending documents" (it also can be more than 2) Now my problem is both has various purpose, so should i need to create two table or single table with a differentiation ? How to handle this efficiently ? Option1: Create two table named "RequestedDocuments" & "SendDocuments" and save accordingly or Option2: Create a single table named "Documents" and have field named "Type" and save accordingly with some types like "request" & "send"?** My another concern is, In one of the view i need to show all the two in separate tables and in another view i need to show only one of the above ! So which is more efficient ? -
invalid literal for int() with base 10: b'13 18:33:25'
I am creating a portfolio website with a blog on it. Everyhting was working perfectly but suddenly the above mentioned error start showing up anytime I tried go to my blog link and it says ther is some thin wrong with my bootstrap css link: enter image description here let me know if you need anything else to find solution. Thanks -
django Model.objects.create not immediately assign primary key to variable how to access that?
I have django Student model like below class Student(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20) score = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return f"Student(id: {self.id}, name: {self.name}, salary: {self.score})" I have created some users in database also below is django shell output >>> s = Student.objects.create(name="erik", score=90) >>> print(s) Student(id: None, name: erik, salary: 90) # <----- here is showing id None >>> Student.objects.all() <QuerySet [<Student: Student(id: 1, name: alex, salary: 40.00)>, <Student: Student(id: 2, name: john, salary: 60.00)>, <Student: Student(id: 3, name: erik, salary: 90.00)>]> when i have called Student.objects.all() then it is showing id. I want to get id from s variable because i am performing unit testing like below. class GetSingleStudentTest(TestCase): def setUp(self): Student.objects.create(name="student1", score=50) Student.objects.create(name="student2", score=55) Student.objects.create(name="student3", score=80) Student.objects.create(name="student4", score=36) def test_get_single_student(self): # get API response response = client.get(reverse("student-detail", kwargs={"pk" : self.student2.pk })) # get data from db student = Student.objects.get(pk=self.student2.pk) serializer = StudentSerializer(student) self.assertEqual(response.data, serializer.data) So when i have tried to access self.student2.pk it is None like we saw in django shell also. So how can i get that id? because as i know Model.objects.create creates a user and also save into database then why id is None here? I am learning from this guide https://realpython.com/test-driven-development-of-a-django-restful-api/ … -
NoReverseMatch in Django, i can't access to details of the order each customers
I am trying to see the orders of each customer, but I get this error views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import OrderForm def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request): form_value = OrderForm() if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == 'POST': form_value = OrderForm(request.POST, instance=order) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST': order.delete() return redirect('/') context={'item':order} return render (request, 'accounts/delete.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/', views.createOrder, name='create_order'), … -
Displaying a many-to-many relationship in Django
Background: I have the following models for a visitor management app. Each site can have multiple visitors and each visitor can visit multiple sites. I am unable to find a way to show a list of visitors on each site or show a list of sites a visitor has visited. I have removed unnecessary fields. .models.py class Site(models.Model): name = models.CharField(max_length=100, unique=True) accomodation = models.BooleanField(default=False) visitors = models.ManyToManyField('Visitor', blank=True) class Visitor(models.Model): name = models.CharField(max_length=50, null=False, blank=False) email = models.EmailField(max_length=200, null=False, blank=False, unique=True) ... admin.py class AdminArea(admin.AdminSite): vms_admin = AdminArea(name='vms_admin') @admin.register(Site, site=vms_admin) class SiteAdmin(admin.ModelAdmin): fieldsets = (*removed*) list_display = [*removed*] list_filter = (*removed*) @admin.register(Visitor, site=vms_admin) class VisitorAdmin(admin.ModelAdmin): fieldsets = (*removed*) list_display = [*removed*] list_filter = (*removed*) Django Admin This is how the list of sites looks: Django Admin Site List This is how the list of visitors look like: Django Admin Visitor List Question How do I show the list of visitors for each site and vice versa? For example: If I click on Gingin Gravity Precinct, I want to see the list of visitors associated with it, in a table, below "site details". Similar to the list of visitors shown, but specific to the site. Django Admin Specific Site -
Best practice Django : make sure User.username is unique even when User is deleted
I would like to know your thoughts about the Django best practice to ensure the uniqueness of a field value, even if objects are deleted. For example I create a CustomerUser with username = "carlos" , delete this user, then if I create another CustomerUser with username= "carlos" I will get an error. models.py class CustomUser(models.Model): username = models.CharField(max_length=100 , unique=True) shell user_one = CustomUser.objects.create(username="carlos") user_one.delete() user_two = CustomUser.objects.create(username="carlos") ---> This should not be possible. Should I save in another model all the usernames created or there is a Django function that assures the uniqueness of the username will be always True even after object deletion ? Thanks -
Django issue contact form with attribute?
models.py : class InformationRequest(models.Model): from_email = models.EmailField() subject = models.CharField(max_length=120) message = models.CharField(max_length=350) forms.py : from django import forms from .models import InformationRequest class ContactForm(forms.Form): from_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'contact__input', 'placeholder': 'Email'})) subject = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'contact__input', 'placeholder': 'Subject'})) message = forms.CharField(widget=forms.Textarea(attrs={'class': 'contact__input', 'cols': 0, 'rows': 8, 'placeholder': 'Message'}), required=True) views.py from django.shortcuts import render, redirect from .models import Home, About, Profile, Category, Skills, Portfolio from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect def index(request): # Home home = Home.objects.latest('updated') # About about = About.objects.latest('updated') profiles = Profile.objects.filter(about=about) # Skills categories = Category.objects.all() skills = Skills.objects.all() # Portfolio portfolios = Portfolio.objects.all() if request.method == 'POST': form = ContactForm() else: form = ContactForm(request.POST or None) if form.is_valid(): form.save() return redirect('success') context = { 'home': home, 'about': about, 'profiles': profiles, 'categories': categories, 'portfolios': portfolios, 'form': form, 'skills': skills, } return render(request, 'index.html', context) So here is the problem I would like to keep the attribute on the form.py to the variable? Why because it then keeps the CSS structure with it. So do you know how to have the form Post save to the database? -
Why Django signals not sending to create user profile for social signup or login?
I have custom signup model. I am using signals to create user profile when anyone signup or creating account. But my signals not sending when anyone creating account using their social media account such as facebook, twitter etc. I want to create user profile through signals for social signup or login. I am using social-auth-app-django #UserProfile class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") mobile = models.IntegerField(blank=True,null=True) country = models.CharField(max_length=200,blank=True,null=True) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) #subscriber_signals @receiver(post_save, sender=Subscriber) def user_is_created_or_save(sender,instance,created,**kwargs): user = instance.user password = instance.user.password username= instance.user.username first_name = instance.first_name last_name = instance.last_name email = instance.email user_id = instance.user.id is_subscriber = instance.user.is_subscriber um = UserManagement(id=user_id,email=email,username=username,password=password,first_name=first_name,last_name=last_name,is_subscriber=is_subscriber ) um.save() if created: UserProfile.objects.create(user=user) -
Lazy load pagination in django
I have a function that makes 100 queries to an API, however there is a rate limit of something like 15 requests per second. Therefore, I tried using Django EL(Endless) Pagination in order to get something like Twitter style pagination. The effect I wanted was something in which by default it would only show the first ten items, and once the user scrolls to end, it would load the next ten items. However, it seems that pagination only paginates the template, not the view in which the data is requested. It seems that what the pagination is doing is: Call the function to send 100 queries. Display first 10 elements. When user reach the end, call again the function to send 100 queries. Show another 10 elements. Basically, each time the next page is requested, the view function is called. The view function is something like this: def user_info(request, user_account, template="entry_list.html"): # Function that makes the 100 requests entry_list = helpers.get_summary_list(user_account) context = { "entry_list": entry_list, } if request.is_ajax(): template = "entry_list_page.html" return render(request, template, context) Then in the template: {% load el_pagination_tags %} {% lazy_paginate entries %} {% for entry in entries %} {# your code to show the … -
gjongo gjango admin list field
models.py: from djongo import models class Passenger(models.Model): _id = models.ObjectIdField() first_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) class Bus(models.Model): _id = models.ObjectIdField() bus_driver = models.CharField(max_length=100, blank=False, null=False, unique=True) passengers = models.ArrayField(model_container=Passenger) admin.py: from django.contrib import admin # Register your models here. from .models import Bus @admin.register(Bus) class BusAdmin(admin.ModelAdmin): list_display = ('bus_driver',) I would like in Django Admin to be able to add passengers to the bus. The bus can be without passengers too. How can I do it? Currently, there is something wrong with the code that does not allow to do it: zero passengers, i.e. zero list is not allowed. Plus the add new passenger button does not exist, i.e. I can not add several passengers. -
I want to convert data from json file to another file
I want to convert data from json file to another file, so I had to use ('for in') because there is a lot of data with different value. The problem is that it displays the same value in different data def pms(request): n= open('./templates/pmsResponse.json') file =json.load(n) guest = dict () newguests = list () newroom=list() for x in file : guests=x['Guests'] for g in guests : guest["guest_id_pms"] = g['Number'] newguests.append ( guest ) data={ "guests" : newguests, } return JsonResponse(data) -
Django-contrib-comments fails to get authenticated user
I'm currently implementing django-contrib-comments and the post_comment view can't figure out the current authenticated user (to say it in my rookie words). I attached the comment form to my object poller which itself has a foreign key to my user model Account. AttributeError at /comments/post/ 'Account' object has no attribute 'get_full_name' class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) [..] The post_comment view fails here: def post_comment(request, next=None, using=None): data = request.POST.copy() if request.user.is_authenticated: if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.get_username() # fails here My custom user model inherited from AbstractBaseUser: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) [..] -
Django+Vue+webpack configuration
I'm trying to setup a project but somehow I cannot properly connecting my backend to my frontend dev.py : from .settings import * DEBUG = True ALLOWED_HOSTS = ["*"] MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware") INSTALLED_APPS.append("debug_toolbar") INTERNAL_IPS = ("127.0.0.1", "localhost") WEBPACK_LOADER = { "DEFAULT": { "BUNDLE_DIR_NAME": "", "STATS_FILE": os.path.join(BASE_DIR, "frontend/webpack-stats.json"), # 'STATS_FILE': BASE_DIR.joinpath('frontend', 'webpack-stats.json'), } } STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = "/dmedia/" MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") VUE_ROOT = os.path.join(BASE_DIR, "frontend\\static\\") CUT FROM settings.py : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) STATICFILES_ROOT = os.path.join(BASE_DIR, "staticfiles") # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "ObjectMgr", "webpack_loader", ] ROOT_URLCONF = "ObjectMgr.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "templates"), ], "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", ], }, }, ] WSGI_APPLICATION = "ObjectMgr.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "/static/" index.html : {% load render_bundle from webpack_loader %} {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frontend</title> <meta http-equiv=X-UA-Compatible content="IE=edge"> <meta name=viewport content="width=device-width,initial-scale=1"> … -
passing django database entries into messages within the line messenger api (linebot)
i would like the linebot to send all classes stored in the database, on a given a particular day, depending on the user input, through line messenger. e.g user types "hello" linebot responds with "hello" user types "monday" linebot sends monday's class schedule user types "studentlist(tutorname)" linebot sends all students in the list of that tutor so far, i can receive the echo, the linebot is storing the user data corectly in the model database too. the bot can differentiate between message type. (i.e "text", "image" etc) everything i seem to do stops the main messages being sent. How would be best to write the loops required to get my desired reponse? I was hoping to using the information in this way and pass that somehow into the message data = Lessons.objects.all().filter(headed_by__name="Tutor Name").filter(day__icontains="Monday") below is not working, and stops the rest of the elif functions from working. elif event.message.type=="text" | event.message.text=="Monday" : message.append(TextSendMessage(text='Monday? Coming right up')) line_bot_api.reply_message(event.reply_token,message) and this is the code that i am using to receive the messages currently @csrf_exempt def callback(request): if request.method == "POST": message=[] signature=request.META['HTTP_X_LINE_SIGNATURE'] body=request.body.decode('utf-8') message.append(TextSendMessage(text=str(body))) try: events = parser.parse(body,signature) except InvalidSignatureError: return HttpResponseForbidden() except LineBotApiError: return HttpResponseBadRequest() for event in events: if isinstance(event, … -
Postgresql database server keeps shutting down randomly
During last two days, it's been five or six times which my postgres database server was shut down unexpectedly, often when server traffic was at the lowest level. So i checked postgresql log: 2021-09-18 10:17:36.099 GMT [22856] LOG: received smart shutdown request 2021-09-18 10:17:36.111 GMT [22856] LOG: background worker "logical replication launcher" (PID 22863) exited with exit code 1 grep: Trailing backslash kill: (28): Operation not permitted 2021-09-18 10:17:39.601 GMT [55614] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.603 GMT [55622] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.686 GMT [55635] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.688 GMT [55636] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.718 GMT [55642] XXX@XXX FATAL: the database system is shutting down 2021-09-18 10:17:39.720 GMT [55643] XXX@XXX FATAL: the database system is shutting down kill: (55736): No such process kill: (55741): No such process (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Failed to stop c3pool_miner.service: Interactive authentication required. See system logs and 'systemctl status c3pool_miner.service' for details. pkill: killing pid 654 failed: Operation not permitted pkill: killing pid 717 … -
no such column: users_profile.user_id - Django
I have created an app in my Django project called users, and I have created a model called Profile. After registering the app in the admin panel also install the app in the setting.py and created the view for it. When I click on the profile inside the 8000/admin/user/Profile I get the following error: OperationalError at /admin/users/profile/ no such column: users_profile.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/users/profile/ Django Version: 3.2.6 Exception Type: OperationalError Exception Value: no such column: users_profile.user_id Exception Location: C:\Users\Serage\Desktop\devsearch\env\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Serage\Desktop\devsearch\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\Users\Serage\Desktop\devsearch', 'c:\users\serage\appdata\local\programs\python\python39\python39.zip', 'c:\users\serage\appdata\local\programs\python\python39\DLLs', 'c:\users\serage\appdata\local\programs\python\python39\lib', 'c:\users\serage\appdata\local\programs\python\python39', 'C:\Users\Serage\Desktop\devsearch\env', 'C:\Users\Serage\Desktop\devsearch\env\lib\site-packages'] Server time: Sat, 18 Sep 2021 13:59:55 +0000 My profile code is: *from django.db import models from django.contrib.auth.models import User import uuid Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True)> bio = models.TextField(blank=True, null=True) profile_image = models.ImageField(null = True, blank = True, upload_to='profiles/', default="profiles/user-default.png") social_github = models.CharField(max_length=500, null=True, blank=True) social_github = models.CharField(max_length=500, null=True, blank=True) social_linkedIn = models.CharField(max_length=500, null=True, blank=True) social_youtube = models.CharField(max_length=500, null=True, blank=True) social_website = models.CharField(max_length=500, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def … -
Exception Value: no such column: noticia_tb.id
I made a scraping application using scrapy, to scrape the news from a page, I put it to create a sqlite database, and then I made a django api to consume this database and make a link available in json, however when I upload the application from the following error: OperationalError at /news/ no such column: noticia_tb.id So I opened the database file and noticed that the ID was not generated, how do I generate this ID or use it without? follow my moldels.py class NoticiaTb(models.Model): title = models.TextField(blank=True, null=True) subtitulo = models.TextField(blank=True, null=True) url = models.TextField(blank=True, null=True) data = models.TextField(blank=True, null=True) image_url = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'noticia_tb' follow the scrapy project pipeline class ApinoticiaPipeline(object): def __init__(self): self.create_connection() self.create_table() def create_connection(self): self.conn = sqlite3.connect("myapinoticia.db") self.curr = self.conn.cursor() def create_table(self): self.curr.execute("""DROP TABLE IF EXISTS noticia_tb""") self.conn.execute("""create table noticia_tb( title text, subtitulo text, url text, data text, image_url text )""") def process_item(self, item, spider): self.store_db(item) return item def store_db(self, item): self.curr.execute("""insert into noticia_tb values (?,?,?,?,?)""",(str(item['title'][0]),str(item['subtitulo'][0]),str(item['url'][0]),str(item['data'][0]),str(item['image_url'][0]))) self.conn.commit() -
djongo Company with ID “None” doesn’t exist. Perhaps it was deleted?
I couldn't find a solution among similar questions. Using mongosh, the Company objects do exist, but in the admin, they show as object(None) and therefore cannot be edited due to error "Company with ID “None” doesn’t exist. Perhaps it was deleted?". I guess it is about the "id" detection, but can not fix it myself. Question: how to fix the code to make the Company object to be shown correctly, not as None. myproject> db.companies_company.find() [ { _id: ObjectId("6145dd9a8bc9a685b2ae2375"), name: 'company1' }, { _id: ObjectId("6145ddaa8bc9a685b2ae2377"), name: 'company2' } ] models.py: from django.db import models # Create your models here. class Company(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) admin.py: from django.contrib import admin # Register your models here. from .models import Company @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): pass -
How to download a file from my media root folder to my phone or computer
Anytime i click on the download link of the mp3 files or images, instead of them starting to download but they just start to preview on the browser. I want when i click on the url "http://localhost:8000/s/download_rdr/1/" and the file "http://localhost:8000/s/media/music.mp3" starts downloading but all it does is to start playing in the browser. My views.py class DownloadRdr(TemplateView): def get(self, request, pk, *args, **kwargs): item = Item.objects.get(id=pk) #Return an mp3 return redirect('http://localhost:8000/s/media/music.mp3')