Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
R Massive Language Models Can Be Accurately Pruned in One-Shot

Paper : https://arxiv.org/abs/2301.00774

Abstract :

>We show for the first time that large-scale generative pretrained transformer (GPT) family models can be pruned to at least 50% sparsity in one-shot, without any retraining, at minimal loss of accuracy. This is achieved via a new pruning method called SparseGPT, specifically designed to work efficiently and accurately on massive GPT-family models. When executing SparseGPT on the largest available open-source models, OPT-175B and BLOOM-176B, we can reach 60% sparsity with negligible increase in perplexity: remarkably, more than 100 billion weights from these models can be ignored at inference time. SparseGPT generalizes to semi-structured (2:4 and 4:8) patterns, and is compatible with weight quantization approaches.

/r/MachineLearning
https://redd.it/1027geh
Thoughts on these Courses?

Good morning, I'm looking to learn ML and AI with python with Udemy courses, did anyone already took any of these courses? I want to know if they worth it

​

​

https://preview.redd.it/dobm0q58du9a1.png?width=1143&format=png&auto=webp&s=bd5c165bad2e8d0d94f633635db56a7eb3c23ce5

https://preview.redd.it/ulf303x9du9a1.png?width=1089&format=png&auto=webp&s=9ce3c87a211495707e5677baf8b47879eb1d757b

/r/Python
https://redd.it/102a6mu
Is there a simple way to show a loading screen/icon while waiting on an API?

New to Django here. In this side-project I'm working on, I'm calling a public API to display some info for a simple game. Is there an easy way to show some "loading...." status while it waits for the GET request to resolve? I read some posts online suggesting to get jquery or htmx involved but I'd rather not if possible. I don't want it to just be blank until it resolves.

/r/djangolearning
https://redd.it/101xjro
Celery Task needs User Data

I have a Celery Task running that outputs a constantly updating dataframe. Doing this with non user-oriented variables is simple. Being able to create the dataframe off of user stored data seems to be a bit of a problem. From the documentation I read online, it seems that Celery Tasks are not meant to be user-centric.

What other way can I go about this so that a dataframe pulls through and constantly updates a "live table" based on a stored stock symbol for the user? Or if I need to look at this in a different light, please let me know. TIA.

/r/djangolearning
https://redd.it/101olfs
Page not found (404) in Post/Detail view

Hello! I've been working on a blog project with Django and I'm having trouble with a CBV.

Context:

I want to add comments to my detailed post template. To do so, I'm following this approach: https://docs.djangoproject.com/en/4.1/topics/class-based-views/mixins/#an-alternative-better-solution

The app renders the form but when I post the comment, I get a 404 (Page not found at /post/5/) saying "No comment found matching the query".

These are my files:

​

views.py:

from django.views.generic import DetailView, FormView, View
from django.views.generic.detail import SingleObjectMixin
from .models import Post, Comment
from .forms import CommentForm
from django.urls import reverse
from django.http import HttpResponseForbidden

class PostDetailView(DetailView):
model = Post
templatename = "postdetail.html"

def getcontextdata(self, kwargs):
context = super().getcontextdata(kwargs)
context"form" = CommentForm()
return context




/r/djangolearning
https://redd.it/101myu1
How to reverse an item list like this in the Django admin panel where the most recent item entered appears the first in the list

/r/djangolearning
https://redd.it/10185w6
Bootstrap misbehaving in Django

Hello guys, I'm working on django project whereby I'm using bootstrap4. The input fileds, buttons and everything are working fine but the date-time picker, select option dropdown, and file uploader are not display properly as they should do. If I render my HTML code outside django project everything is working fine but If I put it in django it's breaking

/r/djangolearning
https://redd.it/1019xqs
any idea how to make that check box in the Django admin panel a lil bit bigger

/r/djangolearning
https://redd.it/100yhoj
export to excel(.xls)

i am using python xlwt module to convert my database query into an excel sheet.everything works fine,but now i want to adjust my date coloumn as below

def tonerdetails_export_toexcel(request,id):
toner_model = find_toner_model(id)
fmt = '%Y-%m-%d %H:%M:%S'
response =HttpResponse(content_type='application/ms-excel')
response['Content-Disposition']='attachment; filename=TonerReport ' + str(toner_model) + '.xls'
wb=xlwt.Workbook(encoding='utf=8')
ws=wb.add_sheet('Toner Report')
row_num=0
font_style=xlwt.XFStyle()
font_style.font.bold=True
date_format = xlwt.XFStyle()
date_format.num_format_str = 'yyyy/mm/dd'
columns=['Toner Model','Issued To','Employee Name','Employee Designation','Date Dispatched','Status']
for col_num in range (len(columns)):
ws.write(row_num,col_num,columns[col_num],font_style)
font_style = xlwt.XFStyle()
rows=TonerDetails.objects.filter(toner_model_id=id).values_list('toner_model_id__ton
er_model','issued_to_id__name','employee_name',

/r/djangolearning
https://redd.it/zzp557
Cómo hago para relacionar una ForeignKey de un models a la view o base de datos?

Realicé un models con relaciones de tablas utilizando ForeignKeys. Realicé su respectivos forms y views. Solo que ahora no se cargan los datos ingresados a la base de datos de esa ForeignKey, en este caso es num_dni.

Adjunto mi código:

Models

class Dueno(models.Model):
localidad = models.CharField('Localidad', maxlength=150, null=True)

class Persona(models.Model):

nombre = models.CharField('Nombre/s', max
length=150)
apellido = models.CharField('Apellido/s', maxlength=150)
direccion = models.CharField('Dirección', max
length=150)
telefono = models.IntegerField('Teléfono')
nummatricula = models.ForeignKey(Empleado, ondelete=models.PROTECT, null=True)
numdni = models.ForeignKey(Dueno, ondelete=models.PROTECT, null=True)

Form:

class DuenoPaciente(forms.Form):
nombre = forms.CharField(label='Nombre', max
length=150)
apellido = forms.CharField(label='Apellido', maxlength=150)
telefono = forms.IntegerField(label='Teléfono')
direccion = forms.CharField(label='Dirección', max
length=150)
dni = forms.CharField(label='DNI')


Views:



/r/djangolearning
https://redd.it/zzu49i
Need a simple source code

I need to develop an application for my company to order material, internally. I'm still learning python, but they gave me ONE WEEK to do it using Django, not in Java that I develop. To build it using java is pretty easy, cos I just need an administrative module to create and manage products/users, and other to order products.
Anyone knows where can I find an open source code for this, so I can use during this time that I'm learning and maybe adapt/improve when i become skilled enough?
I don't know what to do and I'm a little worried.

/r/djangolearning
https://redd.it/102pkr7
My Crispy form fields are not showing

Hello,

So I am in a strange situation here and I can't figure out what it is that I am doing wrong.

I am building a django app that requires user authentication (register, login, logout) and I am using Crispy forms and bootstrap4 to create the necessary forms. Everything looks fine with the code but the form fields are not showing.

The only thing I can see is the button. Here's an image.

https://preview.redd.it/4i2i7o9chy9a1.png?width=1220&format=png&auto=webp&s=afc7976c174dd3d99cc251985aa56e910a72520d

​

I am using this same code on another project and it seems to be working fine.

Here are my register_user views:

def register_user(request):if request.method== "POST":form = NewUserForm(`request.POST`)if form.is_valid():user = `form.save`()login(request, user)messages.success(request, "Registration successful." )return redirect("/")messages.error(request, "Unsuccessful registration. Invalid information.")form = NewUserForm()return render(request, "register.html", {"register_form":form})

​

my forms:

from django import formsfrom django.contrib.auth.forms import UserCreationFormfrom django.contrib.auth.models import Userclass NewUserForm(UserCreationForm):email = forms.EmailField(required = True)

class Meta:model = Userfields =  "email", "username", "password1", "password2"def save(self, commit = True):user= super(NewUserForm, self).save(commit=False)user.email = self.cleaned_data['email']if commit:`user.save`()return user

​

URL path

path('register/', views.register_user, name='register'),

and finally, my HTML code:

<div class="container py-5"><h1>Register Now</h1><form method="POST">{% csrf_token %}{{ register_form|crispy }}<button class="btn btn-primary" type="submit">Register</button></form><p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p></div>The same case applies to my login page.

What I have tried so far:

1. I tried rewriting the code, obviously.
2. I also tried starting another app and using the same code

/r/djangolearning
https://redd.it/102u542
Help With Model Inheritance

Hello all,

I was hoping someone could help me understand model inheritance a little better and figure out why I am getting an error. I am working on some helpers for the game Twilight Imperium. I will explain what I am trying to do and then the ask at the bottom of this post.

First, I have a model that represents a unit in a board game. The model code looks like this:

class Unit(models.Model):
name = models.CharField(max_length=32, primary_key=True)
wiki_url = models.URLField()
avatar = models.URLField()
extra_info = models.TextField(null=True, blank=True)

cost = models.IntegerField()
combat = models.IntegerField()
combat_quantity = models.IntegerField()
move = models.IntegerField()
capacity = models.IntegerField()
production_quantity = models.IntegerField()

upgrade_available = models.BooleanField()


/r/django
https://redd.it/102kib8
Problems with bootstrap base template

The problem is this: when i put this code:

{% extends "base.html" %}

{% block title %}
Home
{% endblock %}


{% block content %}
Quiz list
{% endblock %}

Django just goes to the bootstrap base template and ignores the rest of the code. This is the bootstrap code (base.html):

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>



/r/django
https://redd.it/102rmf9
Problem opening a thumbnail

Hi everyone!

I'm attempting to open a thumbnail of an image that was saved with django-versatileimagefield

https://django-versatileimagefield.readthedocs.io/en/latest/

file = instance.image.thumbnail'1920x1080'.open(mode='rb')

I'm getting the following error:

'SizedImageInstance' object has no attribute 'open'

I have success with the following line of code, but I want to open the smaller version as opposed to the original version

file = instance.image.open(mode='rb')

If it helps, the url of the image is instance.image.thumbnail['1920x1080'\].url

Thanks!

/r/django
https://redd.it/102qn4m
Best practice for displaying local time

Hi!

What is the best practice in django for handling timezones?

If I understood correctly, it would be the best to have TIME_ZONE = 'UTC' and USE_TZ = True in settings.py, but I am really struggling to understand how to then display the correct time depending on the user's location.

Thank you very much in advance for your help!

/r/django
https://redd.it/102ia4p