0

I'm trying to create an app with a form that when submitted, updates a table in my database based on the info submitted, but I'm not sure how to go about it. Currently, I have a simple mode:

class Client(models.Model):
    company_name = models.CharField(max_length=200)
    launchpad_id = models.PositiveIntegerField()
    client_email = models.EmailField()
    content_id = models.CharField(max_length=200)

    def __str__(self):
        return self.company_name + ' | ' + self.content_id

and my databases configured like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_project',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxxx',
        'PORT': 'xxx',
    },
    'info': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'reporting_database',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}

What I want to happen is when I submit my fields through the Client model either in admin or a template, it updates my client_info table in the reporting_database. I cant seem to figure out how to make that connection work though. I would appreciate any direction you can give me. Thanks.

dataatallured
  • 33
  • 1
  • 7

4 Answers4

0

You need to have a funx that makes it possible to create or update Model. You can follow the django doc: https://docs.djangoproject.com/en/2.1/ref/models/instances/

Dori
  • 175
  • 16
0

Use a model form:

from your_app import Client

class ClientUpdateForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ('company_name', 'launchpad_id', 'client_email', 'content_id')

    def __init__(self, *args, **kwargs):
        super(ClientUpdateForm, self).__init__(*args, **kwargs)
        self.fields['company_name'].required  = True
        self.fields['launchpad_id'].required  = True
        self.fields['client_email'].required  = True
        self.fields['content_id'].required  = True

    def clean(self):
        cleaned_data = super(ClientUpdateForm, self).clean()
        company_name = cleaned_data.get('company_name')
        launchpad_id = cleaned_data.get('launchpad_id')
        client_email = cleaned_data.get('client_email')
        content_id = cleaned_data.get('content_id')

Then inherit from UpdateView:

from django.views.generic import UpdateView
from your_app import Client

class ClientUpdateForm(UpdateView):
    model = Client
    form_class = ClientUpdateForm
    template_name_suffix = '_update_form'

    def form_valid(self, form):
        if form.is_valid():
            client = form.save(commit=False)
            client.save()
            return HttpResponseRedirect('/redirect/')

The template_name_suffix means you should call your template where you render the form client_update_form.html.

0

I think you need a database_router for this. Hold https://docs.djangoproject.com/en/2.1/topics/db/multi-db/. Basically you need to set up a DatabaseRouter where you set up from which database you will read the model table ecc. then set your Custom database route in django settings. And you will probably need to run migration for this model with something like this ./manage.py migrate myapp 0005_migration_to_run --databse=your_target_databse_name, I would probably recommend you having different apps inside project per database for take it easier.

slqq
  • 245
  • 2
  • 3
  • 13
0

I was able to achieve my desired results by adding the following code to my model:

def update_mysql(self):
    cursor = db.cursor()
    sql = "UPDATE tb_reporting_info SET client_email = '%s' WHERE content_id = '%s' AND launchpad_id = '%s';"
    cursor.execute( sql % (self.client_email, self.content_id, self.launchpad_id))
    db.commit()

I set my form action to action="{% url 'contact:addClient' %}" and my view to:

def addClient(request):
    if request.method == 'POST':
        # Set POST data to variables
        company_name = request.POST['company_name']
        launchpad_id = request.POST['launchpad_id']
        content_id = request.POST['content_id']
        client_email = request.POST['client_email']
        client_added = True  # Tells the template to render a success message

        # Pass POST data to Client object
        c = Client(company_name = company_name,
                launchpad_id = launchpad_id,
                content_id = content_id,
                client_email = client_email
                )
        c.update_mysql()

It's bare bones but it works perfectly for what I need.

dataatallured
  • 33
  • 1
  • 7