How to display forms for some users Odoo 10 - python

I work with Odoo 10.
In Front-End Development, I have different forms available today for all types of users. I would like to post only certain forms. In backend development, I create a boolean type field that will allow me to tell if this form will be visible to a public or authenticated user. The problem is that I do not know how to create a Python function to differentiate the two types of users with this boolean. Do I have to use the controller? Or rather do a function in my corresponding class? Here are the codes:
class :
# -*- coding: utf-8 -*-
from odoo import models, fields, api, http, exceptions
class InheritedWebsiteApplicationTemplate(models.Model):
# region Private attributes
_inherit = 'website.application.template'
# endregion
# region Fields declaration
user_not_connected = fields.Boolean(string="Formulaire pour utilisateur non connecté")
controller :
#http.route(['/my/web-demarche'], type='http', auth="public", method=['GET'], website=True)
# #http.route(['/my/web-demarche'], type='http', auth='user', method=['GET'], website=True)
def get_demarche(self, date_begin=None, date_end=None, **post):
"""Display all requests owned by the current user."""
template_name = 'grc.demarche'
context = self._prepare_portal_layout_values()
# On va chercher les demandes de l'utilisateur, le filtre se fait par un ir.rule
domain = []
archive_groups = self._get_archive_groups('website.application', domain)
if date_begin and date_end:
domain += [('create_date', '>=', date_begin), ('create_date', '<', date_end)]
domain += [('applicant_id', '=', request.env.uid)]
user_requests = request.env['website.application'].sudo().search(domain)
# On va chercher les modèles de demandes actifs (mais pas ceux sans demande multiple si déjà demandés)
request_templates = get_available_requests(request.env.user, user_requests)
if request.httprequest.method == 'POST':
if post.get('suivi', False):
record_ticket = request.env['website.application'].search([('name','=',str(post.get('suivi', False)))], limit=1)
if record_ticket:
return request.redirect('/my/web-demarche/' + str(record_ticket.name))
else:
context.update({'error_not_found': True})
context.update({
'website_requests': user_requests,
'request_templates': request_templates,
'archive_groups': archive_groups,
'date': date_begin
})
return request.render(template_name, context)
Result (template) :

Related

get a dictionary variable to use it in the same dictionary to get the file extension django python

I am creating a folder tree to display it. For this, I need to get the file extension. Before the folder, we need to enter a password.
views.py
def www_telechargements(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CatalogueForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
context = {
'mdp': form.cleaned_data["response_mdp"]
}
good_answer = ("\n".join(context.values()))
if good_answer == "Vitasolar1234":
template = loader.get_template('telechargement-response.html')
arborescence_path = os.path.join(BASE_DIR, "WWW/static/arborescence")
arborescence_content = os.listdir(arborescence_path)
response_gabarit = {
'answer': True,
'dossier': arborescence_content,
'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix)#c'est ici que je veux récupérer le string de 'dossier'
}
print(os.listdir(arborescence_path))
return HttpResponse(template.render(response_gabarit, request))
else:
response_gabarit = {'answer': False}
template = loader.get_template('telechargement-response.html')
return HttpResponse(template.render(response_gabarit, request))
# if a GET (or any other method) we'll create a blank form
else:
form = CatalogueForm()
return render(request, 'telechargements.html', {'form': form})
This is my mistake:
'type': pathlib.Path(os.listdir(response_gabarit('dossier')).suffix)
And it throws the below error:
UnboundLocalError: local variable 'response_gabarit' referenced before assignment
I would like to get the string 'dossier' but it is not possible;
I understand my mistake but I have no idea how to solve this problem
I tried to use my content_tree variable directly but it's a list and my method absolutely wants a string.

django session project cart

I'm trying to display data that I put on a session for my shopping cart project that I'm developing,
but here I can't recover the product whose code I passed as a parameter
def index(request):
mes_produits={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
parcou=mes_produits['produits']
contex={'produits':parcou}
return render(request,'shop/index.html',contex)
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
request.session['nom']=selected_product.get('nom')
request.session['prix']=selected_product.get('prix')
contex={'nom':request.session['nom'],'prix':request.session['prix']}
return render(request, 'cart/cart_detail.html',contex)
car_detail.html
{% for key,value in request.session.items %}
Nom : {{value.nom}}
Prix : {{value.prix}}
{% endfor %}
I get a blank page with the name of the keys only
Your session object is a dict, not a list of tuple. Try this code in template:
Nom : {{request.session.nom}}
Prix : {{request.session.prix}}
But, you have already set the vars in context, so you can do:
Nom : {{nom}}
Prix : {{prix}}
# And your views.py
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
context={
'nom':selected_product.get('nom'),
'prix':selected_product.get('prix')
}
else:
context = {}
return render(request, 'cart/cart_detail.html',context)
Maybe you do not understand session usage?
https://docs.djangoproject.com/en/4.1/topics/http/sessions/

Django REST: get_queryset providing duplicate responses

I am creating a simple online shop app so when you want to buy an item, a button click leads you to the charge api. (ex. item 2 will direct to /api/charge/2)
urls.py
from django.urls import path
from gallery.views import ClothingView
from gallery.api.views import ListClothes
from gallery.api.views import ChargeView
urlpatterns = [
path('api/<int:num>/', ListClothes.as_view()),
path('api/charge/<int:num>', ChargeView.as_view(), name='charge_api'),
]
views.py
class ChargeView(ListCreateAPIView):
serializer_class = ChargeSerializer
count = 0
def get_queryset(self):
a = ClothingModel.objects.filter(id=self.kwargs['num']).first()
net_price = int(float(a.full_price) * 100)
if float(a.discount) > 0.00:
net_price = int(net_price * (1 - (float(a.discount) / 100)))
self.count += 1
print(self.count)
if self.count == 1:
stripe.api_key = settings.API_KEY
charge_rtn_body = stripe.Charge.create( # Create charge object
amount=net_price,
currency="usd",
source="tok_visa", # obtained with Stripe.js
description= "[Stripe charge] " + a.description.upper()
)
return ClothingModel.objects.filter(id=self.kwargs['num'])
serializers.py
class ChargeSerializer(serializers.ModelSerializer):
class Meta:
model = ClothingModel
fields = ('full_price', 'discount', 'description')
I am creating a charge object for Stripe (payment method) each time the api gets called, but dependent on the clothing item id. So to handle this I use self.kwargs on get_queryset() to link to a clothing item. When I view the charges on my Stripe dashboard after a single click, multiple charges come at once (4 at a time). I have hard coded the if self.count == 1: as a work around but know that is not good practice. Is there a reason for these multiple calls in get_queryset() per single request and how can I cleanly implement? Thank you.
Objects should be created only in POST requests. get_queryset is called everytime a view is invoked (even for GET requests). So the object create should be moved inside the view function. The dynamic part of the URL is accessible from the view function as present here - https://docs.djangoproject.com/en/2.1/topics/http/urls/#example
class ChargeView(ListCreateAPIView):
def post(self, request, num):
charge = ClothingModel.objects.get(id=num)
from django.conf import settings # new
from django.views.generic.base import TemplateView
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
class HomePageView(TemplateView):
template_name = 'stripe.html'
def get_context_data(self, **kwargs): # new
context = super().get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
return context
def charge(request): # new
if request.method == 'POST':
charge = stripe.Charge.create(amount=5000,currency='ind',description='A Django charge',
source=request.POST['stripeToken'])
return render(request, 'charge.html')

Python Psycopg2 cursor.execute returning None

Hello I'm working on a script in Python that will connect to a db retrieve some information and send emails. I'have a problem with queries done with Psycopg.
I'would like to retrieve all the users where created_at = nb_days. My query work very good in navicat/pgadmin and I'have 53 records with the query :
select a.account_name, a.email, a.user_id, a.locale, a.firstname from v_accounts a where date(a.created_at) = date(current_date - interval '2 days')
But when I execute my script I have None as result of the query. This is my script class :
import psycopg2
class MyDatabase(object):
db_name='you'
user='will'
pw='never'
host='know'
port='it'
def __init__(self, db=db_name, user=user, password=pw, host=host, port=port):
"""Connection to db - creation of the cursor"""
try:
self.baseDonn = psycopg2.connect(host=host, port=port, database=db, user=user,password=password)
except Exception as err:
print('La connexion avec la base de données à échoué : Erreur détéctée : %s' % err)
else:
self.cursor=self.baseDonn.cursor() # Création du curseur
def get_data_from_accounts(self,nb_days):
''' Method that retrieves data from all accounts that were created nb_days before today '''
sql="select a.account_name,u.email, u.user_id,u.locale, u.firstname from accounts a inner join account_users au on a.account_id=au.account_id inner join users u on au.user_id=u.user_id where date(a.created_at) = date(current_date - interval '%s days');"
print(sql)
data=(nb_days,)
try:
records = self.cursor.execute(sql,data)
print('cursor-execute={}'.format(records))
except Exception as err:
print("La requete n'est pas passée, erreur={}".format(err))
else:
return records
This is the main part
from my_db import MyDatabase
database=MyDatabase()
# On va récupérer les données des nouveaux accounts d'y a un jours
days_ago_2=database.get_data_from_accounts(2)
for personne_1 in days_ago_2:
# data
#account_name=personne_1[0]
email=personne_1[1]
user_id=personne_1[2]
locale=personne_1[3]
firstname='' if personne_1[4] is None else personne_1[4]
language = locale.split('_')[1]
activation_token= database.get_activation_token(user_id)
subject = call_to_template2(firstname, language,activation_token)['subject']
content = call_to_template2(firstname, language,activation_token)['content']
print('EMAIL={} - ID={} - LANGUE={} - FIRSTNAME={}'.format(email, user_id, language, firstname))
#send_data(qui_envoie, email, subject, content, token, language)
And my error is on the line for personne_1 in days_ago_2: because None object is not iterable. And I've saw that the result of my query get_data_from_accounts(2) = None
cursor.execute allways returns None. You need to fetch the record set:
try:
self.cursor.execute(sql,data)
records = self.cursor.fetchall()

django-autocomplete key error

I installed via pip install django-autocomplete, as the django autocomplete's documentation said.
Then, i added the code, always following the documentation given.
I get the error: KeyError: Gestion.clientes
and also, when i try to import the views module from Gestion app, it says AttributeError: 'module' object has no attribute 'autocomplete'
It seems like i cannot import Gestion/views.py, since there's a circular import going on... i tried to attack this issue in many ways, but i'm really stucked...
Here's my app files
The app is called "Gestion", i'm running Django 1.3 in virtualenv with Python2.7
Gestion/views.py
# -*- encoding: utf-8 -*-
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.shortcuts import render_to_response,render
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.core import serializers
import models
from django.db.models import Q
from django.utils import simplejson
from autocomplete.views import AutocompleteView
import forms
autocomplete = AutocompleteView('Gestion')
def home(request):
return render(request,'index.html')
def facturas(request, cliente=0):
return render(request,'facturas.html')
def cliente_nuevo(request):
form = forms.Clientes()
if request.method == 'POST':
form = forms.Clientes(request.POST)
cliente = form.save()
messages.add_message(request,messages.SUCCESS,'El cliente ha sido creado correctamente')
return HttpResponseRedirect(reverse('cliente_detalle',args=(cliente.pk,)))
return render(request,'cliente-nuevo.html',{'form':form})
def clientes(request):
#Si la petición es de tipo POST, devuelve un listado de cientes en JSON
if request.method == 'POST':
if 'q' in request.POST:
query_build = Q(**{"razon_social__icontains": request.POST['s'] })
clientes = models.Cliente.objects.filter(query_build)
else:
clientes = models.Cliente.objects.all()
data = serializers.serialize('json', clientes)
return HttpResponse(data, mimetype='application/json')
params = request.GET.copy()
s = None
if 'page' in params:
del(params['page'])
if 's' in params:
query_build = Q(**{"razon_social__icontains": params['s'] })
clientes = models.Cliente.objects.filter(query_build)
s = params['s']
else:
clientes = models.Cliente.objects.all()
paginator = Paginator(clientes, 20)#Clientes por página
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
clientes = paginator.page(page)
path = params.urlencode()
return render(request,'clientes.html',{'clientes':clientes,'path':path,'s':s})
def cliente_detalle(request, id):
cliente = models.Cliente.objects.get(pk = id)
return render(request,'cliente-detalle.html',{'cliente':cliente})
def cliente_editar(request, id):
cliente = models.Cliente.objects.get(pk = id)
form = forms.Clientes(instance=cliente)
return render(request,'cliente-editar.html',{'form':form, 'cliente':cliente})
def articulo_nuevo(request):
form = forms.Articulo()
if request.method == 'POST':
form = forms.Articulo(request.POST)
if form.is_valid():
form.save()
messages.add_message(request,messages.SUCCESS,'El artículo ha sido creado correctamente')
return HttpResponseRedirect(reverse('articulos'))
return render(request,'articulo-nuevo.html',{'form':form})
def articulos(request):
params = request.GET.copy()
s = None
c = None
if 'page' in params:
del(params['page'])
q = Q()
if 's' in params and params['s']:
q.add(Q(**{"nombre__icontains": params['s']}), Q.AND)
q.add(Q(**{"referencia__icontains": params['s']}), Q.OR)
s = params['s']
if 'c' in params and params['c']:
c = params['c']
q.add(Q(**{"categoria__contains":c}), Q.AND)
articulos = models.Articulo.objects.filter(q)
sql = articulos.query
articulos = list(articulos.order_by('stock'))
paginator = Paginator(articulos, 2)#Artículos por página
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
articulos = paginator.page(page)
path = params.urlencode()
return render(request,'articulos.html',{'lista':list(articulos.object_list),'articulos':articulos, 'path':path, 's':s, 'c':c, 'categorias': models.Articulo.CATEGORIAS, 'sql':sql})
def factura_nueva(request):
return render(request,'factura-nueva.html')
def pedidos(request):
return render(request,'pedidos.html')
def nueva_linea_de_pedido(request):
form = forms.Linea()
return render(request,'pedido-linea-nueva.html',{'form':form})
def editar_linea_de_pedido(request, linea):
return render(request,'pedido-linea-editar.html')
Gestion/forms.py
# -*- encoding: utf-8 -*-
from django import forms
import Gestion.models as models
import views
import autocomplete.utils as utils
import autocomplete.widgets as widgets
class Clientes(forms.ModelForm):
razon_social = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required': 'Escriba la razón social'})
numero_de_cliente = forms.CharField(widget=forms.TextInput(attrs={'required':''}),required=True,error_messages={'required': 'Escriba el número de cliente'})
cuit = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required':'Escriba el número de CUIT/CUIL'})
direccion = forms.CharField(widget=forms.TextInput(attrs={'required':''}),error_messages={'required':'Escriba la dirección'})
condicion_de_iva = forms.ChoiceField(choices=models.Cliente.CONDICIONES_DE_IVA,error_messages={'required':'Seleccione una condición de IVA'})
contacto = forms.CharField(required=False)
class Meta:
model = models.Cliente
class Articulo(forms.ModelForm):
nombre = forms.CharField(widget=forms.TextInput(attrs={'required':'','placeholder':'Nombre','class':'span4'}))
costo = forms.FloatField(widget=forms.TextInput(attrs={'required':'','placeholder':'Costo','class':'span4'}),error_messages={'invalid':'El costo debe ser numérico'})
categoria = forms.CharField(widget=forms.Select(attrs={'class':'span4'}, choices=models.Articulo.CATEGORIAS))
referencia = forms.CharField(widget=forms.TextInput(attrs={'required':'','placeholder':'Referencia','class':'span4'}))
stock = forms.IntegerField(widget=forms.TextInput(attrs={'required':'','placeholder':'Stock','class':'span4'}),error_messages={'invalid':'El stock debe ser un número entero'})
class Meta:
model = models.Articulo
class Linea(forms.ModelForm):
articulo_txt = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Comienze a escribir','class':'span4'}))
articulo = forms.IntegerField(widget=forms.HiddenInput())
cliente = utils.autocomplete_formfield('Gestion.clientes',widget=widgets.AutocompleteWidget('Gestion.clientes', view=views.autocomplete))
class Meta:
model= models.Linea
Gestion/urls.py
from django.conf.urls.defaults import patterns, include, url
from Gestion import views
from django.conf import settings
import Gestion.autocomplete_settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'imprenta.views.home', name='home'),
# url(r'^imprenta/', include('imprenta.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home, name='home'),
url(r'^facturas/$', views.facturas, name='facturas'),
url(r'^facturar/$', views.factura_nueva, name='facturar'),
url(r'^clientes/nuevo/$', views.cliente_nuevo, name='cliente-nuevo'),
url(r'^clientes/$', views.clientes, name='clientes'),
url(r'^clientes/detalle/([0-9]+)$', views.cliente_detalle, name='cliente_detalle'),
url(r'^cliente/([0-9]+)/facturas/$', views.facturas, name='cliente_facturas'),
url(r'^clientes/editar/([0-9]+)$', views.cliente_editar, name='cliente_editar'),
url(r'^articulos/$', views.articulos, name='articulos'),
url(r'^articulos/nuevo/$', views.articulo_nuevo, name='articulo_nuevo'),
url(r'^pedidos/$', views.pedidos, name='pedidos'),
url(r'^pedidos/lineas/nueva/$', views.nueva_linea_de_pedido, name='pedidos-linea-nueva'),
url(r'^pedidos/lineas/editar/([0-9]+)$', views.editar_linea_de_pedido, name='pedidos-linea-editar'),
url(r'^autocomplete/', include(views.autocomplete.urls)),
) + patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
You should almost never import views into forms. Forms are used in views, not vice versa. I'd move autocomplete = AutocompleteView('Gestion') into some separate module (for example, gestion.autocomplete) and imported from there.
P.S. Also please note that modules in Python are named in lowercase, so it should be gestion, not Gestion

Categories

Resources