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:

Anyone bought Two Scoops for 1.11 yet?

Enough new info for the price of upgrading from the 1.8 version?

In Two Scoops of Django 1.11, the chapter dealing with "When Django Rest Framework gets in the way", specifically section 16.4.2 "Problems With Complex Data", they talk about the scenario when you've got Cone and Scoop models, where Scoops are represented within a Cone (standard one-to-many relationship, each Cone contains zero or more Scoops). Basically they say that while there are complex ways to deal with PUT/POSTing a Cone that contains Scoops (especially hairy in the case of PUT, where some Scoops have been added, others modified, and others removed), the right thing to do is just not deal with it.

Basically instead of this:
code:
/api/cones/        # GET, POST
/api/cones/:uuid/  # PUT, DELETE

/api/scoops/       # GET, POST
/api/scoops/:uuid/ # PUT, DELETE
They recommend providing additional endpoints like this:
code:
/api/cones/        # GET, POST
/api/cones/:uuid/  # PUT, DELETE

/api/cones/:uuid/scoops/       # GET, POST
/api/cones/:uuid/scoops/:uuid  # PUT, DELETE

/api/scoops/       # GET, POST
/api/scoops/:uuid/ # PUT, DELETE
In other words, make separate API calls to add/modify/remove Scoops from a Cone. I agree that this does simplify your API (and your tests), however I have some problems/questions with this.

One can imagine a common UI for this looks roughly like a Cone edit page/window, with a list of Scoop items that can be dynamically added/modified/removed, and a Save button. Using the method they recommend, before the Save button is tapped/clicked, whatever modifications to the parent object and its children would have to be tracked in the UI (we haven't submitted anything to the server yet). When the Save button is tapped/clicked, the UI would have to make N+1 calls to the server to fully save the children and its parent.

Yes I've simplified my API and the work the server needs to do, but haven't I just pushed that complexity down onto my UI?

What if one of those calls failed? Users expect the Save button to be atomic. Should the client undo all previous calls before the failure to get back to where we were before Save was executed? Haven't I lost the atomicity of my Save button?

Edit: Basically I'm looking for the functionality of formsets when using standard Django templates. I can load up a parent and it's children in html, make all sorts of modifications, and POST the whole thing to the server. On the server side, I just do
Python code:
with transaction.atomic():
    myform.save()
    myformset.save()
and I'm done, everything is handled for me.

epswing fucked around with this message at 15:46 on Oct 5, 2017

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

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

Basically, it's a hairy problem no matter which end you deal with it on.

My thought on the matter is that the client is the one who knows what the client is intending to do, so the client should be the one to express that intent by creating objects in the correct order.

Like all rules of thumb this is just a guideline. If you have a hard business requirement that a cone should never exist without scoops, you might want to pull that logic into your views and deal with the headache of updating with nested objects.

Another rule of thumb is that I almost always find the backend logic for dealing with nested updates more complicated than the frontend logic of doing multiple requests to build up your objects.

In the Cone/Scoops scenario I would go with multiple frontend requests.

You could even have a flag on your database models that says "this model belongs to a Cone/Scoop that is under construction" and then require your frontend to POST to some url like /cone-is-complete. That way you could vacuum up cones and scoops that got orphaned because of incomplete creation every once in awhile.

Thermopyle
Jul 1, 2003

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

epalm posted:

I hear you re: github stars. Hard to top a thriving community. When looking for 3rd party apps, the first thing I look at tends to be "date of last commit" on GitHub/BitBucket/etc.

RQ looks interesting, however after reading their Docs section, there's one part I don't understand: how do you start the worker process in production? The Starting workers page shows an example running $ rq worker, but... obviously I'm not going to leave an ssh session running with a user logged in after running this command.

All of these task runners like python-rq and celery have worker processes. How you start and maintain those processes is a function of where you have your application deployed. If it's a regular Linux server you can use supervisord, if it's on Heroku you create additional worker processes. Other platforms all have their own thing.

epswing
Nov 4, 2003

Soiled Meat

Thermopyle posted:

In the Cone/Scoops scenario I would go with multiple frontend requests.

You could even have a flag on your database models that says "this model belongs to a Cone/Scoop that is under construction" and then require your frontend to POST to some url like /cone-is-complete. That way you could vacuum up cones and scoops that got orphaned because of incomplete creation every once in awhile.

Sure, that might work for POST. But it's really PUT that's the problem, which you didn't address.

Thermopyle
Jul 1, 2003

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

epalm posted:

Sure, that might work for POST. But it's really PUT that's the problem, which you didn't address.

It's basically the same thing.

If you're wanting to update one of your scoops, you set the flag for the cone/scoop to incomplete, do your PUTs, and set it back to complete.

epswing
Nov 4, 2003

Soiled Meat

Thermopyle posted:

It's basically the same thing.

If you're wanting to update one of your scoops, you set the flag for the cone/scoop to incomplete, do your PUTs, and set it back to complete.

You're glossing over the failure case. The user is looking at a Cone and a list of Scoops. They make changes, and click Save. One of the Scoop calls fail. You present the user with some error message. If they decide "nah I'll do this later", I can't just leave half the Scoops as "incomplete". Also, some of them might have been deleted, others added.

Again, a simpler API and multiple frontend requests seems to lose the atomicity of the Save button users are expecting. (I.e. I can't wrap multiple separate API calls in a transaction.) That's really the crux of my initial question.

epswing fucked around with this message at 16:12 on Oct 5, 2017

Thermopyle
Jul 1, 2003

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

epalm posted:

You're glossing over the failure case. The user is looking at a Cone and a list of Scoops. They make changes, and click Save. One of the Scoop calls fail. You present the user with some error message. If they decide "nah I'll do this later", I can't just leave half the Scoops as "incomplete". Also, some of them might have been deleted, others added.

Again, a simpler API and multiple frontend requests seems to lose the atomicity of the Save button users are expecting. (I.e. I can't wrap multiple separate API calls in a transaction.) That's really the crux of my initial question.

No, I'm saying it's hard no matter what you do. I'm glossing over it in the sense I'm not going to write all the logic for you.

You have to simulate the atomicity the users are expecting.

epswing
Nov 4, 2003

Soiled Meat

Thermopyle posted:

No, I'm saying it's hard no matter what you do. I'm glossing over it in the sense I'm not going to write all the logic for you.

You have to simulate the atomicity the users are expecting.

Sure it's hard, no matter if this logic resides on the server, or the client. It's just that both you, and the authors of Two Scoops, are recommending putting that logic on the client, but I'm just not seeing it with respect to users who expect an atomic Save button when editing a parent+children, which I think is most of them. That's why I'm asking, I'm not expecting anyone to do my homework for me, I'm just not yet convinced it's worth it, or even feasible. Another reason why I'm asking is because Django itself perfectly handles exactly this scenario with formsets.

Thermopyle
Jul 1, 2003

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

epalm posted:

Sure it's hard, no matter if this logic resides on the server, or the client. It's just that both you, and the authors of Two Scoops, are recommending putting that logic on the client, but I'm just not seeing it with respect to users who expect an atomic Save button when editing a parent+children, which I think is most of them. That's why I'm asking, I'm not expecting anyone to do my homework for me, I'm just not yet convinced it's worth it, or even feasible. Another reason why I'm asking is because Django itself perfectly handles exactly this scenario with formsets.

I mean, all I can really tell you without getting into writing code is basically what I've already told you. The logic to handle nested updates is not easy. If your client knows what it is updating, it's often more clear (both in code and in the sense of explicitness) for it to just tell the backend what to update.

So, the client GETs your Cone/Scoop info. The client edits one of the scoops. PUT that scoop.

If your client does not know what its updating then you've got a hairy logic problem wherever you write the code.

Like most things REST there's not a clear answer on which way is the best for all circumstances.

NtotheTC
Dec 31, 2007


My personal way of handling that cone/scoops scenario in terms of UI would be to have an "Edit Cone" page, an "Edit Scoop" page, and an "Add/Remove Scoops" page. With SPA's its not difficult or time consuming to navigate to each section and it makes it so that you never have to send edited cone information at the same time as updating the scoops on a cone.

Then your interface for updating scoops can be drag the scoops onto/off the cone, and when the drag event completes you send the request to the API, if it fails it snaps back. So you don't end up doing a bulk "ok i've arranged all my scoops now post them all" thing.

Pro-tip: Add a save button with a 1 second spinny animation that does absolutely gently caress all that your users can press at the end of all their tweaking, it'll make them feel better.

Thermopyle
Jul 1, 2003

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

NtotheTC posted:

My personal way of handling that cone/scoops scenario in terms of UI would be to have an "Edit Cone" page, an "Edit Scoop" page, and an "Add/Remove Scoops" page. With SPA's its not difficult or time consuming to navigate to each section and it makes it so that you never have to send edited cone information at the same time as updating the scoops on a cone.

Then your interface for updating scoops can be drag the scoops onto/off the cone, and when the drag event completes you send the request to the API, if it fails it snaps back. So you don't end up doing a bulk "ok i've arranged all my scoops now post them all" thing.

Pro-tip: Add a save button with a 1 second spinny animation that does absolutely gently caress all that your users can press at the end of all their tweaking, it'll make them feel better.

Oh yeah, I was going to say something about that.

The atomicity of the Save operation is as much determined by your UI design as it is by your code.

epswing
Nov 4, 2003

Soiled Meat

NtotheTC posted:

My personal way of handling that cone/scoops scenario in terms of UI would be to have an "Edit Cone" page, an "Edit Scoop" page, and an "Add/Remove Scoops" page. With SPA's its not difficult or time consuming to navigate to each section and it makes it so that you never have to send edited cone information at the same time as updating the scoops on a cone.

Then your interface for updating scoops can be drag the scoops onto/off the cone, and when the drag event completes you send the request to the API, if it fails it snaps back. So you don't end up doing a bulk "ok i've arranged all my scoops now post them all" thing.

That sounds good. The only problem I see is trying to convince the person paying for the software that "this is how your UI should work" borne not from necessarily the best UI design, but from API/server/complexity constraints that they don't know or care about. But that's a whole other can of worms. :can: :v:

NtotheTC posted:

Pro-tip: Add a save button with a 1 second spinny animation that does absolutely gently caress all that your users can press at the end of all their tweaking, it'll make them feel better.

Really dislike this, gives users the impression that if they don't click Save, none of their changes will be applied (meanwhile they've already been applied).

NtotheTC
Dec 31, 2007


epalm posted:

That sounds good. The only problem I see is trying to convince the person paying for the software that "this is how your UI should work" borne not from necessarily the best UI design, but from API/server/complexity constraints that they don't know or care about. But that's a whole other can of worms. :can: :v:

I agree with the whole tail wagging the dog concern, but I tend to find that clean, simple API/UI design tends to lend itself to good UX regardless. If someone comes to you and says "No we simply must be able to edit all this information on one page" then I guess you have to go the complex front-end logic route but if the UI reponds quickly then noone is going to mind.

epalm posted:

Really dislike this, gives users the impression that if they don't click Save, none of their changes will be applied (meanwhile they've already been applied).

Well you use it in conjunction with a "saving..." "saved" indicator that also shows as they update things one at a time, it's a silly little thing but some users just feel more comfortable with it I've found.

e: I'm being semi-facetious but UX stuff like that is actually a thing in some places

NtotheTC fucked around with this message at 18:31 on Oct 5, 2017

porksmash
Sep 30, 2008
Has anyone deployed Django to AWS Lambda? It looks pretty simple with Zappa, but I also have RabbitMQ and Celery as critical parts of my application which I have not yet figured out the best way to implement in this serverless architecture business.

Thermopyle
Jul 1, 2003

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

porksmash posted:

Has anyone deployed Django to AWS Lambda? It looks pretty simple with Zappa, but I also have RabbitMQ and Celery as critical parts of my application which I have not yet figured out the best way to implement in this serverless architecture business.

Yes, it's dope and that poo poo is the future.

RabbitMQ/Celery is not a problem, you just have to have it running on a persistent server somewhere.

Tigren
Oct 3, 2003

Thermopyle posted:

Yes, it's dope and that poo poo is the future.

RabbitMQ/Celery is not a problem, you just have to have it running on a persistent server somewhere.

Or fully embrace dat serverless lifestyle and convert your Celery/RabbitMQ to Lambda/SNS

https://github.com/Miserlou/Zappa#executing-in-response-to-aws-events

Tigren fucked around with this message at 23:41 on Oct 9, 2017

epswing
Nov 4, 2003

Soiled Meat
Another best-practice I've read in more than one place, but I'm skeptical of, is to break your site into many small Apps (where each App should be responsible for One Thing (tm)). While this sounds good, during the natural growth of a site, I always seem to get the placement of a model wrong, and moving a model from App A to App B appears to be an ill-advised, intense, manual operation. There's a trac ticket with a proposal to automate this, but it hasn't been touched in 9 months.

What do y'all do?

Edit: vvv yeah depends on the size of the project. Personally, it's happened a couple of times where the project got just big enough to warrant multiple Apps, but by that point it was too late to restructure. If moving models across Apps were easy, I feel like I'd follow this "best-practice" more often.

epswing fucked around with this message at 19:27 on Oct 14, 2017

Thermopyle
Jul 1, 2003

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

The "problem" with a lot of programming rules of thumb is that they're there to help you with situations you won't encounter until you've got large and advanced projects that require on-going maintenance. This makes it hard to understand the point of them until you've been in that situation.

Small, purposeful apps are just another way of lessening your future technical debt.

If you don't think your project is going to be large enough or require on-going maintenance, gently caress it and make a mono-app.

As to what I do...I make small apps. It's not uncommon for me to have apps with just a model or two with no views or any other logic.

grenada
Apr 20, 2013
Relax.
After working through the Mozilla Django tutorial, I have a pretty good understanding of Django's MVT way of doing things, and can make a simple CRUD app using HTML, CSS, and Python. But, I'm a bit at a loss of how to start incorporating JavaScript into my website. How do I use JavaScript to interact with Views? If an action takes place on a webpage, and I want to trigger to call a View to do something with my model data to respond to that action, and then update the page with that information?

Any good tutorials on this topic? The Django tutorials I've read don't seem to cover this. This is a big leap forward in my current knowledge, so I am probably not even articulating my question, or what I want to do properly.

Thermopyle
Jul 1, 2003

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

laxbro posted:

After working through the Mozilla Django tutorial, I have a pretty good understanding of Django's MVT way of doing things, and can make a simple CRUD app using HTML, CSS, and Python. But, I'm a bit at a loss of how to start incorporating JavaScript into my website. How do I use JavaScript to interact with Views? If an action takes place on a webpage, and I want to trigger to call a View to do something with my model data to respond to that action, and then update the page with that information?

Any good tutorials on this topic? The Django tutorials I've read don't seem to cover this. This is a big leap forward in my current knowledge, so I am probably not even articulating my question, or what I want to do properly.

This is a big leap to make, so let me just say some things and you can tell me if they help.

Generally nowadays javascript on a page interacts with your Django backend with what's called AJAX calls. So, your end user goes to your /home/ url. Your template for that page includes some javascript that makes a request to /users/7/ which gets data about the current user. Your view at /users/7/ returns data in JSON format and then your javascript edits the HTML of the page to display the data.

Javascript can also POST data and do stuff with the data your Django view returns.

Make sense? Need more info?

Data Graham
Dec 28, 2009

📈📊🍪😋



You're talking about the front-end/back-end split. Django doesn't really do anything front-end-wise; it's a back-end platform.

What it sounds like you want is to have your JS talk to a set of API endpoints and fetch/post data to act on in the front-end context. How you build that front-end is entirely outside Django's sphere (theoretically you should be able to swap in a whole different back-end with only minimal changes to your JS). But to build those API endpoints the usual way is http://www.django-rest-framework.org

You can manually build Views that serve up JSON data using vanilla Django if you prefer, but DRF gives you a full-featured and widely understood framework for exposing your models to the front-end via API calls, and it saves you most of the grunt-work of adding CRUD handling to all your views individually.

NtotheTC
Dec 31, 2007


laxbro posted:

After working through the Mozilla Django tutorial, I have a pretty good understanding of Django's MVT way of doing things, and can make a simple CRUD app using HTML, CSS, and Python. But, I'm a bit at a loss of how to start incorporating JavaScript into my website. How do I use JavaScript to interact with Views? If an action takes place on a webpage, and I want to trigger to call a View to do something with my model data to respond to that action, and then update the page with that information?

Any good tutorials on this topic? The Django tutorials I've read don't seem to cover this. This is a big leap forward in my current knowledge, so I am probably not even articulating my question, or what I want to do properly.

If you mean sending data to the server and getting a response back without refreshing the page, the main way to do that is via AJAX (Asynchronous Javascript and XML JSON, AJAJ is a bad acronym). There's quite a few tutorials out there about using AJAX with Django (this one is the first one I found).

If you want all your views to behave this way, you'll want to looking into creating an API in Django that you can consume on the front end with javascript. Django REST framework is the de facto library for creating REST APIs in Django, and has a good tutorial on the homepage.

As to what flavour of Javascript (plain jQuery, Angularjs, etc) you use to do the AJAX, that really depends on the scope of your application.

e: beaten twice

NtotheTC fucked around with this message at 20:04 on Oct 26, 2017

grenada
Apr 20, 2013
Relax.
Thanks all! Yes, AJAX & DRF is what I need. I wasn't sure if there was a stock Django way of doing this.

I made a simple, simple weather app earlier this year on codepen using AJAX calls to the wunderground API and then using JS to put the returned JSON into HTML. So essentially, I'll be making AJAX calls to my own API created with DRF? And then I will using JS to put the returned JSON back into my template?

I plan on using vanilla JavaScript as much as possible for now, but my eventual goal is to build a Django/React app.

Noob question: Is it best practice to write JS in external files in your static folder? Or do you include your JS in script tags within your template, particularly if it is JS relevant only to that template?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
It's better to have js as statics rather than embedded in the template, easier to work with, cleaner separation of responsibility.

Use the template to include the relevant script reference OR use data attributes to communicate information to the regular JavaScript so it knows what to do. Avoid generating the JavaScript through templating, there are much better workflows to use.

Data Graham
Dec 28, 2009

📈📊🍪😋



^^ What are the best-practice workflows in those cases where you otherwise would have to generate JS or CSS from back-end variables, like populating a JS var or an image URL?

... You know, for the benefit of the class. :kiddo:

Data Graham fucked around with this message at 23:05 on Oct 26, 2017

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.

Data Graham posted:

^^ What are the best-practice workflows in those cases where you otherwise would have to generate JS or CSS from back-end variables, like populating a JS var or an image URL?

... You know, for the benefit of the class. :kiddo:

There's two ways to go about this, you either split the JS into a static file and reference the data you need through data attributes on your outputted html, like this:

code:
<div data-image-you-need="{{ someImage }}" id="image"></div>
code:
// vanilla js:
var imageUrl = document.getElementById('image').getAttribute('data-image-you-need');

// jquery:
var imageUrl = $('#image').data('image-you-need');
Or if you need quite a lot of data, it might be worthwhile to get it via an http request. Without knowing your specific use case it's hard to say which one would be more appropriate, though.

Ah, I realized this doesn't touch on the CSS portion of your question, but I'm not sure what your use-case is there...

Eleeleth fucked around with this message at 23:15 on Oct 26, 2017

Data Graham
Dec 28, 2009

📈📊🍪😋



Like say I want to set the background-image of a class to an image url generated via {% static %}.

I guess I could always make an api endpoint that serves up all the variable URLs I’ll need and updates the classes’ CSS programmatically, but that sure seems like a lot of round trips and subterfuge just to avoid inlining some snippets of css in my base.html. (Plus I wouldn’t be able to benefit from {% static %} directly, which is kinda the whole point.)

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.
In that case, can't you just use relative urls?

If you're resolving main.css and someImage.png with {% static %} you should be able to just use ./someImage.png

Maybe I'm missing something here?

e: If you *absolutely must* use {% static %} to resolve the absolute url here, you can just pipe only that stuff through a django view and be extremely careful to set caching headers, but I would consider that a hacky gross last resort.

e2: https://docs.djangoproject.com/en/1.11/intro/tutorial06/#adding-a-background-image The warning in this section of the django docs also calls out using relative paths between static assets as a best practice (although it's not mentioned elsewhere)

Eleeleth fucked around with this message at 23:46 on Oct 26, 2017

Data Graham
Dec 28, 2009

📈📊🍪😋



Hmm, good point. I guess I found myself wanting to keep path independence between my css and images dirs in case I wanted to move things around, but then I’d be updating all the prefixes anyway. It’s not like you can have multiple static roots. Thanks

Hed
Mar 31, 2004

Fun Shoe

Thermopyle posted:

Yes, it's dope and that poo poo is the future.

RabbitMQ/Celery is not a problem, you just have to have it running on a persistent server somewhere.

This looks neat but I'm having trouble figuring out where the persistent store of data is in a stateless thing like this. Do you bring up Amazon RDS and then all your lambda workers query that? Do you have to start optimizing for instantiation time now that overhead of spinning up your request (e.g. loading modules) is non-negligible?

Thermopyle
Jul 1, 2003

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

Hed posted:

This looks neat but I'm having trouble figuring out where the persistent store of data is in a stateless thing like this. Do you bring up Amazon RDS and then all your lambda workers query that? Do you have to start optimizing for instantiation time now that overhead of spinning up your request (e.g. loading modules) is non-negligible?

Yeah, you just use some service whether it's Amazon or whatever to store your data.

Generally speaking I don't think need to optimize for anything special because you can keep your function warm and even if not it's not a lot of time in the context of web requests.

Data Graham
Dec 28, 2009

📈📊🍪😋



I'm having a dumbass evening and I can't stay up any later beating my head against this one, so I'll throw it out to you guys in case anyone's seen this before.

I'm trying to upload a file (field name "picture") via AJAX to an UpdateView. The picture is on a model called Claim, which has a ForeignKey member called Offer.

code:
class UploadClaimView(UpdateView):
    model = models.Claim
    form_class = forms.ClaimForm
    template_name = 'includes/claim.html'

    def get_object(self):
        claim = get_object_or_404(models.Claim, pk=self.kwargs['claim_id'])
        logger.info(claim.id)
        logger.info(claim.offer.id)
        logger.info(claim.comment)
        return claim

    def form_valid(self, form):
        logger.info(self.object.id)
        logger.info(self.object.comment)
        logger.info(self.object.offer)
        logger.info(self.request.POST)
        logger.info(self.request.FILES)
        self.object.picture = self.request.FILES['picture']
        ... other stuff beyond here


class ClaimForm(forms.ModelForm):
    
    class Meta:
        model = models.Claim
        fields = ['picture']
As you can see, I'm basically just logging my brains out here because I don't get what's going on. My get_object method finds the Claim object just fine, and when I log the values of offer, comment, and other fields, they're present and accounted for. But then in form_valid, when I log those same fields, they're null. The object itself exists, it has the right id, but the comment and offer fields are gone.

I've tried adding the fields as attributes in the form class (and the fields list too), but that doesn't make a difference.

The end result of all this is that the only field that gets saved properly in my form_valid method is the picture, because I'm setting it manually from self.request.FILES. All the other fields get blanked out.

What the hell? What's going on between get_object and form_valid that clears out all the attributes from my Claim object?

Data Graham
Dec 28, 2009

📈📊🍪😋



Never mind my late-night dumbassery; I was using the wrong form, one which had additional fields listed like comment and offer, so they were being cleaned as null :doh:

huhu
Feb 24, 2006
I've got a project with React frontend DRF backend. I keep getting the following error intermittently across different endpoints. Sometimes, for example, /users/me will load, and other times it'll error out.
code:
Failed to load [url]https://api.foo.com/users/me/:[/url] Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.foo.com' is therefore not allowed access. The response had HTTP status code 504.
As far as I've gotten into my research, I thought it was placing 'corsheaders.middleware.CorsMiddleware' too far down the MIDDLEWARE_CLASSES list so I moved it up
code:
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
...
But still get the issue. I'm lost about next steps and was curious if anyone has any thoughts of why this might be happening?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

huhu posted:

But still get the issue. I'm lost about next steps and was curious if anyone has any thoughts of why this might be happening?
Have you configured any allowed origins?

huhu
Feb 24, 2006

In my settings.py I've got:
code:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
The weird thing is that it doesn't happen every time. Like 95% of the time an endpoint will load successfully and the data will get displayed on the front end.

I'm refreshing the homepage over and over and getting the following results -

5x -> loads successfully
1x -> 502 Error with /foo endpoint (preflight request issue with Access-Control-Allow-Origin)
7x -> loads successfully
2x -> 500 Error with OPTIONS
3x -> loads successfully
2x -> 500 Error with OPTIONS
1x -> 502 Error with /bar endpoint (preflight request issue with Access-Control-Allow-Origin)
2x -> loads successfully

huhu fucked around with this message at 21:29 on Nov 30, 2017

epswing
Nov 4, 2003

Soiled Meat

huhu posted:

I'm refreshing the homepage over and over and getting the following results -

Is this with the built-in dev server? Or a real web server like apache or nginx?

huhu
Feb 24, 2006

epalm posted:

Is this with the built-in dev server? Or a real web server like apache or nginx?

Real web server with uwsgi.

NtotheTC
Dec 31, 2007


huhu posted:

Real web server with uwsgi.

Is the server running on a VM/container somewhere or locally on the machine you're accessing the server from?

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

NtotheTC posted:

Is the server running on a VM/container somewhere or locally on the machine you're accessing the server from?

It's running in Docker.

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