社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Gasanov  »  全部回复
回复总数  3
5 年前
回复了 Gasanov 创建的主题 » Django transaction.atomic()不工作

它不起作用,因为原子事务只有在引发异常时才会回滚。在您的情况下,您只需返回普通响应对象,它不会触发回滚,从而提交到数据库。

有关中的原子事务的详细信息 django docs .

将您的代码更改为类似这样的代码(未确认它是否正常工作,但链接文档中有此类示例):

from django.core.exceptions import ValidationError

def form_valid(self, form):
        context = self.get_context_data()
        phone_formset = context['phone_formset']
        email_formset = context['email_formset']
        try:
            with transaction.atomic():
                o = form.save() # <--- this object is saved even when formsets below are not valid
                condition = phone_formset.is_valid() and email_formset.is_valid()
                if not condition:
                    raise ValidationError
                phone_formset.instance = o
                phone_formset.save()
                email_formset.instance = o
                email_formset.save()
        except ValidationError:
            return render(self.request, self.template_name, self.get_context_data())
        return super(PersonCreateView, self).form_valid(form)
6 年前
回复了 Gasanov 创建的主题 » 无法扩展django 2.1密码重置模板

在路径周围加引号,如下所示:

{% extends "registration/password_reset_form.html" %}

{% block content %}
<h1> hello </h1>
{% endblock %}

enter image description here

另外,如果你自己的模板文件根本没有被读取,请确保你的应用程序在 INSTALLED_APPS 在里面 settings.py TEMPLATES 'APP_DIRS': True DIRS 正确设置。

6 年前
回复了 Gasanov 创建的主题 » M2M Django在遵循教程后的实现

您没有在提取的对象中引用M2M字段。你需要解决 sample 字段如下:

型号.py:

@classmethod
def add_to_container(cls, current_container, new_sample):
    containerContents, created = cls.objects.get_or_create(
        current_container=current_container
    )
    containerContents.sample.add(new_sample)

@classmethod
def remove_from_container(cls, current_container, new_sample):
    containerContents, created = cls.objects.get_or_create(
        current_container=current_container
    )
    containerContents.sample.remove(new_sample)

并为模型方法设置适当的变量:

视图.py

def change_container(request, operation, pk, fk='', sample_id=''):
    container = Container.objects.get(pk=pk)
    sample = Sample.objects.get(pk=fk)
    # sample = Container.objects.get(container.sample_id=sample_id)
    if operation == 'add':
        ContainerContents.add_to_container(container, sample)
    elif operation == 'remove':
        ContainerContents.remove_from_container(container, sample)

    return redirect('depot:allcontainer')