Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ran the server got class and module error. please any one help on issue
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Djangoproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() -
how to utilize same list view for search and category queryset in django
I am trying to build functionality in my Django app in which we can get data with two methods: Using Search Selecting a Category Since both of them require to get data from the dataset, I am wondering if there is a way I can utilize same ListView (not a CBV) to output data. urls.py path('datalist/<slug:category_slug>/' views.problemlist, name="problem_list_category"), path('datalist/search/' views.problemlistbysearch, name="problem_list_search"), views.py def problemlist(request, category_slug): qs = DataModel.objects.get(category_slug=category_slug) return render(request,'list.html',{'qs':qs} ) def problemlistbysearch(request): if request.method == 'GET': querry = request.GET.get('name') objlst = DataModel.objects.all() qs = objlst.filter(title__icontains=querry) return render(request, 'seach.html', {'qs':qs}) -
Django: "Product matching query does not exist."?
I'm new to programming following along a Udemy Python/Django e-commerce tutorial while creating the cart_update function. I ran into this error below. I used ForeignKey for user in my models. Can someone explain what I'm doing wrong; and how should I be thinking about this kinda of error going forward? thanks in advance SO communinty DoesNotExist at /cart/update/ Product matching query does not exist. /Users/duce/Sites/RENUecommerce/src/carts/views.py, line 20, in cart_update product_obj = Product.objects.get(id=product_id) … views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from inventory.models import Product from .models import Cart def cart_update(request): product_id = 1 product_obj = Product.objects.get(id=product_id) #product_obj = get_object_or_404(Product, id=product_id) cart_obj, new_obj = Cart.objects.new_or_get(request) cart_obj.products.add(product_obj) return redirect('cart:update') models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from inventory.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get('cart_id', None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user … -
Django: save(commit=False) on formset CBV is triggering customized model save() actions
I'm using CBV CreateView to display a couple of pages with formsets to the user. When the model behind a given formset/CreateView is a common one (it will became clearer later), everything works fine using the following logic on the view: class Create(CreateView): ... def form_valid(self, formset): instances = formset.save(commit=False) for instance in instances: instance.user = self.request.user instance.save() return super(Create, self).form_valid(formset) However, on one of the models, I had to add extra actions to the model save() method. Namely, I need to create child objects when the parents are saved. Something like: class Parent(models.Model): ... def save(self, *args, **kwargs): super().save(*args, **kwargs) self.child_set.create(...., *args, **kwargs) In this particular case, the child object is being created twice and I believe that the formset.save(commit=False) is the culprit. I tried replacing the child_set.create() for child = Child(...parameters, parent=self) child.save(*args, **kwargs) But it yields the same result. How can I prevent that? -
ValueError: Field 'id' expected a number but got 'None'
Im using django update class wiew, im also using form_valid here, whe submit gives me the following error: "ValueError: Field 'id' expected a number but got 'None'".here is the code. thanks in advance !! [class update view][1] [1]: https://i.stack.imgur.com/c6GP2.png -
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, …