{% for el in equipment %}
<img src="{{ el.logo }}" alt="{{ el.title }}">
{% endfor %}
{% for el in equipment %}
<img src="{{ el.logo.url }}" alt="{{ el.title }}">
{% endfor %}
class ViewClass(Base):
some_var=""
def get_initial(self):
profile = Profile.objects.get(user=self.request.user)
initial = super(konkurs_resultNew_record, self).get_initial() #
..........
except:
self.some_var = "Ошибка"
return initial
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["some_var"] = self.some_var
from django.core.validators import MaxValueValidator, MinValueValidator
class Unit(models.Model):
"""модель объекта недвижимости"""
year_construction = models.IntegerField(verbose_name='Год постройки', choices=year_choices(),null=True, blank=True, validators=[MinValueValidator(1950), max_value_current_year])
def current_year():
return datetime.date.today().year
def max_value_current_year(value):
return MaxValueValidator(current_year())(value)
def year_choices() -> List:
return [(r,r) for r in range(1950, datetime.date.today().year+1)]
def get_form(self, request, obj=None, **kwargs):
form = super(<<ClassName>>, self).get_form(request, obj, **kwargs)
И делай здесь что нужно как с обычной формой .....
#if request.GET and request.GET['product_id']:
#product_id = request.GET['product_id']
#product = Product.objects.get(id=product_id)
# form.base_fields['delivery_add'].initial = request.user.address
return form
def get_client_ip(request):
"""получение IP пользователя"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def check_captcha(token,request):
"""проверка токена капчи"""
guest_ip = str(get_client_ip(request))
resp = requests.get(
"https://captcha-api.yandex.ru/validate",
{
"secret": settings.YACAPCHA_SERVER,
"token": token,
"ip": guest_ip # Нужно передать IP пользователя.
# Как правильно получить IP зависит от вашего фреймворка и прокси.
# Например, в Flask это может быть request.remote_addr
},
timeout=1
)
server_output = resp.content.decode()
if resp.status_code != 200:
print(f"Allow access due to an error: code={resp.status_code}; message={server_output}", file=sys.stderr)
return True
return json.loads(server_output)["status"] == "ok"
class RequestWithCapchaCreateAPI(generics.CreateAPIView):
"""общий класс для проверки каппчи"""
def create(self, request, *args, **kwargs):
captchaToken = request.POST['smart-token']
if check_captcha(captchaToken,request):
return super().create(request, *args, **kwargs)
else:
return JsonResponse({'status':'false','message':'ROBOT'}, status=423)
def perform_create(self, serializer):
subdomain = get_subdomain(self.request)
serializer.save(subdomain=subdomain)
class CallRequestCreateAPI(RequestWithCapchaCreateAPI):
"""создание запроса на звонок"""
serializer_class = CallRequestSerializer
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/ 'templates'], # add for index (templates),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'wellway_system.context_processors.debug',
'wellway_system.context_processors.capcha', #Капчу в общий контекст
],
},
},
]
# Для yandex capcha
SECURE_REFERRER_POLICY = 'no-referrer-when-downgrade'
YACAPCHA_CLIENT = '...........' #Ключ клиента
YACAPCHA_SERVER = '...........' #Ключ сервера
from django.conf import settings
def capcha(context):
return {'YACAPCHA_CLIENT': settings.YACAPCHA_CLIENT}
<script src="https://captcha-api.yandex.ru/captcha.js?render=onload&onload=onloadFunction" defer></script>
<script>
function onloadFunction() {
if (window.smartCaptcha) {
const containers = document.querySelectorAll('#captcha-container');
containers.forEach(function (container) {
const widgetId = window.smartCaptcha.render(container, {
sitekey: "{{ YACAPCHA_CLIENT }}",
});
container.dataset.widgetid = widgetId
})
}
}
</script>
<div style="height: 100px" id="captcha-container" class="smart-captcha"></div>
function formSent(form, responseResult = ``) {
document.dispatchEvent(new CustomEvent("formSent", {
detail: {
form
}
}));
setTimeout((() => {
if (flsModules.popup) {
const popup = form.dataset.popupMessage;
popup ? flsModules.popup.open(popup) : null;
}
}), 0);
formValidate.formClean(form);
formLogging(`Форма отправлена!`);
let widget = form.querySelector("#captcha-container");
let widgetId = widget.dataset.widgetid;
smartCaptchaReset(widgetId);
}
return render(request, 'main/create.html')
--- Здесь контекст не передали в рендер!return render(request, 'main/create.html', context)
class FixLangMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if "HTTP_ACCEPT_LANGUAGE" in request.META:
del request.META["HTTP_ACCEPT_LANGUAGE"]
response = self.get_response(request)
return response
MIDDLEWARE = [
"pages.middlewares.FixLangMiddleware",
.....
# Для yandex capcha
SECURE_REFERRER_POLICY = 'no-referrer-when-downgrade'
class ContractorAdmin(admin.ModelAdmin):
model = Contractor
list_display = ('__str__', 'phone', 'site','verified')
inlines = (ProductListInline,)
def get_queryset(self, request):
"""Ограничиваем выдачу списка поставщиков"""
queryset = super().get_queryset(request)
if request.user.has_perm('orders.only_not_verified') and not request.user.is_superuser:
return queryset.filter(verified=False)
return queryset
class CustomUserModelSerializer(serializers.ModelSerializer):
"""give all users"""
status = serializers.SerializerMethodField()
class Meta:
model = CustomUser
fields = ('id', 'email', 'name', 'status', 'avatar')
def get_status(self, obj):
if obj.is_active == True:
status = 'active'
else:
status = 'inactive'
return status
def to_representation(self, instance):
response = super().to_representation(instance)
if not instance.avatar.name:
request = self.context.get('request')
response['avatar'] = request.build_absolute_uri("/media/images/avatar-test.jpg")
return response