Snippets Collections
from django.utils import timezone

current_year = timezone.now().year
items = Items.objects.filter(created_time__year=current_year)
["GET / api", "GET / api/rooms", "GET / api/rooms/:id"]
import threading
from django.core.mail import EmailMessage
from django.conf import settings

class EmailThread(threading.Thread):

    def __init__(self, email_message):
        self.email_message = email_message
        threading.Thread.__init__(self)

    def run(self):
        print(self.email_message.send())
        
        
        
email_message = EmailMessage(
                "subject",
                "message",
                settings.EMAIL_HOST_USER,
                ["example@mail.com"]
            )
        

EmailThread(email_message).start()
pip install django-blockchain

 
--Add app in your settings.py

INSTALLED_APPS = [
    "django_blockchain",
]

--And something in your urls.py

urlpatterns = patterns('',
    url(r'^blockchain$', 'django_blockchain.urls', name='blockchain_urls'),
git clone git@github.com:runekaagaard/django-hypergen.git
cd django-hypergen/
virtualenv -p python3.9 venv
source venv/bin/activate
pip install -r requirements.txt
pip install -r examples/requirements.txt
cd examples
python manage.py migrate
python manage.py runserver
class Item(models.Model):
    sku = models.CharField(max_length=50)
    description = models.CharField(max_length=200)
    added_by = models.ForeignKey(User)


class ItemForm(ModelForm):
    class Meta:
        model = Item
        exclude = ('added_by')

def new_item_view(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        # Validate and save
    else:
            form = ItemForm()
    # Render the view
#view.py

from django.shortcuts import get_object_or_404
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView


class ProfileDetail(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'profile_detail.html'

    def get(self, request, pk):
        profile = get_object_or_404(Profile, pk=pk)
        serializer = ProfileSerializer(profile)
        return Response({'serializer': serializer, 'profile': profile})

    def post(self, request, pk):
        profile = get_object_or_404(Profile, pk=pk)
        serializer = ProfileSerializer(profile, data=request.data)
        if not serializer.is_valid():
            return Response({'serializer': serializer, 'profile': profile})
        serializer.save()
        return redirect('profile-list')

#profile_detail.html

{% load rest_framework %}

<html><body>

<h1>Profile - {{ profile.name }}</h1>

<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save">
</form>

</body></html>
{% for kategorie in kalender.kategorie_set.all %}
          {% ifequal kategorie.name "Aktuell" %}
        		{% if kategorie.anzeigbare_termine %}
            		<!-- Headline ausgeben -->
            		{% for termin in kategorie.anzeigbare_termine %}
             			<!-- Termin ausgeben -->
            		{% endfor %}
             	{% endif %}
         {% endifequal %}
{% endfor %}


     
// views.py
class SomeFormView(FormView):

    def get_success_url(self):
        if 'ka' in self.request.get_full_path():
            success_url = '/ka/message-sent/'
        elif 'en' in self.request.get_full_path():
            success_url = '/en/message-sent/'
        else:
            success_url = '/message-sent/'
        return success_url

// template.html
<form action="{% url 'app_name:message-sent' %}">
  	{% csrf_token %}
	{{ form }}  
</form>
// models.py
class Product(models.Model):
    title = models.CharField(max_length=225, unique=True)
    slug = models.SlugField(max_length=225, unique=True, null=True)

// admin.py
class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}

// views.py
class productDetail(generic.DetailView):
    model = Detail
    template_name = 'detail.html'

// urls.py
    path('product/<slug:slug>/', views.productDetail.as_view(), name='productDetail'),
// models.py
from django.db.models.fields import FloatField

class Product(models.Model):
    title = models.CharField(max_length=225)
    price = models.FloatField()
    discount_percent = FloatField(default=0) # Assigning it a default value of 0 so it doesn't throw a 'NoneType' error when it's null.
  
    @property
    def discount(self):
        if self.discount_percent > 0:
            discounted_price = self.price - self.price * self.discount_percent / 100
            return discounted_price

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
	
	# get_total function has to be updated too to calculate using the correct current price
    @property
    def get_total(self):
        if self.product.discount_percent > 0:
            price_now = self.product.price - self.product.price * self.product.discount_percent / 100
        else:
            price_now = self.product.price

        total = price_now * self.quantity
        return total

// Your template
{% if product.discount_percent %}
                <h4 class="product__price--original">₾{{ product.price|floatformat:2 }}</h4>
                <h4 class="product__price--discounted">₾{{ product.discount|floatformat:2 }}</h4>
                {% else %}  
                <h4>₾{{ product.price|floatformat:2 }}</h4>
                {% endif %}
                
// Here's some Sass too, if you need it
.product__price {
  &--original {
    text-decoration: line-through;
  }
  &--discounted {
    color: green;
  }
}
// models.py
from django.utils import timezone

class Product(models.Model):
    name = models.CharField(max_length=225)
    created_on = models.DateTimeField(auto_now_add=True)
    
    @property
    def is_new(self):
        now = timezone.now()
        diff = now - self.created_on
        
        if diff.days < 7: # 7 is the number of days
            return True
        else:
            return False  

// in your template
<h4>{{ product.name }}{% if product.is_new %}<span>სიახლე</span>{% endif %}</h4>
class Meta:
	verbose_name_plural = "Categories"
AWS_ACCESS_KEY_ID = your_access_key_id
AWS_SECRET_ACCESS_KEY = your_secret_access_key
AWS_STORAGE_BUCKET_NAME = 'sibtc-static'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
  
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage
virtualenv myenv

myenv\Scripts\activate

deactivate
{
    "python.defaultInterpreterPath": "E:\\WebDevDjango\\Django_Projects\\PARASenv\\Scripts\\Python.exe"
}
{% if places.spalte %}
	<section>
		{% render_elements "spalte" %}
	</section>
{% endif %}
    def create(self, validated_data):
        # print(validated_data)
        tags = validated_data.pop("tags")
        language = validated_data.pop("language")
        snip = Snip(**validated_data)
        # languageObj, created = Language.objects.get_or_create(**language)
        snip.language = language
        snip.save()
        for tag in tags:
            # tagObj, created = Tag.objects.get_or_create(**tag)
            # print(tagObj)
            snip.tags.add(tag)
        return ShallowSnipSerializer(snip).data
django-admin startproject mysite

python manage.py startapp myapp
{% include "cms/seminare.html" %}
if reg_form.is_valid():
            nuevo_usuario = reg_form.save(commit=False)
            pw_hash = bcrypt.hashpw(clave.encode(), bcrypt.gensalt()).decode() 
            nuevo_usuario.password = pw_hash
            nuevo_usuario.save()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'dojoreads_db',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
# Git Commands

## git init
initialize git and create a new local repository

## git add .
track all the files in the local repo for changes

## git add filename
track a specific file in the repo for changes

## git commit -m "first commit" -m "the description"
take a snapshot of the files in the repo

## git status
check the status of your code

## git remote add origin https-link
add a new remote repository

## git push origin master
push the local repository to github

## git push -u origin master
push the local repository to github and also set upstream (enables you to use git push only in future)

## git branch
check the current branch and available branches

## git checkout -b new-branch-name
go to another new branch

## git checkout existing-branch
switch to an existing branch

## git diff feature
see the difference between files you want to merge

## git config --global user.name "[name]"
Sets the name you want attached to your commit transactions

## git config --global user.email "[email address]"
Sets the email you want attached to your commit transactions

## git config --global color.ui auto
Enables helpful colorization of command line output

## git push
use this cmd when pushing a new branch to see how it should be done

## git pull
when upstream is set , to pull from github when changes made on the github and want them to reflect on local machine

## git pull origin master
to pull from github when changes made on the github and want them to reflect on local machine

## git branch -d branch-name
delete a branch

## git commit -am "message"
commit and add at the same time
## generate the requirements file
pip freeze > requirements.txt

## specify where to store django static files just above the static url
STATIC_ROOT = BASE_DIR / 'staticfiles'

## tell heroku how to serve them with whitenoise
add this in settings.MIDDLEWARE below security
'whitenoise.middleware.WhiteNoiseMiddleware',

## add allowed hosts, name of app and local host url example
ALLOWED_HOSTS = ['text-test-heroku.herokuapp.com', '127.0.0.1:8000']

## create a runtime.txt file to put the python version required-
python-3.7.9

## create a Procfile file to say from where it would beserved
(make sure to have installed gunicorn in pip)
web: gunicorn MovieReview.wsgi --log-file -
MovieReview is folder where wsgi is located
//template

{% for contact in page_obj %}
    {# Each "contact" is a Contact model object. #}
    {{ contact.full_name|upper }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
         

//views.py
         
from django.core.paginator import Paginator
from django.shortcuts import render

from myapp.models import Contact

def listing(request):
    contact_list = Contact.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page.

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'list.html', {'page_obj': page_obj})       
{% if request.resolver_match.url_name == 'home' %} active {% endif %}
// template.html
<link rel="stylesheet" href="{% static '/bulma-css/bulma-divider.min.css' %}" type="text/css">
<link rel="stylesheet" href="{% static '/bulma-css/bulma-switch.min.css' %}" type="text/css"> 
<link rel="stylesheet" href="{% static '/bulma-css/bulma.min.css' %}" type="text/css"> 
<link rel="stylesheet" href="{% static '/css/main.css' %}" type="text/css"> 


// settings.py

STATIC_URL = '/static/'

STATIC_ROOT = 'avon/static'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

// views.py

def template(request, self):
	return render(request, "template.html")
    
//  urls.py

urlpatterns [] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

    
# make sure that you save the file when reloading changes in port 8000
# check the path you defined in views.py, and for urls.py


# views
def about(request):
    return render(request, 'about.html')
    
# urls

urlpatterns [
path('', views.index, name='index'),
path('templates/about.html/', views.about, name="about")
]
star

Wed Apr 19 2023 19:32:13 GMT+0000 (Coordinated Universal Time)

#python #django
star

Mon Apr 17 2023 07:50:27 GMT+0000 (Coordinated Universal Time) http://127.0.0.1:8000/api/

#django
star

Tue Dec 20 2022 12:29:24 GMT+0000 (Coordinated Universal Time) https://www.coursera.org/learn/apis/supplement/oQrdH/optional-creating-a-django-project-steps-and-code

#django
star

Fri Jul 01 2022 08:56:09 GMT+0000 (Coordinated Universal Time)

#python #django
star

Sun May 29 2022 19:51:50 GMT+0000 (Coordinated Universal Time) https://pythonrepo.com/repo/null-none-django-blockchain-python-django-utilities

#api #blockchain #django #cli
star

Wed May 25 2022 00:39:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/34719230/django-how-to-access-current-logged-in-users-id-in-javascript

#django #js #javascript
star

Mon May 02 2022 20:28:26 GMT+0000 (Coordinated Universal Time) https://github.com/runekaagaard/django-hypergen

#python #django
star

Sun Apr 03 2022 13:48:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot

#django
star

Wed Mar 16 2022 12:58:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57939294/how-to-use-the-django-rest-auth-views-with-custom-html-templates-instead-of-brow

#python #django #djangorestframework
star

Fri Feb 04 2022 13:41:34 GMT+0000 (Coordinated Universal Time) http://www.noris-inklusion.de

#django
star

Fri Dec 10 2021 17:24:15 GMT+0000 (Coordinated Universal Time) https://realpython.com/get-started-with-django-1/

#django
star

Mon Oct 11 2021 04:11:32 GMT+0000 (Coordinated Universal Time)

#django #ecommerce #slug
star

Sat Oct 09 2021 22:08:37 GMT+0000 (Coordinated Universal Time)

#django #ecommerce
star

Fri Oct 08 2021 16:21:03 GMT+0000 (Coordinated Universal Time)

#django
star

Mon Oct 04 2021 19:48:40 GMT+0000 (Coordinated Universal Time) https://stackabuse.com/serving-static-files-in-python-with-django-aws-s3-and-whitenoise/

#django #aws #awss3
star

Thu Jul 29 2021 06:31:35 GMT+0000 (Coordinated Universal Time)

#python #django
star

Thu Jul 29 2021 06:29:19 GMT+0000 (Coordinated Universal Time) https://code.visualstudio.com/docs/python/environments

#python #django
star

Tue Jun 08 2021 11:27:42 GMT+0000 (Coordinated Universal Time)

#django #selfsite
star

Wed May 12 2021 08:30:51 GMT+0000 (Coordinated Universal Time)

#python #django
star

Fri Apr 02 2021 12:37:15 GMT+0000 (Coordinated Universal Time)

#python #django
star

Wed Mar 31 2021 10:03:05 GMT+0000 (Coordinated Universal Time)

#django
star

Wed Mar 31 2021 00:23:18 GMT+0000 (Coordinated Universal Time)

#django #python
star

Mon Mar 29 2021 22:54:38 GMT+0000 (Coordinated Universal Time)

#python #django #postgres
star

Mon Mar 29 2021 22:20:07 GMT+0000 (Coordinated Universal Time)

#python #django #postgres
star

Wed Dec 30 2020 19:26:24 GMT+0000 (Coordinated Universal Time)

#django,python,django #django
star

Wed Dec 30 2020 19:24:10 GMT+0000 (Coordinated Universal Time)

#django #python,django
star

Fri Dec 25 2020 11:34:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38257231/how-can-i-upload-multiple-files-to-a-model-field

#django
star

Tue Dec 22 2020 11:16:09 GMT+0000 (Coordinated Universal Time)

#python #django
star

Tue Dec 22 2020 09:02:28 GMT+0000 (Coordinated Universal Time)

#python #django
star

Sun Aug 02 2020 02:24:12 GMT+0000 (Coordinated Universal Time)

#django #css #html
star

Fri Jun 05 2020 23:16:55 GMT+0000 (Coordinated Universal Time)

#django
star

Mon May 11 2020 13:44:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15501673/how-to-temporarily-disable-a-foreign-key-constraint-in-mysql

#django #python

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension