我想从类方法重定向到url

时间:2019-05-23 06:10:19

标签: django

我有Source_page和Target_Page应用程序。在Source_page应用程序视图中,我使用表单来选择“数据库”,“架构”和“表”下拉列表,并且每个下拉列表均在选择一个之后出现。

有一个TableStructure类需要在选择一个表进行某些处理后调用。这些过程完成后,我要重定向URL“ / targetSource /”。

有人可以帮忙吗?这是代码文件

Views.py

class DBForm(forms.Form):
    database = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['database'].choices = self._get_databases()

    def _get_databases(self):
        self.pgObj = Postgres(server="localhost",user="postgres",password="*****",port=5433)
        dbList = self.pgObj.connect()
        dbChoiceList = getChoiceList(dbList)
        return dbChoiceList


class SchemaForm(DBForm):
    schema = forms.ChoiceField()

    def __init__(self, database, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['database'].initial = database
        # self.fields['database'].widget.attrs['disabled'] = True
        self.fields['schema'].choices = self._get_schemas(database)

    def _get_schemas(self, database):
        # TODO Do NOT forget to escape "database" here to prevent injections
        schemaList= self.pgObj.schemaList(database)
        schema = getChoiceList(schemaList)
        return schema


class TableForm(SchemaForm):
    table = forms.ChoiceField()

    def __init__(self, database, schema, *args, **kwargs):
        super().__init__(database, *args, **kwargs)
        self.fields['schema'].initial = schema
        # self.fields['schema'].widget.attrs['disabled'] = True
        self.fields['table'].choices = self._get_tables(database, schema)

    def _get_tables(self, database, schema):
        # TODO Do NOT forget to escape "database" here to prevent injections
        tableList = self.pgObj.tableList(schema)
        table = getChoiceList(tableList)
        return table


class TableStructure(TableForm):

    def __init__(self, database, schema, table, *args, **kwargs):
        super().__init__(database, schema, *args, **kwargs)
        self.fields['table'].initial = table
        self.fields['schema'].widget.attrs['disabled'] = True
        self.fields['database'].widget.attrs['disabled'] = True
        self._get_tables_structure(database, schema, table)

        # self.fields['acknowledge'].widget.attrs['disabled'] = True

    def _get_tables_structure(self,database, schema, table):
        # print("INSIDE GET TABLE STRUCTURE")
        # return HttpResponseRedirect('127.0.0.1:8000/targetSource/')
        # return redirect('http://127.0.0.1:8000/targetSource/')
        # return redirect('targetCreds') 
        data = self.pgObj.getTableData(schema, table)
        print("writing File ",table)
        data.to_csv(table+".csv", index=False,sep='|')
        print("file Wrote now mapping columns")

        COL_MAPPING_FILE = "postgresToRedshiftColMapping.csv"
        mapped_list = self.pgObj.get_ColMapped(table, COL_MAPPING_FILE)
        print("Got mapped list Outside : ",mapped_list)
        pkCol  = self.pgObj.get_Primary_Key(table)
        print("Primary Key:",pkCol)
        createTabelquery = self.pgObj.createTableQuery(mapped_list,table,pkCol)
        print(createTabelquery)
        selectedTable = dict()
        selectedTable['table']=[table]
        selectedTable['createTableQuery']=createTabelquery
        selectedTable = json.dumps(selectedTable)
        file = open("SelectedTable.json", 'w', encoding='utf-8')
        file.write(selectedTable)






class TestView(generic.FormView):
    template_name = 'source_database/test.html'
    # template_name = 'source_database/selectTables.html'
    def get_form(self, form_class=None):
        kwargs = self.get_form_kwargs()
        database = self.kwargs.get('database')
        schema = self.kwargs.get('schema')
        table = self.kwargs.get('table')
        if table:
            print("Inside get_form table")
            return TableStructure(table=table,schema=schema,database=database, **kwargs)
        if schema:
            print("Inside get_form schema")
            return TableForm(schema=schema,database=database, **kwargs)
        if database:
            print("Inside get_form database")
            return SchemaForm(database=database, **kwargs)
        return DBForm(**kwargs)

    def form_valid(self, form):
        database = form.cleaned_data.get('database')
        schema = form.cleaned_data.get('schema')
        table = form.cleaned_data.get('table')

            # return redirect('targetCreds')
        if table:
            return HttpResponseRedirect(reverse('data', kwargs={'schema': schema, 'database': database, 'table': table}))
        if schema:
            print("Inside form_valid schema")  
            return HttpResponseRedirect(reverse('test', kwargs={'schema': schema, 'database': database}))
        if database:
            print("Inside form_valid database") 
            return HttpResponseRedirect(reverse('test', kwargs={'database': database}))
        return HttpResponseRedirect(reverse('test'))

url.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('profile/', user_views.profile, name='profile'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('form/', sourceform_view.resource, name='resources'),
    # path('tables/', sourceform_view.select_tables, name="tables"),
    path('blogs/', include('blog.urls')),
    path('',auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('tables/', sourceform_view.TestView.as_view(), name='test'),
    path('tables/<str:database>/', sourceform_view.TestView.as_view(), name='test'),
    path('tables/<str:database>/<str:schema>/', sourceform_view.TestView.as_view(), name='test'),
    path('tables/<str:database>/<str:schema>/<str:table>', sourceform_view.TestView.as_view(), name='data'),
    path('targetSource/', targetform_view.target, name='targetCreds'),
    path('targetSource/process/', targetform_view.process, name='targetProcess'),
] 

template test.html

{% extends "blog/layout.html" %} 
{% load crispy_forms_tags %}
{% block content %}
    <form name ='xyz' method="post"  onchange="xyz.submit();">
        {% csrf_token %}
        {{ form.as_p }}
        <!-- <input type="submit" value="Submit"/> -->
    </form> 
{% endblock content %}
''

1 个答案:

答案 0 :(得分:0)

首先,您对Django's FormView类有错误的理解。通常的重定向应该通过form_valid()form_invalid()方法进行。 get_form()负责创建您的Form类的实例,仅此而已。最好的方法是在TableStructure(table=table,schema=schema,database=database, **kwargs)方法内创建form_valid()对象,然后制作HttpResponseRedirect。但您可以这样做,

class TestView(generic.FormView):
    template_name = 'source_database/test.html'
    form_class = YourFormClassHere # + Add your form class here
    # template_name = 'source_database/selectTables.html'
    def get_form(self, form_class=None):
        my_form = super(TestView, self).get_form() # +
        kwargs = self.get_form_kwargs()
        database = self.kwargs.get('database')
        schema = self.kwargs.get('schema')
        table = self.kwargs.get('table')
        if table:
            print("Inside get_form table")
            table_structure = TableStructure(table=table,schema=schema,database=database, **kwargs)
            self.form_valid(my_form) # +
        if schema:
            print("Inside get_form schema")
            return TableForm(schema=schema,database=database, **kwargs)
        if database:
            print("Inside get_form database")
            return SchemaForm(database=database, **kwargs)
        return DBForm(**kwargs)

    def form_valid(self, form):
        database = form.cleaned_data.get('database')
        schema = form.cleaned_data.get('schema')
        table = form.cleaned_data.get('table')

            # return redirect('targetCreds')
        if table:
            return HttpResponseRedirect(reverse('data', kwargs={'schema': schema, 'database': database, 'table': table}))
        if schema:
            print("Inside form_valid schema")  
            return HttpResponseRedirect(reverse('test', kwargs={'schema': schema, 'database': database}))
        if database:
            print("Inside form_valid database") 
            return HttpResponseRedirect(reverse('test', kwargs={'database': database}))
        return HttpResponseRedirect(reverse('test'))

测试此代码。