Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get object numbers in django models
I am a new user in Django and I am trying to print the total number of objects in a model but this code below prints the query set with its title. Here's my function def showthis(request): count= Item.objects.count() print (count) I need to get the total number of objects in Model Item -
Django Sockets: ConnectionRefusedError at /robot/1, [Errno 111] Connection refused
I am trying to connect to another device on my same network, a robot running on a raspberry pi but when I try to connect I get the error. I am not sure what is causing it because they are on the same IP 127.0.0.1. If anybody has any ideas on what is causing it the help would be great. My View: HEADER = 64 PORT = 6060 SERVER = '127.0.0.1' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' def form_valid(self, form): self.object = form.save() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) client.send(send_length) client.send(message) send("HELLO") print(self.object) send(DISCONNECT_MESSAGE) return render(self.request, "theblog/bloghome.html") My Raspi Code: HEADER = 64 PORT = 6060 SERVER = '127.0.0.1' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) return msg conn.close() def start(): server.listen() print(f"[LISTENING] Server … -
Models and serializers Django
I'm working on the back end part of the project and I'm facing an issue that I cant through Postman send an API request for POST, GET or PUT data in model_seconds field. At this point, no required any front end part, only back end. thanks Models: class ModelBase(models.Model): email = models.EmailField(blank=True) phone = models.CharField(max_length=32, blank=True) first_name = models.CharField( max_length=64, blank=True, verbose_name=_(u'First name') ) last_name = models.CharField( max_length=64, blank=True, verbose_name=_(u'Last name') ) name = models.CharField(max_length=128, blank=True, editable=False) ] birth_date = models.DateField(null=True, blank=True) personal_code = models.CharField( max_length=32, blank=True, verbose_name=_(u'Personal code') ) hobbies = models.CharField( max_length=128, blank=True, verbose_name=_(u'Hobby') ) legal_name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Legal name') ) registration_nr = models.CharField( max_length=32, blank=True, verbose_name=_(u'Registration Nr') ) legal_address = models.CharField( max_length=128, blank=True, verbose_name=_(u'Address') ) country = models.ForeignKey( Country, blank=True, null=True, related_name='+', verbose_name=_('Country'), on_delete=models.CASCADE ) state = models.CharField( max_length=128, blank=True, verbose_name=_(u'State/province') ) city = models.CharField( max_length=128, blank=True, verbose_name=_(u'City') ) zip_code = models.CharField( max_length=32, blank=True, verbose_name=_(u'ZIP code') ) class Meta: abstract = True def __str__(self): if self.hobbies: return self.hobbies elif self.legal_name: return self.legal_name elif self.name: return self.name elif self.email: return self.email else: return self.phone class Models(ModelBase, UUIDIdMixin): friend = models.ForeignKey(Merchant, related_name='models', on_delete=models.CASCADE) account = models.ForeignKey(Account, related_name='models', on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='models', on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) class … -
How to increase read and write time after using DJango storages package?
I have a web app running on DJango which currently uses the DJango Admin interface as front end. Till date I had been using the default file system of the server for storing my media files, recently I ran out of space and chose to go for a third party storage service like AWS S3. But for all the images uploaded to my server I need to create a Dropbox link so I planned to use the DJango Storages package and set Dropbox as the default storage backend. It work fine, but the problem is that the reading and writing is very slow. It takes a lot of time to upload the images and to view the same. The loading time is very very slow. But the moment I change my storage backend it fastens up again. Is it due to using the DJango storages package? Is there a work around for the same? Yes I’m aware that I can use DJango queued storage for uploading but that’ll fix uploading speed and not the reading time. -
How do I create a function to update many entries at once in Django SQLite database?
I have a functioning application, but would like to streamline aspects. I have create, update and view pages for a table of about 20 instances of Post2. I would like to assign a function to a button that would update all player1, player2 and player3 to "Empty". Even better would be to set it to a weekly timer. Any help would be very much appreciated, nothing I've tried has worked. The following is my models.py- class Post2(models.Model): time=models.CharField(max_length=50) player1=models.CharField(max_length=50, default="Player 1") player2=models.CharField(max_length=50, default="Player 2") player3=models.CharField(max_length=50, default="Player 3") def __str__(self): return self.time This is my views.py- def teetimes(request): posts=Post2.objects.all() return render(request, 'memtees2/teetimes.html', {'posts':posts}) def add(request): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post2.objects.create(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'New Time has been added') return render(request,'memtees2/add.html') def update(request,id): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post2.objects.filter(id=id).update(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'Information has been updated, return to Tee-Times to view ') post=Post2.objects.get(id=id) return render(request,'memtees2/update.html',{'post':post}) -
How to link 3rd party model and view with own model in Django
I successfully implemented django-contrib-comments to my project and starting to adjust it step by step to make it 100% suitable to my project. Now I have the following issue which I cannot solve: I have a model Poller which offers two possible votes for any user stored in the model Vote. Now if a user comments on a poller I would like to return his individual vote for this specific poller to the rendered comment in the template. Since I don't wanna touch the 3rd partie's architecture by any means, I would prefer to get the required queryset in my view. Comment model of django-contrib-comments package class CommentAbstractModel(BaseCommentAbstractModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), [..] My Poller, Vote and Account/User models class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) [..] class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) [..] class Account(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) [..] -
django social does not return user after login
I am trying to setup social login with GitHub using the Django social package. I am able to complete the begin by visiting http://127.0.0.1:8000/api/v1/auth/login/github/ and the I get redirected to the complete page as expected. The login is appears to be successful as it sends me to the SOCIAL_AUTH_LOGIN_REDIRECT_URL I have specified in my settings. Now the view has a IsAuthenticated permission requirement and throws an error that credentials are not provided. I expected that after the login completes that the logged in user is added to the request but that does not seem to be the case as request.user is an Anonymous user. How can I get the logged in user after I am redirected from the oauth provider page successfully. My end goal is to return the access token to my spa from end and query the convert-token endpoint to get a jwt which I can then use for all my routes. Any example on how I can achieve this would be greatly appreciated. view # @permission_classes([IsAuthenticated]) class MyProfileView(APIView): def get(self, request): # profile = UserProfile.objects.get(user=request.user.id) # serializer = UserProfileSerializer(profile) # return Response(serializer.data) social = request.user.social_auth.get(provider='provider name') return social.extra_data['access_token'] -
Finding total score from specific user's maximum score in django orm
I have a function that gets two parameters(contest_id,user_id), how could i get maximum score of each problem in given contest for the given user and then sum up all those max scores? each problem can have zero or many submitted scores. for example : (problem_id,submitted_score) --> (1, 80), (1, 100), (2, 150), (2, 200), (3, 220), (3, 300) expected result for this example should be 600, 100 + 200 + 300. Models: class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants') class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey(User, on_delete=models.DO_NOTHING) score = models.PositiveIntegerField(default=100) class Submission(models.Model): submitted_time = models.DateTimeField() participant = models.ForeignKey(User, related_name="submissions", on_delete=models.DO_NOTHING) problem = models.ForeignKey(Problem, related_name="submissions", on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) -
how to pass query parameters from DRF serializer
when we pass query params through a request to DRF, are query params passed through serializer ? or is there any way to pass them from serializer ? -
My Django custom signup form does not save new users in the Database even after i have tried everything i can
**So am trying to build a signup page for users on my app but, after i built it, when a user sings up, they are not registered in the database. I used the Django form and also used html and CSS for styling but my custom form does not register user on the database this is the views.py section passing the form after it has been created in the forms.py** def customerRegister(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.save() group = Group.objects.get(name = 'Customer') user.groups.add(group) messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request,'kumba/register.html', context) *forms.py this is my custom form with specific information needed from the user* class CreateUserForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'required' : "", 'name': "username", 'id' : 'username', 'type': 'text', 'placeholder' : 'Enter Username.....', 'class' : 'form-input' }) self.fields['email'].widget.attrs.update({ 'required' : "", 'name': "email", 'id' : 'email', 'type': 'email', 'placeholder' : 'Enter Email.....', 'class' : 'form-input' }) self.fields['password1'].widget.attrs.update({ 'required' : "", 'name': "password1", 'id' : 'password1', 'type': 'text', 'placeholder' : 'Enter password.....', 'class' : 'form-input' }) self.fields['password2'].widget.attrs.update({ 'required' : "", 'name': "password2", 'id' : 'password2', 'type': … -
Django - get file path from client pc
I work on some gov project and got task to make an opportunity to track if operator(user) uploaded file using scanner or USB drive. I find it's possible if I could get file path before uploading it to server. Is it real in Django? -
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/ …