Author Picture

Kim Majali


Add Field to QuerySet to Store Computation Results

Author Avatar wrote on 06/06/2022

Way 1: Annotate() & Query Expressions

  • https://docs.djangoproject.com/en/3.2/ref/models/expressions
  • How many chairs are needed for each company to seat all employees?
    
    from django.db.models import F
    
    company = Company.objects.filter(
       num_employees__gt=F('num_chairs')).annotate(
       chairs_needed=F('num_employees') - F('num_chairs')).first()
    
    Read more

    Django Redirect/Reverse/Render in View

    Author Avatar wrote on 03/06/2022

    1. Redirect (will prevent resubmitting the form, no context to update)

    
    from django.shortcuts import redirect
    return redirect('glossaries')
    
    Read more

    Django Loop to Update Multiple Objects

    Author Avatar wrote on 03/06/2022

    Set filed name this way name="sub_service_{{ service.id }}"
    In View data will be the name fo the field in the loop, request.POST[data] is the value
    
    for data in request.POST:
            if "sub_service_" in data:
                sub_service_id = int(data.replace("sub_service_", ""))
                CompanySubService.objects.select_for_update().filter(id=sub_service_id).update(delivery_per_hour = request.POST[data])
    
    Example with try and message
    
    if request.POST.get("form_type") == 'update_sub_services_delivery':
        try:
            for data in request.POST:
                if "sub_service_" in data:
                    sub_service_id = int(data.replace("sub_service_", ""))
                    CompanySubService.objects.select_for_update().filter(id=sub_service_id).update(delivery_per_hour = request.POST[data])
            messages.success(request, "Sub services delivery info has been updated." )
        except Exception as e:
            print("Exception update_sub_services_delivery ==========================")
            messages.error(request, "Error. Something went wrong.")
            print(e)
            print("End of Exception  ==========================")
            
        return render(request, template_name, context)
    
    Read more

    Django Checkbox, Text and Select

    Author Avatar wrote on 03/06/2022

    Checkbox

    
    record.full_timer = request.POST.get('full_timer', False)
    if record.full_timer == 'on':
        record.full_timer = True
        
    record.save(update_fields=['full_timer'])
    print('record updated')
    
    Read more

    Django URLs

    Author Avatar wrote on 03/06/2022

    Basic urls

    
    from django.conf.urls import url
    from boards import views
    
    urlpatterns = [
        url(r'^$', views.home, name='home'),
        url(r'^about/$', views.about, name='about'),
    ]
    
    

    Deeper URL structures:

    
    urlpatterns = [
        url(r'^$', views.home, name='home'),
        url(r'^about/$', views.about, name='about'),
        url(r'^about/company/$', views.about_company, name='about_company'),
    ]
    
    Advanced urls (with regex) eg: this will create a url of each username
    
    from django.conf.urls import url
    from boards import views
    
    urlpatterns = [
        url(r'^$', views.home, name='home'),
        url(r'^(?P[\w.@+-]+)/$', views.user_profile, name='user_profile'),
    ]
    

    Parameters

    1. Parameters as part of url: eg: /users/5
    
    url(r'^users/(?P\d+)/$', 'viewname', name='urlname')
    
    Function-based view
    
    def viewname(request, user_id):
        user = User.objects.get(id=user_id)
    
    Class-based view
    
    class SampleView(TemplateView):
        def get_context_data(self, **kwargs):
            user = User.objects.get(id=kwargs['user_id'])
    
    2. GET parameters eg: /products?price_lte=5000
    
    url(r'^products/$', 'viewname', name='urlname')
    
    def viewname(request):
        price_lte = request.GET['price_lte']
    
    
    3. POST parameters
    
    url(r'^register/$', 'register', name='urlname')
    
    def register(request):
        form = RegisterForm()
        if request.method == "POST":
            form = RegisterForm(request.POST) #if no files
            if form.is_valid():
                #do something if form is valid
        context = {
            'form': form
        }
        return render(request, "template.html", context)
    
    Match string after drinks/ prefix
    
    path('drinks//',...),
    
    Match one or more characters (non-digit regular expression) after drinks/ prefix
    
    re_path(r'^drinks/(?P\D+)/',...),
    
    Match integer after stores/ prefix
    
    path('stores//',...),
    
    Match one or more digits (digit regular expression) after stores/ prefix
    
    re_path(r'^stores/(?P\d+)/',...),
    
    Read more

    Topics: ViewsBasics

    CRUDgen Django CRUD generator