Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
epswing
Nov 4, 2003

Soiled Meat

Thermopyle posted:

If your SPA request doesn't send cookies, then SessionAuthentication will be avoided.

OK I'll pass that along.

Thermopyle posted:

If you're using fetch to do your requests on the frontend look into the credentials config on requests.

I don't know what this means. Will my frontend guy know what this means?

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

epalm posted:

I don't know what this means. Will my frontend guy know what this means?

Yes.

When you're doing requests from javascript in the browser you have to be sure to not send cookies. fetch is the browser-native library for doing requests with JS, and the credentials option is how you configure that.

huhu
Feb 24, 2006
code:
class Project(models.Model):
    name = models.CharField(max_length=200, unique=True)
    description = models.TextField(blank=True, null=True)

class Author(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()

class Link(models.Model):
    name = models.CharField(max_length=200)
    src = models.URLField(blank=True, null=True)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name='link')
    author = models.ForeignKey(Author, on_delete=models.CASCADE, blank=True, null=True, related_name='link')
I have these three models. Each Project and Author can have several links attached to them. I'm a bit confused why Django wants me to put the foreignkey field on the Link. I imagine there's a better way to write this, if so, how? If not, why is it setup that way?

porksmash
Sep 30, 2008
I think you actually want a many-to-many with a Through model: https://docs.djangoproject.com/en/2.0/topics/db/models/#extra-fields-on-many-to-many-relationships

epswing
Nov 4, 2003

Soiled Meat
When using httpie to make a GET request to DRF, even though I specify the Accept: application/json header, if there's a 500 error on the server, the response dumps a ton of html into my shell.

How can I avoid this, and just get the error response in json?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

epalm posted:

When using httpie to make a GET request to DRF, even though I specify the Accept: application/json header, if there's a 500 error on the server, the response dumps a ton of html into my shell.

How can I avoid this, and just get the error response in json?
If I remember correctly you can set the JSON renderer as the default renderer so that even error responses get returned as JSON: http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers

epswing
Nov 4, 2003

Soiled Meat

IAmKale posted:

If I remember correctly you can set the JSON renderer as the default renderer so that even error responses get returned as JSON: http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers

I've tried DEFAULT_RENDERER_CLASSES with/without JSONRenderer, no change. I thought that would work.

Regardless, shouldn't adding Accept: application/json to the request do it?

epswing fucked around with this message at 02:55 on Mar 26, 2018

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.
What's handling the 500? Previously I've had to write a custom exception handler because the exception was being thrown up to django, causing the default django error page to be shown instead of handling it within DRF and returning an appropriate response.

See the second paragraph in the custom handler docs here for a less word salad explanation of what I'm talking about : http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

ickbar
Mar 8, 2005
Cannonfodder #35578
Hello, I'm new to web development, and I'm trying to create a database driven website involving making transactions similar to an eccomerce site but for a nonprofit. Though I am stepping through a tutorial just to gain some familiarity first...

It was between node.js or using django as a backend, and from my research django seems to be more appropriate and is better for getting something up quick, with an admin panel to boot. And it seems like I might have to use mySQL or postgres,

I'm still unfamiliar with a lot of things like setting up databases, and my only exposure is using SQLite for Android so my question is going to be very noobish. But in order to use something other than SQL lite, like postgres, what are the general steps to connect it to django on my computer?

I've installed a postgres sql package for windows enterprise grade 'edb', but a little bit lost as were to proceed .

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

ickbar posted:

Hello, I'm new to web development, and I'm trying to create a database driven website involving making transactions similar to an eccomerce site but for a nonprofit. Though I am stepping through a tutorial just to gain some familiarity first...

It was between node.js or using django as a backend, and from my research django seems to be more appropriate and is better for getting something up quick, with an admin panel to boot. And it seems like I might have to use mySQL or postgres,

I'm still unfamiliar with a lot of things like setting up databases, and my only exposure is using SQLite for Android so my question is going to be very noobish. But in order to use something other than SQL lite, like postgres, what are the general steps to connect it to django on my computer?

I've installed a postgres sql package for windows enterprise grade 'edb', but a little bit lost as were to proceed .

I don't know the specifics for Windows but, generally, you'll need to make a database w/ a user and a password on your machine. Then do this https://docs.djangoproject.com/en/2.0/ref/settings/#databases with your local db info. When you deploy this to some server you'll need to make sure the DATABASES config knows how to look for the db you set up in that environment. There are approximately a trillion strategies for that.

I'll additionally say that while this is a good thing to be doing in order to learn this stuff, I would personally be pretty weary of rolling my own ecommerce site were I you unless I had an exceptionally good reason to be doing so.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

ickbar posted:

Hello, I'm new to web development, and I'm trying to create a database driven website involving making transactions similar to an eccomerce site but for a nonprofit. Though I am stepping through a tutorial just to gain some familiarity first...

It was between node.js or using django as a backend, and from my research django seems to be more appropriate and is better for getting something up quick, with an admin panel to boot. And it seems like I might have to use mySQL or postgres,

I'm still unfamiliar with a lot of things like setting up databases, and my only exposure is using SQLite for Android so my question is going to be very noobish. But in order to use something other than SQL lite, like postgres, what are the general steps to connect it to django on my computer?

I've installed a postgres sql package for windows enterprise grade 'edb', but a little bit lost as were to proceed .

Install Postgres

Then you have to do createdb mydatabase.

Then you configure Django's settings.py like so:

Python code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
Simple as that. (haha, I'm sure I'm forgetting something)

hanyolo
Jul 18, 2013
I am an employee of the Microsoft Gaming Division and they pay me to defend the Xbox One on the Something Awful Forums
How do I pass an Model instance (or preferably the models pk) between forms/views?

For example if i wanted a two part form where you selected the country first (dropdown of existing objects), and then based on the country selected the second form would filter the list of cities based on the country.

I've tried storing it in the session then doing a redirect to the second view, i.e:

code:
if countryform.is_valid():
    request.session['country'] = countryform.cleaned_data
    return redirect("app:form2")
But a session won't take a dictionary (not JSON serialisable). There must be a way I can just put the pk in the session but I can't figure it out for the life of me.

I know you can put it in the URL and there are plenty of existing solutions for country/city but I'm trying to pass a bunch of data through where I don't think a massive URL would be suitable.

Edit: using crispy-forms in case there is a way to do it in there

hanyolo fucked around with this message at 23:36 on Mar 27, 2018

Fluue
Jan 2, 2008

hanyolo posted:

How do I pass an Model instance (or preferably the models pk) between forms/views?

For example if i wanted a two part form where you selected the country first (dropdown of existing objects), and then based on the country selected the second form would filter the list of cities based on the country.

I've tried storing it in the session then doing a redirect to the second view, i.e:

code:
if countryform.is_valid():
    request.session['country'] = countryform.cleaned_data
    return redirect("app:form2")
But a session won't take a dictionary (not JSON serialisable). There must be a way I can just put the pk in the session but I can't figure it out for the life of me.

I know you can put it in the URL and there are plenty of existing solutions for country/city but I'm trying to pass a bunch of data through where I don't think a massive URL would be suitable.

Edit: using crispy-forms in case there is a way to do it in there

How do you populate the dropdown with countries? You could probably do something like
code:
if countryform.is_valid():
    request.session['country'] = countryform.cleaned_data['name_of_country_dropdown_field']
    return redirect("app:form2")
Which takes the value of the field with that name ("key") instead of the entire form.

hanyolo
Jul 18, 2013
I am an employee of the Microsoft Gaming Division and they pay me to defend the Xbox One on the Something Awful Forums

Fluue posted:

How do you populate the dropdown with countries? You could probably do something like
code:
if countryform.is_valid():
    request.session['country'] = countryform.cleaned_data['name_of_country_dropdown_field']
    return redirect("app:form2")
Which takes the value of the field with that name ("key") instead of the entire form.

Yeah I have also tried with selecting the specific charfield (name_text in my instance) and it still comes back as a dict. Also tried using .id and .pk with no luck. Form looks like the below:

code:
class CreateBaseCountryForm(forms.ModelForm):

    name_text = forms.ModelChoiceField(
        label = "Country",
        queryset = None,
        help_text = "Select Country from list",
        required = True,
    )

    class Meta:
        model = Country
        fields = ['name_text']

    def __init__(self, *args, **kwargs):
        super(CreateBaseCountryForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-CreateBaseCountryForm'
        self.helper.form_class = 'blueForms'
        self.fields['name_text'].queryset = Country.objects.all()
Edit: Hmm actually

code:
countryform.cleaned_data['name_text'].pk
Seems to have gotten me to the next part of the form, hopefully this works :)

hanyolo fucked around with this message at 00:04 on Mar 28, 2018

ickbar
Mar 8, 2005
Cannonfodder #35578

The March Hare posted:

I don't know the specifics for Windows but, generally, you'll need to make a database w/ a user and a password on your machine. Then do this https://docs.djangoproject.com/en/2.0/ref/settings/#databases with your local db info. When you deploy this to some server you'll need to make sure the DATABASES config knows how to look for the db you set up in that environment. There are approximately a trillion strategies for that.

I'll additionally say that while this is a good thing to be doing in order to learn this stuff, I would personally be pretty weary of rolling my own ecommerce site were I you unless I had an exceptionally good reason to be doing so.

Thanks so much for the information guys, I'm still researching just the basics right now and learning python more in depth (eventually I plan to learn data science). So I consider this mainly to be a learning experience.

Bonxai
May 2, 2011
Does anyone have experience deploying a Django site on Windows 7 with Apache and mod_wsgi? I was asked to make a site for my boss's boss's boss and I have no clue what I'm doing in terms of deployment.

IT gave us a virtual machine with Win 7 to host it on, and I'm getting errors in the Apache error log with wsgi (the exact error is "target wsgi script cannot be loaded as Python module"). I'm using Python 3.6, Apache 2.4, and wsgi_mod version 4.5.24 because apparently versions after that don't work on Windows. I can give more details if needed, it's just that SA is blocked at work so I have to type this on my phone.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Bonxai posted:

Does anyone have experience deploying a Django site on Windows 7 with Apache and mod_wsgi? I was asked to make a site for my boss's boss's boss and I have no clue what I'm doing in terms of deployment.

IT gave us a virtual machine with Win 7 to host it on, and I'm getting errors in the Apache error log with wsgi (the exact error is "target wsgi script cannot be loaded as Python module"). I'm using Python 3.6, Apache 2.4, and wsgi_mod version 4.5.24 because apparently versions after that don't work on Windows. I can give more details if needed, it's just that SA is blocked at work so I have to type this on my phone.

Install a linux VM on that Win 7 VM to host your Django site!

(i can't actually help you, but I was a little weirded out by an IT department giving you a Win7 machine to host a site with)

Bonxai
May 2, 2011

Thermopyle posted:

Install a linux VM on that Win 7 VM to host your Django site!

(i can't actually help you, but I was a little weirded out by an IT department giving you a Win7 machine to host a site with)

Me too... According to a co-worker, IT here doesn't have a lot of experience with anything Linux (I work at one of those companies where everyone has had their job since before computers were invented). I might have to ask them to reinstall the OS and switch if I can't get this working though.

epswing
Nov 4, 2003

Soiled Meat

Bonxai posted:

Does anyone have experience deploying a Django site on Windows 7 with Apache and mod_wsgi? I was asked to make a site for my boss's boss's boss and I have no clue what I'm doing in terms of deployment.

IT gave us a virtual machine with Win 7 to host it on, and I'm getting errors in the Apache error log with wsgi (the exact error is "target wsgi script cannot be loaded as Python module"). I'm using Python 3.6, Apache 2.4, and wsgi_mod version 4.5.24 because apparently versions after that don't work on Windows. I can give more details if needed, it's just that SA is blocked at work so I have to type this on my phone.

Wow. This post evokes so many feelings and emotions :cripes:

NtotheTC
Dec 31, 2007


Bonxai posted:

Me too... According to a co-worker, IT here doesn't have a lot of experience with anything Linux (I work at one of those companies where everyone has had their job since before computers were invented). I might have to ask them to reinstall the OS and switch if I can't get this working though.

Could try containers? Docker is pretty mature these days and you can run linux containers on windows with no performance hit

The Fool
Oct 16, 2003


NtotheTC posted:

Could try containers? Docker is pretty mature these days and you can run linux containers on windows with no performance hit

Only natively supported in Windows 10.


Bonxai posted:

Does anyone have experience deploying a Django site on Windows 7 with Apache and mod_wsgi? I was asked to make a site for my boss's boss's boss and I have no clue what I'm doing in terms of deployment.

IT gave us a virtual machine with Win 7 to host it on, and I'm getting errors in the Apache error log with wsgi (the exact error is "target wsgi script cannot be loaded as Python module"). I'm using Python 3.6, Apache 2.4, and wsgi_mod version 4.5.24 because apparently versions after that don't work on Windows. I can give more details if needed, it's just that SA is blocked at work so I have to type this on my phone.

I would pay :10bux: a month out of pocket for some hosting service before building a website in that environment.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I mean I would never host a site in that environment on purpose, but there's no real reason it won't work.

There's just some config problem.

Bonxai
May 2, 2011

Thermopyle posted:

I mean I would never host a site in that environment on purpose, but there's no real reason it won't work.

There's just some config problem.

Yeah I'm getting a "so close yet so far away" feeling from this. I can't tell if the problem is with Apache's config, my Django code, or the mod_wsgi install. This is all new to me.

BaronVonVaderham
Jul 31, 2011

All hail the queen!
I'm officially stumped on this celery nonsense....

I created a "dead man switch" system for our celery tasks. Basically, we've had some tasks that get hung up and never complete, and the entire queue freezes as a result. The idea was to set up a switch that gets toggled when a super important task begins, and gets unset when it successfully completes. Then in the background the switch is checked at intervals to see if it was set a really loving long time ago, and if so, it blows us up with notifications.

I don't like the idea, but it's what they wanted....

So I got it to work using the @task_prerun and @task_postrun flags and just manually setting a value in the redis cache with the timestamp of the task starting and the task object itself. I've manually tested it and it works fine.

The problem is unit testing it. My idea was the set up a dummy task in the test file that just fails quietly when it kicks a divide by zero or something else guaranteed to explode. Then in the test we can run the dummy task, confirm the cache switch is set properly, then run the check task (usually periodic) and it should see the switch is stuck (I changed the settings variable in my setUp() to say anything over 1 second old is too old), and then do its thing.

The issue I'm running into: I can't run it asynchronously for some reason. I've altered the settings variables to enable caching and to turn off celery always eager. Redis is running and the manual .get()s hit it just fine....but the task itself doesn't run if I use .delay().

Has anyone run into this before who might have some idea what's going on (and a way around it)? I feel like I've tried every possible permutation of this test. The only thing that came close was running it synchronously, but it won't let me fail the task then or the whole test halts (but the prerun hook did its job and set the switch ok).

Or is there a trick I don't know to let the synchronous task fail (so the postrun hook doesn't hit), and yet still move on in the test?

BaronVonVaderham
Jul 31, 2011

All hail the queen!
gently caress it. I just modified my pre- and post-run hooks to use an "is_set" boolean, and have the post-run not just delete the cache key but update it. It's not ideal, it doesn't really prove that the pre-run hook does anything, but it's good enough for now (I'm testing the hooks manually in another testcase anyway, so really all that isn't tested is that the pre-run hook triggers automatically).

I found a package that lets to set up a virtual worker or something that lets you test running tasks asynchronously, but it's so buggy and useless and the guy hasn't touched it since 2014. Guess I found my new open-source project.....this feels like something that should be integrated into celery itself, but if I can get a testing suite package written I'm sure there have to be other people like me struggling with poo poo that has to be async.

Data Graham
Dec 28, 2009

📈📊🍪😋



Celery is so depressing. Sorry I couldn't help, your use case was just outside the realm of what I've successfully dealt with.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I never use Celery anymore because as a result of it being very powerful, it's over-configurable.

I just use python-rq instead.

BaronVonVaderham
Jul 31, 2011

All hail the queen!
I really don't like it, but everyone I've worked for loves it.

At my last job my first project was to convert their entire SQS workflow into Celery tasks (I will say the Chord functionality for batching tasks and having a single callback for when the whole thing finishes was really, really useful when you're processing like 10k entities then running an overall performance report).

Here, they already had Celery in place, but it's been failing primarily because they run EVERYTHING in one monolithic docker container, so they keep running out of resources. I just finished converting everything into a multi-container environment so one domino falling doesn't take down the whole setup anymore. I hate how fragile celerybeat is.

The lesson I learned is remove the word "Celery" from my resume, because everywhere I go this poo poo is brewing for months accruing massive tech debt and they're just waiting to dump it on the new guy.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm using DRF. I have an "Entry" model with a ForeignKey field to a "Translation" model. I've discovered that a user can create an Entry while supplying a Translation pk that the user does not have access to.

At what level would I check that the specified Translation is one that the user can access? The Entry model's serializer?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

IAmKale posted:

I'm using DRF. I have an "Entry" model with a ForeignKey field to a "Translation" model. I've discovered that a user can create an Entry while supplying a Translation pk that the user does not have access to.

At what level would I check that the specified Translation is one that the user can access? The Entry model's serializer?

You should do database model consistency checks at the model's clean or save method.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Thermopyle posted:

You should do database model consistency checks at the model's clean or save method.
Well this is tricky. clean() doesn't fire when save() is called, so I could validate the Translation PK when an Entry is first created, but not when it's updated. And from what I can tell save() lacks a way of returning a ValidationError like I can in clean() so I don't really have a way to say, on edit, that the given Translation pk is invalid. Am I misreading the docs?

MonkeyMaker
May 22, 2006

What's your poison, sir?
Foreign keys have limit_choices_to which can be used to...limit the choices...that can be linked to with the FK. Not sure exactly how you'd want to approach it, but it should be possible to use the requesting user to set this limit.

Otherwise, seems like a thing to do in the queryset for Translations. I think that'll stop them from being able to link to an object they don't have access to.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

IAmKale posted:

Well this is tricky. clean() doesn't fire when save() is called, so I could validate the Translation PK when an Entry is first created, but not when it's updated. And from what I can tell save() lacks a way of returning a ValidationError like I can in clean() so I don't really have a way to say, on edit, that the given Translation pk is invalid. Am I misreading the docs?

You just call full_clean from your save method, then clean will be called. This is pretty common.

https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.full_clean posted:

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually ...

You'll find examples like this all over the interwebs:

Python code:
class ValidateModelMixin(object):

    """Make :meth:`save` call :meth:`full_clean`.
    .. warning:
        This should be the left-most mixin/super-class of a model.
    Do you think Django models ``save`` method will validate all fields
    (i.e. call ``full_clean``) before saving or any time at all? Wrong!
    I discovered this awful truth when I couldn't understand why
    a model object with an email field (without `blank=True`) could be
    saved with an empty string as email address.
    More info:
    * "Why doesn't django's model.save() call full clean?"
        [url]http://stackoverflow.com/questions/4441539/[/url]
    * "Model docs imply that ModelForm will call Model.full_clean(),
        but it won't."
        [url]https://code.djangoproject.com/ticket/13100[/url]
    """

    def save(self, *args, **kwargs):
        """Call :meth:`full_clean` before saving."""
        self.full_clean()
        super(ValidateModelMixin, self).save(*args, **kwargs)
It's kinda bullshit, but it's just that way for historical reasons that I don't understand.

You'll also need to watch out for .update() and .objects.create().

I can't remember off hand what I do if I need the validation error, but I think I just call full_clean before save where I need the validation error. Kinda like you call is_valid() on a DRF serializer before saving.

But, you definitely want to do this at the lowest level possible to prevent any inconsistent data from getting into your database.

Thermopyle fucked around with this message at 23:29 on Apr 2, 2018

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Oh, I forgot to mention I try to adhere to a domain-driven design on Django projects.

Something like the person here describes.

So, the model or database level validation is a just-in-case backup to the logic you have in your services module/package.

The Fool
Oct 16, 2003


I want to use passwordless auth in a personal project, anyone have any experience with a good Django library that would help me do this?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

The Fool posted:

I want to use passwordless auth in a personal project, anyone have any experience with a good Django library that would help me do this?
If you're writing a REST API with Django Rest Framework, I had good luck going passwordless with drfpasswordless: https://github.com/aaronn/django-rest-framework-passwordless

It supports using email and SMS to authenticate via one-time codes, and offers a great deal of customization for email templates. For development I'd pair this with Django's ability to print emails to the console so you can quickly grab the codes: https://docs.djangoproject.com/en/2.0/topics/email/#console-backend

Dominoes
Sep 20, 2007

Hey dudes. Looking for wisdom on what URL to query for Django Rest tied to a Create-React-App setup.

Setup: standard, unejected CRA folder inside Django folder. Django's static and temple settings point to frontend/build. Dummy package.json in main folder that tells Heroku which node version and packages to install, then points to the real one in frontend, which commands a build on install.

Can use locally from http://localhost:8000 for Django; eg using the built frontend, admin page etc, or http://localhost:3000 for the hot-loading CRA server.

How I'm making the API calls:
JavaScript code:
axios.post(
    'http://localhost/api/search',
    {} // data
).then(//...
When loading on Heroku or locally it... queries my own local dev server! How do I set this up properly? Ie something like.

JavaScript code:
let BASE_URL = on_heroku? 'https://myapp.herokuapp.com' : 'http://localhost.com:8000'
Is this an appropriate solution, and if so, how do I let the frontend determine if we're on heroku? Tutorials online demonstrate calls to process.env, or 'http://0.0.0.0', which I can't get working.

edit: Trying something like this:
JavaScript code:
const HOSTNAME = window && window.location && window.location.hostname

let ON_HEROKU = false
if (HOSTNAME === 'myapp.herokuapp.com' || HOSTNAME === 'mydomain.org') {
    ON_HEROKU = true
}

export const BASE_URL = ON_HEROKU ? 'https://readseek.herokuapp.com/api/' : 'localhost:8000/api/'

Dominoes fucked around with this message at 13:13 on Apr 14, 2018

porksmash
Sep 30, 2008
I did it like this:

code:
const API_ROOT =  process.env.NODE_ENV === 'development' ? '/api/v2/' : 'https://swarfarm.com/api/v2/';
Edit: I should probably add so it's clear - this decision is made during your CRA build process.

porksmash fucked around with this message at 16:39 on Apr 14, 2018

Fluue
Jan 2, 2008

Thermopyle posted:

Oh, I forgot to mention I try to adhere to a domain-driven design on Django projects.

Something like the person here describes.

So, the model or database level validation is a just-in-case backup to the logic you have in your services module/package.

Going back to this for a question:

I work on an application that interfaces with another vendor's API that essentially acts as the data store for 98% of the data in the application. There are a few Django models for user auth and one for dealing with the primary "business object." What I've done so far is add some memoization on the primary business object model that does a per-instance cache of values retrieved from the vendor API.

E.g.
code:
class SomeModel(models.Model):
	some_django_db_field = models.CharField()
	...
	etc

	@property
	def field_from_api(self):
		if self._field_from_api is not None:
			return self._field_from_api
		
		self._field_from_api = self.api.load_some_data(self.business_model_id)
		return self._field_from_api
Should I instead move these @property values into a model manager method? I believe the original intention was to leverage Django-rest-framework's ModelSerializers but changes to the vendor API has led us to move away from that. Additionally, a lot of the data commits are actually done to the vendor's API/data store so we end up calling the API to save data most of the time anyways.

Is this a good case for DDD/using repositories instead?

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Fluue posted:

Going back to this for a question:

I work on an application that interfaces with another vendor's API that essentially acts as the data store for 98% of the data in the application. There are a few Django models for user auth and one for dealing with the primary "business object." What I've done so far is add some memoization on the primary business object model that does a per-instance cache of values retrieved from the vendor API.

E.g.
code:
class SomeModel(models.Model):
	some_django_db_field = models.CharField()
	...
	etc

	@property
	def field_from_api(self):
		if self._field_from_api is not None:
			return self._field_from_api
		
		self._field_from_api = self.api.load_some_data(self.business_model_id)
		return self._field_from_api
Should I instead move these @property values into a model manager method? I believe the original intention was to leverage Django-rest-framework's ModelSerializers but changes to the vendor API has led us to move away from that. Additionally, a lot of the data commits are actually done to the vendor's API/data store so we end up calling the API to save data most of the time anyways.

Is this a good case for DDD/using repositories instead?

The goal of DDD is largely about helping you understand your own codebase when the business logic gets too complicated. Sure, if I was designing from scratch, I'd probably do all api requests and caching from a services module, but if you're not having a hard time with the complexity I think I'd leave them where they are but use django's @cached_property decorator and not worry about caching the values on the object instance myself.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply