Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Can I check the message position in a buffered channel?

Let's say I dispatch works to workers via channels, and the dispatcher needs to keep notifying the sender how many jobs are scheduled before job X at each time. Is it possible to know the message position (e.g. by examining an ID) with buffered channels or does this require another type of queue?

Using in Django exactly same python database code already working in PHP

I have a bunch of files containing python functions, used in a web-serving apache2, they are all called from PHP as shell scripts just with "python3 'file' 'args'" (without the -m, that is) and return data to PHP via JSON strings, are all debugged since a long time, and work well.

They are all in a single directory, and most of them import other files simply using

   from file_with_lower_level_functions import gimme_this_table

many imported functions in turn import other ones, and some import chains may be 4 or 5 links long.

Trying to import this into Django is nightmarish. All of my "froms" are replied to by "manage.py check" with "module not found". I did obtain partial success by changing the top level froms above to

   from .file_with_lower_level_function import gimme_this_table 

adding the leading dot. But first, changing the "from"s like that in every single module would make them unworkable in the old situation, and I do not want to do this change.

And, next, this gives problems with 2nd links, when one of my functions imports another one: applying the same cure to the 2nd like doesn't work: "Huh uh! module not found"

Is this kind of approach even possible with Django? Is there a common form which would give me a code usable in BOTH django and PHP?

I thought of playing to Django the same trick I did to PHP, that, is calling my code as a shell script, and that would probably work; but since Django is already python, that does not appeal much to me: I would sweat a job and learn nothing.

I tried calling from django views my old functions, and I was expecting that to work without (many) problems.

How the message is output to the client in the chat server example from the Go programming language book?

Below is an example of a chat server from Chapter 8 of Alan Donovan and Brian Kernighan's book Go Programming Language.

// Chat is a server that lets clients chat with each other.
package main

import (
    "bufio"
    "fmt"
    "log"
    "net"
)

//!+broadcaster
type client chan<- string // an outgoing message channel

var (
    entering = make(chan client)
    leaving  = make(chan client)
    messages = make(chan string) // all incoming client messages
)

func broadcaster() {
    clients := make(map[client]bool) // all connected clients
    for {
        select {
        case msg := <-messages:
            // Broadcast incoming message to all
            // clients' outgoing message channels.
            for cli := range clients {
                fmt.Println(cli)
                cli <- msg
            }

        case cli := <-entering:
            clients[cli] = true

        case cli := <-leaving:
            delete(clients, cli)
            close(cli)
        }
    }
}

//!-broadcaster

//!+handleConn
func handleConn(conn net.Conn) {
    ch := make(chan string) // outgoing client messages
    go clientWriter(conn, ch)

    who := conn.RemoteAddr().String()
    ch <- "You are " + who
    messages <- who + " has arrived"
    entering <- ch

    input := bufio.NewScanner(conn)
    for input.Scan() {
        messages <- who + ": " + input.Text()
    }
    // NOTE: ignoring potential errors from input.Err()

    leaving <- ch
    messages <- who + " has left"
    conn.Close()
}

func clientWriter(conn net.Conn, ch <-chan string) {
    for msg := range ch {
        fmt.Fprintln(conn, msg) // NOTE: ignoring network errors
    }
}

//!-handleConn

//!+main
func main() {
    listener, err := net.Listen("tcp", "localhost:8000")
    if err != nil {
        log.Fatal(err)
    }

    go broadcaster()
    for {
        conn, err := listener.Accept()
        if err != nil {
            log.Print(err)
            continue
        }
        go handleConn(conn)
    }
}

//!-main

One point is not obvious to me at all. In the broacaster function we have map clients, where the key is the outgoing message channel for each client. Sending a message to the chat room:

for cli := range clients {
    fmt.Println(cli)
    cli <- msg
}

we send a string to this outgoing message channel.

Where does the message output from this outgoing message channel take place? Where is this channel read and output?

In the clientWriter function only some ch := make(chan string) is passed, but as I see it has nothing to do with the outgoing message channel.

I want to get an understanding of how the message is passed to the terminal output.

Why won't my home page redirect to a detail view (Django)

So the context is I'm following a tutorial on codemy.com. Somewhere before Django 5.0 I lost my "magic", the tutorial was written for 3.8 or 4.X maybe. I am showing a function based view although I have tried the class base view as suggested on the codemy youtube. The reason I chose function view is it was easier for me to debug.

views.py

 from django.shortcuts import render
 from django.views.generic import ListView #DetailView
 from django.http import HttpResponse
 from .models import Post


 class Home(ListView):
     model = Post
     template_name = "home.html"


 def articleDetail(request, pk):
     try:
         obj = Post.objects.get(pk=pk)
         return render(request, "article_detail.html", {object, obj})
     except Post.DoesNotExist:
         print("Object number: " + str(pk) + " not found")
         return HttpResponse("Object number: " + str(pk) + " not found")

the model

 from django.db import models
 from django.contrib.auth.models import User


 class Post(models.Model):
     title = models.CharField(max_length=255)
     author = models.ForeignKey(User, on_delete=models.CASCADE)
     body = models.TextField()

     def __str__(self):
         return str(self.title) + ' by: ' + str(self.author)

the urls file

 from django.urls import path,include
 from .views import Home, articleDetail

 urlpatterns = [
     path('', Home.as_view(), name="home"),
     path('article/<int:pk>', articleDetail,name="article-detail"),
         ]

the template for home, works fine until redirect

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>Landing!!!</title>
     <h1> Home Pageeeeee</h1>
 </head>
 <body>
 <ul>
     <h2>Articles</h2>
     {% for article in object_list  %}
     <li>
         <a href="{$ url 'article-detail' article.pk %}">{{article.title}}</a>
         <br/>
         By: {{article.author}}
         <p>
             {{article.body}}
         </p>
     </li>
     {% endfor %}
 </ul>
 </body>
 </html>

I think my error is either how I'm passing the primary key to look up the object or how I'm asking the URL file to locate the document

Django crispy-forms TemplateDoesNotExist

I am new in Django, so I was trying structures in the book "Django for Beginners by William S Wincent" about how to attach crispy forms to my signup page!

However, in the middle of my progress in the topic, I faced to TemplateDoesNotExist exception! Error: Error description

Here is where the error raises: Error description

And here is my settings.py configuration:

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
    "accounts",
    "pages",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"
...

django = 4.2.3 django-crispy-forms = 2.0

I've tried to create a Sign Up Page, configuring its views and urls properly to host crispy_forms in my project.

Also crispy_forms(Version 2.0) is installed. Packages installed in my virtual environment

recursively change the value of field in mongodb document

I need to change a value of a field in a mongoDB document recursively.

More or less, this is just a find and replace for a value of a field if the field name and the (old) value matches.

Example Document:

{
  "topLevel": {
    "level1": [
      {
        "itemKey": "N-99999",
        "level2": [
          {
            "itemKey": "N-99999",
            "level3": [
              {
                "itemKey": "N-99999"
              },
              {
                "itemKey": "a-4157-637"
              },
              {
                "itemKey": "t-3213-569"
              },
              {
                "itemKey": "s-3984-763"
              },
              {
                "itemKey": "n-5996-963"
              }
            ]
          }
        ]
      }
    ]
  }
}

What I tried, but doesn't work:

func replaceItemKey(ctx context.Context, coll *mongo.Collection, old, new string) (*mongo.UpdateResult, error) {
    filter := bson.D{
        {Key: "toplevel.level1.itemKey", Value: old},
        {Key: "toplevel.level1.level2.itemKey", Value: old},
        {Key: "toplevel.level1.level2.level3.itemKey", Value: old},
    }
 
    update := bson.D{
        {Key: "$set", Value: bson.D{{Key: "toplevel.$[l1]level1.itemKey", Value: new}}},
        {Key: "$set", Value: bson.D{{Key: "toplevel.level1.$[].level2.$[l2].itemKey", Value: new}}},
        {Key: "$set", Value: bson.D{{Key: "toplevel.level1.$[].level2.$[].level3.$[l3].itemKey", Value: new}}},
    }
    
    opts := options.Update().SetArrayFilters(
        options.ArrayFilters{
            Filters: []interface{}{
                bson.D{{Key: "l1.itemKey", Value: bson.D{{Key: "$eq", Value: old}}}},
                bson.D{{Key: "l2.itemKey", Value: bson.D{{Key: "$eq", Value: old}}}},
                bson.D{{Key: "l3.itemKey", Value: bson.D{{Key: "$eq", Value: old}}}},
            },
        },
    )
    
    return coll.UpdateMany(ctx, filter, update, opts)
}



I know this is not recursively at all. It just tries to change the value in 3 levels. Recursively would be better.

I'd prefer to change the value in one statement. Doing it in a statement per level works fine. But I'm not aware on the performance impact if I have to change thousends of documents.

Thanks a lot.

The same uuid is generated for different objects in Django

When I run a server on localhost I am able to add new objects in my postgre database through the Django admin panel, but only one for every table. When I try to add a second new object, it assigns the same UUID that has already been used. There is an example of model with UUID as primary key:

models.py

from django.db import models
from authuser.models import User
from django.utils import timezone
import uuid

class Thread(models.Model):

    idthread = models.UUIDField(default=uuid.uuid4(), primary_key=True, unique=True)
    date_created = models.DateTimeField(default=timezone.now)
    userid = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    name = models.CharField()

    def __str__(self):
        return self.name

Only after restarting the server will assign a new unique UUID to objects that I would like to add.

Cannot connect to running Docker container from locally run Golang

I have a container running on my local with

docker run \
    --publish 8081:8081 \
    --publish 10250-10255:10250-10255 \
    --interactive \
    --tty \
    mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest   

I am able to run in Chrome just fine, https://localhost:8081/etc/etc.

However I must now write a Go program to make an API call to the running container. I get:

Post "https://172.17.0.2:8081/dbs": dial tcp 172.17.0.2:8081: connect: no route to host

Am I missing something here, do I need to further expose the ports?

package main

import (
    "context"
    "log"
    "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
    const (
        cosmosDbEndpoint = "https://localhost:8081/"
        cosmosDbKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
        dbname = "db5"
    )
    cred, err := azcosmos.NewKeyCredential(cosmosDbKey)
    handle(err)
    client, err := azcosmos.NewClientWithKey(cosmosDbEndpoint, cred, nil)
    handle(err)
    databaseProperties := azcosmos.DatabaseProperties{ID: dbname}
    _, err = client.CreateDatabase(context.Background(), databaseProperties, nil)
    handle(err)
}

Tried running

set http_proxy=
set https_proxy=

Note that you have to import a cert as in curl -k https://localhost:8081/_explorer/emulator.pem > ~/emulatorcert.crt then for example in Mac go to the keychain, add the cert, and trust it

GO! LEGO DREAMZzz Stable of Dream Creatures Set $39 Shipped (Reg. $80) – Amazon Lightning Deal

Score 50% off the LEGO DREAMZzz Stable building set!

lego dreamzzz stable set on table

Hurry over to Amazon where they are offering the LEGO DREAMZzz Stable of Dream Creatures Building Set for just $39.20 shipped (regularly $79.99)! Note that this is a lightning deal so you’ll want to be quick to snag yours before they’re all gone!

LEGO DREAMZzz Stable of Dream Creatures Building Set
Just $39.20 shipped (regularly $79.99)!

two kids playing with lego dreamzzz stable set

This 681-piece set allows kiddos to build this own stable with a functioning windmill, opening windows and gates, and more! It includes 4 minifigures and kids can choose to decorate the deer toy as a flying pegasus or a forest guardian. Plus, it also has fun story-led building instructions available on the LEGO Builder app.

Thinking it over? Check out this retailed review…

I’ve been doing this set with my daughter and she absolutely loves it. We’ve not actually finished it yet but so far it’s been a huge hit!. Think the fact that it’s a wee bit different and a bit more quirky than any of the other Lego we’ve done before, makes it even better! She cannot wait until we are onto building the deer!!

As always with Lego it comes with clear instructions, and you can also download the app which has all the instructions for the Lego sets as well. The packs inside are all numbered for each individual stage (and comes with several spares also) The set itself really is beautiful with such gorgeous vibrant colours and detail. So yeah, so far we are very impressed.

We’ve got loads more LEGO deals over here!

(Thanks, Lisa!)

golang: how to gracefully shutdown/interupt for loop in k8s container

I am new to golang. I have a go program which is a for loop, like

for {
  f()
}

f may take seconds to 1 min. the for loop runs for ever, and can be killed by KILL signal.

in k8s container, we may kill the program/process very often. So i hope the KILL signal only interupt the for loop after function f finished and not started.

How to do this? Any example?

Thanks

How do I get CORS working with golang chi server?

I am trying to get cross origin request working against a golang chi server (https://github.com/go-chi/chi). The preflight request made by the browser isn't getting the expected headers (screen shot below). Here is a script that sets up a simple go server and express server

go mod init
cat > main.go <<EOF
package main

import (
    "net/http"
    "github.com/go-chi/chi"
    "github.com/go-chi/cors"
)

func main() {
    r := chi.NewRouter()

    cors := cors.New(cors.Options{
    AllowedOrigins:   []string{"*"},
    // AllowOriginFunc:  func(r *http.Request, origin string) bool { return true },
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    ExposedHeaders:   []string{"Link"},
    AllowCredentials: true,
    MaxAge:           300, // Maximum value not ignored by any of major browsers
    })
    r.Use(cors.Handler)    
    r.Post("/blogs", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("{\"Ack\": \"OK\"}"))
    })
    http.ListenAndServe(":8888", r)
}
EOF
go mod tidy
go build -o test-server
# Setup an express web server
npm init -y
npm install express --save
cat > server.js <<EOF
var express = require('express');
var app = express();

app.use('/', express.static(__dirname));
app.listen(3000, function() { console.log('listening')});
EOF
cat > index.html <<EOF
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script>
    document.addEventListener("DOMContentLoaded", function (event) {
        var payload = { blog: "example" }
        fetch('http://localhost:8888/blogs', {
            method: 'post',
            body: JSON.stringify(payload),
            headers: {
                "Content-Type": "application/json",
                "X-PINGOTHER": "pingpong"
            }
        })
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                console.log(data);
            });
    });
</script>

<body>
</body>

</html>
EOF

Run the above script in a directory and execute 'npm start' followed by './test-server' from another tab. Navigate to 'http://localhost:3000/' in Chrome. Open Chrome developer tool to view the error

See the screen shot

Unauthorized (401) while i sent a Post request to the server

when i try to add a post to my server i get 401 Unauthorized i sent my jwt in postman with Bearer jwt but nothing change . i think the probleme in the api where exactly i don't have any idea

i use django as backend and react as frontend those are all my code

urls.py :

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView


urlpatterns = [
    #path('admin/', admin.site.urls),
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),

    path('', include('crm.urls')),
]

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]

views.py :

from django.shortcuts import render ,redirect ,get_object_or_404          
from rest_framework.parsers import MultiPartParser, FormParser
from .serializers import PostSerializer
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from .forms import CreateUserForm, LoginForm
from rest_framework.response import Response
from rest_framework import status

#, UploadForm
from rest_framework.decorators import api_view, action

from django.contrib.auth.decorators import login_required, user_passes_test
from .models import Post, PostImage

# - Authentication models and functions 
from django.contrib.auth.models import auth 
from django.contrib.auth import authenticate, login, logout

def homepage(request):

    return render(request, 'crm/index.html')

def register(request):

    form = CreateUserForm()

    if request.method == "POST":

        form = CreateUserForm(request.POST)

        if form.is_valid():

            form.save()

            return redirect("my-login")

    context = {'registerform':form}

    return render(request, 'crm/register.html', context=context)



def my_login(request):

    form = LoginForm()

    if request.method == 'POST':

        form = LoginForm(request, data=request.POST)
        
        if form.is_valid():

            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(request, username=username,password=password)

            if user is not None :

                auth.login(request, user)

                return redirect("dashboard")

    
    context = {'loginform':form}

    return render(request, 'crm/my-login.html', context=context)

def user_logout(request):
    auth.logout(request)
    
    return redirect("")

#def upload(request):
#   if request.POST:
#      form = UploadForm(request.POST, request.FILES)
#     print(request.FILES)
    #    if form.is_valid():
#       form.save_()
#  return redirect(homepage)
    #return render(request, 'crm/upload.html', {'form' : UploadForm })

def post_view(request):
    posts = Post.objects.all()
    return render(request, 'post.html', {'posts':posts})

def detail_view(request, id):
    post = get_object_or_404(Post, id=id)
    photos = PostImage.objects.filter(post=post)
    return render(request, 'detail.html', {
        'post':post,
        'photos':photos
    })

@api_view(['POST'])
class PostsViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    parser_classes = (MultiPartParser, FormParser)
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)






@login_required(login_url="my-login")
def dashboard(request):

    return render(request, 'crm/dashboard.html')

serializers.py :

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import Post, PostImage



User = get_user_model()

class CustomUserCreateSerializer(UserCreateSerializer):
    age = serializers.IntegerField(required=True)
    role = serializers.ChoiceField(choices=User.Role.choices, required=True)

    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ('id', 'email', 'name', 'password', 'age', 'role')

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
    

class PostImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostImage
        fields = ('id', 'post', 'image')

class PostSerializer(serializers.ModelSerializer):
    images = PostImageSerializer(many=True, read_only=True)
    uploaded_images = serializers.ListField(
        child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False),
        write_only=True)
    
    class Meta:
        model = Post
        fields = ('id', 'title', 'text', 'category', 'author', 'created_at', 'images', "uploaded_images")
    

    def create(self, validated_data):
        uploaded_images = validated_data.pop("uploaded_images")
        post = Post.objects.create(**validated_data)
        for image in uploaded_images:
            newpost_image = PostImage.objects.create(post=post, image=image)
    
        return post 

models.py :

from django.db import models
from django.contrib.auth.models import PermissionsMixin , AbstractBaseUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError

class CustomUserManager(BaseUserManager):
    def create_user(self, email, name, password=None, **extra_fields):
        if not email:
            raise ValueError(_('The Email field must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, name, password, **extra_fields)

class User(AbstractBaseUser):
    email = models.EmailField(_('email address'), unique=True)
    name = models.CharField(_('name'), max_length=150, default='Anonymous', unique=False)
    age = models.PositiveIntegerField(_('age'), blank=True, null=True, validators=[MinValueValidator(18), MaxValueValidator(100)])
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('staff status'), default=False)

    class Role(models.TextChoices):
        ADMIN = "ADMIN", "Admin"
        CLIENT = "CLIENT", "Client"
        ANALYST = "ANALYST", "Analyst"

    role = models.CharField(_('role'), max_length=50, choices=Role.choices, default=Role.CLIENT)
    objects = CustomUserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'age', 'role']

    def save(self, *args, **kwargs):
        if not self.pk:
            if not self.email:
                raise ValidationError("Email address is required.")
            elif User.objects.filter(email=self.email).exists():
                raise ValidationError("Email address must be unique.")
            elif not self.role:
                self.role = self.Role.CLIENT
        super().save(*args, **kwargs)
class ClientManager(CustomUserManager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(role=User.Role.CLIENT)

class Client(User):
    base_role = User.Role.CLIENT
    objects = ClientManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for Client"

class AnalystManager(CustomUserManager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(role=User.Role.ANALYST)

class Analyst(User):
    base_role = User.Role.ANALYST
    objects = AnalystManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for Analysts"




class Post(models.Model):
    CATEGORY_CHOICES = [
        ('math', 'Math'),
        ('philosophy', 'Philosophy'),
        ('science', 'Science'),
        ('political', 'Political'),
        ('other', 'Other'),
    ]
    
    title = models.CharField(max_length=250, blank=False)  # Required field
    text = models.TextField(blank=False)  # Required field
    category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, blank=False)  # Required field
    author = models.CharField(max_length=100)  # You can adjust the max length as needed
    created_at = models.DateTimeField(auto_now_add=True)  # Automatically set to the current date and time when created
    
    def __str__(self):
        return self.title



class PostImage(models.Model):
    post = models.ForeignKey(Post, default=None ,on_delete=models.CASCADE, related_name = "images")
    image = models.ImageField(upload_to='djangoposts/files/images', default="", null=True, blank=True)
    
    def __str__(self):
        return self.post.title

i try to put a jwt token in the Bearer Token in postman but nothing have change the same error still show up

Is there a way to annotate the count for all objects without grouping by another column?

I have code that looks like the following:

filtered_queryset = Object.objects.filter(...misc filters)

match time:
  case "year":
    qs = filtered_queryset.annotate(year=TruncYear("created_at")).values("year")
  case "month":
    qs = filtered_queryset.annotate(month=TruncMonth("created_at")).values("month")
  case "week":
    qs = filtered_queryset.annotate(week=TruncWeek("created_at")).values("week")
  case _:
    qs = filtered_queryset

final_count = qs.annotate(count=Count("id"))

In each case, I am expecting data that looks like the following

# Each case
{
  [{
    "TIME": ...
    "count": ...
   },
   ...
   ]
}
# Default
{
  [{
    "count": ...
   }]
}

I was under the impression that Count() was a terminal expression in django and that the queryset would be evaluated. However, the default case returns a queryset instead of evaluating. What am I missing here that causes it to not evaluate the queryset?

I know that I can just call filtered_queryset.count() instead of trying to do this via annotate, but it causes extra code to check for the default case and adds code smell.

trouble understanding go slices len and cap()

I'm reviewing the tour of Go and I ran into these exercises:

package main

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Slice the slice to give it zero length.
    s = s[:0]
    printSlice(s)

    // Extend its length.
    s = s[:4]
    printSlice(s)

    // Drop its first two values.
    s = s[2:]
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

prints:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

which I was beginning to understand, since the previous slice (s[:4]) had a length of 4, the capacity for the new one would reflect this length.

But then I went a little further:

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)

    b := make([]int, 0, 5)
    printSlice("b", b)

    c := b[:2]
    printSlice("c", c)

    d := c[2:5]
    printSlice("d", d)
}

func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}

prints:

a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]

and now I'm confused because the capacity of s[2:5] is now 3, and not the length of the previous slice.

Can someone please explain this behavior?

GO! LEGO DREAMZzz Stable of Dream Creatures Set $39 Shipped (Reg. $80) – Amazon Lightning Deal

Score 50% off the LEGO DREAMZzz Stable building set!

lego dreamzzz stable set on table

Hurry over to Amazon where they are offering the LEGO DREAMZzz Stable of Dream Creatures Building Set for just $39.20 shipped (regularly $79.99)! Note that this is a lightning deal so you’ll want to be quick to snag yours before they’re all gone!

LEGO DREAMZzz Stable of Dream Creatures Building Set
Just $39.20 shipped (regularly $79.99)!

two kids playing with lego dreamzzz stable set

This 681-piece set allows kiddos to build this own stable with a functioning windmill, opening windows and gates, and more! It includes 4 minifigures and kids can choose to decorate the deer toy as a flying pegasus or a forest guardian. Plus, it also has fun story-led building instructions available on the LEGO Builder app.

Thinking it over? Check out this retailed review…

I’ve been doing this set with my daughter and she absolutely loves it. We’ve not actually finished it yet but so far it’s been a huge hit!. Think the fact that it’s a wee bit different and a bit more quirky than any of the other Lego we’ve done before, makes it even better! She cannot wait until we are onto building the deer!!

As always with Lego it comes with clear instructions, and you can also download the app which has all the instructions for the Lego sets as well. The packs inside are all numbered for each individual stage (and comes with several spares also) The set itself really is beautiful with such gorgeous vibrant colours and detail. So yeah, so far we are very impressed.

We’ve got loads more LEGO deals over here!

(Thanks, Lisa!)

Can someone explain to me what "data = validated_data.copy()" means?

I wonder why the create method does not process the data directly but has to copy it into data and then process it indirectly, while the returned result is also the processed user.

class UserSerializer(serializers.ModelSerializer):
    alumni = AlumniSerializer()
    
    def to_representation(self, instance):
        req = super().to_representation(instance)
        if instance.avatar:
            req['avatar'] = instance.avatar.url
            
        if instance.cover:
            req['cover'] = instance.cover.url
        
        return req
    
    def create(self, validated_data):
        data = validated_data.copy()
        user = User(**data)
        user.set_password(user.password)
        user.save()
        
        return user
    
    class Meta:
        model = User
        fields = ['id', 'first_name', 'last_name', 'username', 'password', 'email', 'avatar', 'cover', 'alumni']
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

How to have multiple versions of website (with different type of content)?

I need a little bit of help. I'm working on a Django project, it's like a blog. I have implemented localization and added couple languages. Now I would like to develop a customized content for specific regions.

Current set up it like this: http://127.0.0.1:8000/en/

I have one content and 3 languages:

content 
             - en (English) - http://127.0.0.1:8000/en/
             - de (German) - http://127.0.0.1:8000/de/
             - ar (Arabic) - http://127.0.0.1:8000/ar/

I used django-parler so every article can be provided in all 3 languages.

Now I'd like to have more content - let's say content specific to specific region, it would look like this:

Global content
             - en (English) - http://127.0.0.1:8000/en/glo/ (content on English for global readers)
             - de (German) - http://127.0.0.1:8000/de/glo/ (content German for global readers)
             - ar (Arabic) - http://127.0.0.1:8000/ar/glo/ (content on Arabic for global readers)

German content
             - en (English) - http://127.0.0.1:8000/en/de/ (content on English for German region)
             - de (German) - http://127.0.0.1:8000/de/de/ (content German for German region)
             - ar (Arabic) - http://127.0.0.1:8000/ar/de/ (content on Arabic for German region)

Middle East content
             - en (English) - http://127.0.0.1:8000/en/me/ (content on English for Middle East readers)
             - de (German) - http://127.0.0.1:8000/de/me/ (content German for Middle East readers)
             - ar (Arabic) - http://127.0.0.1:8000/ar/me/ (content on Arabic for Middle East readers)

I would incorporate on menu, I speak this language and I want to see this content.

Models would do same thing, I don't think that there would be many exemptions.

I noticed that django website has same approach, if we look at the link: docs.djangoproject.com/en/4.2

en at the end of the domain is language and 4.2 is version, I'm looking how to implement version part on my website.

I found the django "sites" framework but it doesn't make sense for me. Please could you guide me how to do this, is there any tutoral or there is specific name for this?

Thanks in advance!

Why is the variable used as an argument in fmt.Print escaped?

Why is the variable used as an argument in fmt.Print escaped? Also, why is the variable used as an argument in print not escaped?

package main

import "fmt"

func main() {
    a := 1
    fmt.Print(a) // a escapes to heap
    print(a)     // a doesn't escape to heap
}
$ go build -gcflags="-m -m -l" main.go
# command-line-arguments
./main.go:7:12: a escapes to heap:
./main.go:7:12:   flow: {storage for ... argument} = &{storage for a}:
./main.go:7:12:     from a (spill) at ./main.go:7:12
./main.go:7:12:     from ... argument (slice-literal-element) at ./main.go:7:11
./main.go:7:12:   flow: {heap} = {storage for ... argument}:
./main.go:7:12:     from ... argument (spill) at ./main.go:7:11
./main.go:7:12:     from fmt.Print(... argument...) (call parameter) at ./main.go:7:11
./main.go:7:11: ... argument does not escape
./main.go:7:12: a escapes to heap
❌
❌