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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Megaman posted:

Nope, the timeout happens between the server and s3. We also can't store on the server, we have tons of data, thus s3. I was thinking the client could upload from our app directly to s3, wouldn't that be a valid solution to this? We could just cut out the server.

Wasn't suggesting it as a long term solution, just as a way to debug and isolate the issue.

So for the third time...what are you using to transfer the files to S3?

Adbot
ADBOT LOVES YOU

Megaman
May 8, 2004
I didn't read the thread BUT...

fletcher posted:

So for the third time...what are you using to transfer the files to S3?

Boto, but then again you're question is insanely vague so Boto, Python, S3, Django, Apache. One of those should answer your question however you meant to ask it.

ManoliIsFat
Oct 4, 2002

Megaman posted:

Nope, the timeout happens between the server and s3. We also can't store on the server, we have tons of data, thus s3. I was thinking the client could upload from our app directly to s3, wouldn't that be a valid solution to this? We could just cut out the server.

That sounds crazy, what would you do, give your client your AWS keys?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Megaman posted:

Boto, but then again you're question is insanely vague so Boto, Python, S3, Django, Apache. One of those should answer your question however you meant to ask it.

Yeah but just because Apache and Django are in your stack doesn't mean they are the components that send the files to s3. You also listed s3 in there...you're using s3 to send files to s3? That doesn't make any sense.

Anyways, are you able to reproduce the issue with a tiny little python script that just uses Boto to send a file to s3? It looks like others have this issue too. The issue is for aws-cli but it uses boto under the covers.

Pardot
Jul 25, 2001




ManoliIsFat posted:

That sounds crazy, what would you do, give your client your AWS keys?

No. You can give a presigned upload url, which includes a policy which can include things like max file size, content type, an expiration date, and more. You sign the policy with your key, then s3 verifies it. http://aws.amazon.com/articles/1434

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Pardot posted:

No. You can give a presigned upload url, which includes a policy which can include things like max file size, content type, an expiration date, and more. You sign the policy with your key, then s3 verifies it. http://aws.amazon.com/articles/1434

Incidentally you can do the same to create individual urls that allow downloads to private files on S3.

ManoliIsFat
Oct 4, 2002

Pardot posted:

No. You can give a presigned upload url, which includes a policy which can include things like max file size, content type, an expiration date, and more. You sign the policy with your key, then s3 verifies it. http://aws.amazon.com/articles/1434

Siiiick, thanks for that.

Babby Sathanas
May 16, 2006

bearbating is now adorable
I've been away from Django for about a year, but I'm interviewing for a Django position on Monday. Is there anything I should be aware of in the ecosystem these days or any literature I can read this weekend to bring me up to scratch?

ufarn
May 30, 2009
South and django-registration being out are the two big changes I can think of.

Well, South isn't out just yet, but soon.

euclidian88
Aug 3, 2013
I am very new to django I want to add an event calendar to a site.

Nothing particularly fancy just a calendar displaying events by month and a list of recent events.

Does anyone have any suggestions for where to look or a good package to use expand on? As this is my first django project and I am working on it in my own time I had thought of rolling my own but backed away might it be a good learning experience?

MonkeyMaker
May 22, 2006

What's your poison, sir?

euclidian88 posted:

I am very new to django I want to add an event calendar to a site.

Nothing particularly fancy just a calendar displaying events by month and a list of recent events.

Does anyone have any suggestions for where to look or a good package to use expand on? As this is my first django project and I am working on it in my own time I had thought of rolling my own but backed away might it be a good learning experience?

code:
class Event(models.Model):
    starts_at = models.DateTimeField()
    ends_at = models.DateTimeField()
    title = models.CharField(max_length=255)
    description = models.TextField()

    class Meta:
        order_by = ['starts_at', 'ends_at']
then make a couple of views that show a list of events and a single event's detail and you're done, yes?

euclidian88
Aug 3, 2013

MonkeyMaker posted:

code:
class Event(models.Model):
    starts_at = models.DateTimeField()
    ends_at = models.DateTimeField()
    title = models.CharField(max_length=255)
    description = models.TextField()

    class Meta:
        order_by = ['starts_at', 'ends_at']
then make a couple of views that show a list of events and a single event's detail and you're done, yes?

Ok thank you for your reply. I will have a go based on this.

I had just been wondering in case there had been a more standard way that I had been missing. It seemed a very common thing to do and i didn't want to get 1/2 way through to realize that there is a django package/app blah that makes it trivial.

ephphatha
Dec 18, 2009




There's a few calendar/event tracking applications for Django, no idea whether they actually make things trivial though. The first three on Django packages seem to be recommended and fairly featured, and django-calendarium aims to be a replacement for django-schedule so it might be worth checking out.

MonkeyMaker
May 22, 2006

What's your poison, sir?

euclidian88 posted:

Ok thank you for your reply. I will have a go based on this.

I had just been wondering in case there had been a more standard way that I had been missing. It seemed a very common thing to do and i didn't want to get 1/2 way through to realize that there is a django package/app blah that makes it trivial.

I'm sure there are packages but most of them will likely go farther than what you described (providing hCals or something, for example). If you need more features, look into packages. If you don't, roll it yourself, especially as a beginner.

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord
I've got a page that I want to update with ajax. I've currently got it working more or less in that a call is made, a view ships off the request to render a template which is then inserted into the page using jquery with $('#containing-div').html(data) in the success function for the ajax request.

However, at this point it is basically rendering the entire page again and just making GBS threads that HTML into the already rendered containing div. If I only want to have it update the values of a few things spread out across the page, how should I go about this?

e; My best guess right now is to just have the view return JSON instead of raw HTML and then insert the different JSON key values into the different divs. But I also see some stuff around SO about rendering individual blocks and returning those and all sorts of other stuff. Just wanted to figure out what was considered best practice, if anything.

The March Hare fucked around with this message at 23:54 on Feb 15, 2014

Baby Nanny
Jan 4, 2007
ftw m8.

The March Hare posted:

I've got a page that I want to update with ajax. I've currently got it working more or less in that a call is made, a view ships off the request to render a template which is then inserted into the page using jquery with $('#containing-div').html(data) in the success function for the ajax request.

However, at this point it is basically rendering the entire page again and just making GBS threads that HTML into the already rendered containing div. If I only want to have it update the values of a few things spread out across the page, how should I go about this?

e; My best guess right now is to just have the view return JSON instead of raw HTML and then insert the different JSON key values into the different divs. But I also see some stuff around SO about rendering individual blocks and returning those and all sorts of other stuff. Just wanted to figure out what was considered best practice, if anything.

Yup what I'd do is use something like handlebars.js and create templates for all the dynamic areas of your page. The templates would then be called after your ajax calls and get populated with fields from your json data. This tends to be faster than just making GBS threads out .HTML() everywhere and is also a lot nicer to maintain code wise. JS templates own.

One thing to watch out for is a lot of them share the same {{ }} poo poo like djangos templates, so if you're in-lining js templates make sure to use djangos newish verbatim template tag. Also if you're doing any sort of api focused thing in django I highly highly reccomend checking out django rest framework, its a really great django lib that takes out a lot of the boilerplate involved in creating restful apis with django. You can get a super nice api up with just a model definition and a 4 line generic class call in like 5 mins with it.

Hit me up on COBOL irc if you have any weird questions, I poo poo out restful APIs in django for a living currently

Baby Nanny fucked around with this message at 17:59 on Feb 16, 2014

The March Hare
Oct 15, 2006

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

Baby Nanny posted:

Yup what I'd do is use something like handlebars.js and create templates for all the dynamic areas of your page. The templates would then be called after your ajax calls and get populated with fields from your json data. This tends to be faster than just making GBS threads out .HTML() everywhere and is also a lot nicer to maintain code wise. JS templates own.

One thing to watch out for is a lot of them share the same {{ }} poo poo like djangos templates, so if you're in-lining js templates make sure to use djangos newish verbatim template tag. Also if you're doing any sort of api focused thing in django I highly highly reccomend checking out django rest framework, its a really great django lib that takes out a lot of the boilerplate involved in creating restful apis with django. You can get a super nice api up with just a model definition and a 4 line generic class call in like 5 mins with it.

Hit me up on COBOL irc if you have any weird questions, I poo poo out restful APIs in django for a living currently

Thanks Gruntox, I'll give it a go and hit you up if I can't figure something out.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

The March Hare posted:

I've got a page that I want to update with ajax. I've currently got it working more or less in that a call is made, a view ships off the request to render a template which is then inserted into the page using jquery with $('#containing-div').html(data) in the success function for the ajax request.

However, at this point it is basically rendering the entire page again and just making GBS threads that HTML into the already rendered containing div. If I only want to have it update the values of a few things spread out across the page, how should I go about this?

e; My best guess right now is to just have the view return JSON instead of raw HTML and then insert the different JSON key values into the different divs. But I also see some stuff around SO about rendering individual blocks and returning those and all sorts of other stuff. Just wanted to figure out what was considered best practice, if anything.

This will vary wildly by use case, but if you want to update a few labels on return, rather than re-rendering the whole content area, your JSON return could be something like:

JavaScript code:
{
  success: true,
  data: [
      {id:'#someLabelID', value:"lol"},
      {id:'#anotherFineID', value:"pants"}
  ]
}
And you iterate through data and use the element / value pairs to set only certain elements. Of course, this is mixing presentation into your data, but it's a way of doing it that's pretty simple and flexible.

NtotheTC
Dec 31, 2007


Are there any good user location libs for django? I dont meed accuracy, I'd just like to display specific content based on "oh this person is in america/asia/europe". django-geoip looks promising but seems far more granular than I want for this task. I'd have to translate the country location to region. just wondering if theres a simpler solution

Pollyanna
Mar 5, 2005

Milk's on them.


I'm doing the Tango with Django tutorial, and I've got a question about the adding a category section. The template has this snippet of code:

HTML code:
{% if not category_name_url %}
<div style="color: red;">The specified category does not exist.</div>
{% else %}
Thing is, the URL for 'rango/add_category' doesn't pass in category_name_url.

Python code:
urlpatterns = patterns('',
                       url(r'^$', views.index, name='index'),
                       url(r'^about/', views.about, name='about'),
                       url(r'^add_category/$', views.add_category, name ='add_category'),
                       url(r'^category/(?P<category_name_url>\w+)$', views.category, name='category'),
                       )
So every time I access rango/add_category, I just get the "The specified category does not exist." message, and nothing else, even if it's a GET method. Why is that even there? I'm not trying to access a category page. Or am I just confused? (Cause I feel like I am.) Has anyone else gone through TWD?

ManoliIsFat
Oct 4, 2002

Looking at the example...it seems like the template in 7.2.3 is flawed. Looking at the view and urls, tour rango/add_category.html template is never gonna have a category_name_url variable, in the query string or the POST. I'd think it should look like

code:
<!DOCTYPE html>
<html>
    <head>
        <title>Rango</title>
    </head>

    <body>
        <h1>Add a Category</h1>
        <form id="category_form" method="post" action="/rango/add_category/">

            {% csrf_token %}
            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}

            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text}}
                {{ field }}
            {% endfor %}

            <input type="submit" name="submit" value="Create Category" />
        </form>


    </body>

</html>
e: so...did that work for you? I'm curious if the example is just wrong.

ManoliIsFat fucked around with this message at 17:08 on Feb 21, 2014

Pollyanna
Mar 5, 2005

Milk's on them.


Oh, sorry. Yes, it was wrong in the book. It works fine now.

I'm making my own Django app right now, and I'm kind of confused on how to handle something. I'm making a page where you can submit a form to create an object that has a User as a foreign key. You're required to be logged in to use it. Right now, the form shows all the data associated with the object, including the User. It has a <select> input with all the users on the site available to choose. I want to make it so that 1. the user cannot change what User the form object is related to and 2. the user selection field is invisible.

I understand that for the User field, I can set widget = forms.HiddenInput() (I think) to make it invisible, but I don't know how to make the default argument for the input the same as user.username. How do I do that?

ManoliIsFat
Oct 4, 2002

Cool :)

What you're proposing is a really bad practice actually: a hidden form can still be manipulated by the end user (either with dev tools or just forging of a POST). You most likely want to get the user info from request.user at that moment you're actually parsing the form and making the DB entries. Something like

code:
if request.user.is_authenticated():
    form.user_id = request.user.id
    #continue filling out this object, saving it to the DB
else:
    #kick back the form with a "you must be logged in" error
Does that make sense? Did I understand you correctly? Will this entry always be filled in the with user_id of the currently logged in user?

ephphatha
Dec 18, 2009




You shouldn't need an input (hidden or otherwise) to hold information about the user. Using the django.contrib.auth request context processor should set a cookie for all logged in users that will set request.user.

Edit: That's what I get for leaving a tab open.

Pollyanna
Mar 5, 2005

Milk's on them.


That seems about right, but it gives me this error:

code:
IntegrityError at /tracker/addapp/
tracker_application.user_id may not be NULL
What I do is basically have an attribute on the model called "user" that is a foreign key to the default User model that Django supplies. In my view, I have:

Python code:
if request.user.is_authenticated():
    form.user_id = request.user.id
    form.save(commit=True)
I'm guessing that form.user_id doesn't actually work, since it's supposed to be "user", but it still gives me that integrity error. Where is that coming from?

Ephphatha posted:

You shouldn't need an input (hidden or otherwise) to hold information about the user. Using the django.contrib.auth request context processor should set a cookie for all logged in users that will set request.user.

Yeah, I figured this out a while back but didn't quite understand how to use it in this context. Super useful that Django does this for you automatically.

ephphatha
Dec 18, 2009




That's because a user object doesn't have an ID field. If you're using the default user model you are probably looking for user.username.

Do you have this code on github or somewhere we can see what's in the Form model?

Pollyanna
Mar 5, 2005

Milk's on them.


Then why do I get "tracker_application.user_id may not be NULL" if user_id isn't a thing?

This is what I have right now:

Python code:
        if form.is_valid():
            if request.user.is_authenticated():
                form.user = request.user.username
                form.save(commit=True)
Trying to set form.username give me an error saying that that doesn't exist (naturally). form.user = request.user doesn't work either :downs:

Here's the Github.

ManoliIsFat
Oct 4, 2002

Ya, I'm sorry about that. It's called like user.pk? I saw this note "id is always None" on the AnonymousUser (https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users), assumed there was an id field.

So ya, Pollyana, I think I was leading you wrong there. I'm just learning Django along with you, but I've got years doing web dev in other frameworks, so I have some intuition. But I don't think I was using the django ORM correctly. I think on your model, you'd define a field like "user = models.ForeignKey(User)", and then when filling out and instance of the object, do:
code:
if request.user.is_authenticated():
    myObject.user = request.user
e: oh, you tried that. and you're sure you're authenticated, you're not just getting the AnonymousUser object?

Pollyanna
Mar 5, 2005

Milk's on them.


I'm checking it by putting {{ user.username }} on the page, and it displays. So, I'm still logged in.

I do have user = models.ForeignKey(User) in my object model, so there's that.

Fake edit: Figured it out! I had to do this:

Python code:
@login_required
def addapp(request):

    if request.method == 'POST':

        form = ApplicationForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save(commit=True)

            return HttpResponseRedirect('/tracker/{0}/apps/'.format(request.user.username))

        else:
            print form.errors

    else:

        form = ApplicationForm()

    content = { 'form': form }

    return render(request, 'tracker/addapp.html', content)
Basically I had to set the instance argument (I dunno what that argument is) to request.user. I found it in an SO question, but still don't quite get why. I also removed the if user.is_authenticated() since it's restricted to logged in users.

edit: Oh god, now /addapp/ is completely blank. :negative: Whyyyyy edit2: nvm. the url order is annoying

Pollyanna fucked around with this message at 00:36 on Feb 25, 2014

ephphatha
Dec 18, 2009




Pollyanna posted:

Then why do I get "tracker_application.user_id may not be NULL" if user_id isn't a thing?
I was actually wrong about the User model not having an ID field. Because it doesn't define a primary key it uses the Django default automatic primary key.

When the corresponding database table is created for the Application model it creates a table column called 'user_id' to store the information needed for the 'user' field in the model (in this case the foreign key to the user models primary key, user.id, hence user_id). So Application.user (in code) refers to tracker_application.user_id (in the database).

Pollyanna
Mar 5, 2005

Milk's on them.


That makes sense.

Now for some reason the apps don't update when I save a form, even though the redirect and everything works. :argh: Djangooo!

The POST data is right and gets POSTed and everything, but then nothin'.

nm worked. something about needing commit=False cause the user wasnt set

Pollyanna fucked around with this message at 01:33 on Feb 25, 2014

ephphatha
Dec 18, 2009




Alright, there's a few things to cover here.

I'd suggest reading over the ModelForm documentation again carefully, from looking at your code you've got a few redundancies.

Having a look at your ApplicationForm definition, you don't need to explicitly define the fields in the form (lines 9-12) since you have a Meta child class that does that for you.

So your ApplicationForm would look like this:

Python code:
__author__ = 'rebecca'

from django import forms
from models import Application


class ApplicationForm(forms.ModelForm):

    #This isn't needed since we associate the model in the Meta child class.
    #title = forms.CharField(max_length=64)
    #description = forms.CharField(widget=forms.Textarea)
    #company = forms.CharField(max_length=64)
    #submitted_date = forms.DateField()

    class Meta:
        model = Application
        fields = ('title', 'description', 'company', 'submitted_date')
Now for the view.

Pollyanna posted:

Basically I had to set the instance argument (I dunno what that argument is) to request.user. I found it in an SO question, but still don't quite get why.

The instance argument says "Create a form that alters this object". This allows the form to make changes to an existing object (useful in this case because the object contains information that the form does not define). You're trying to create an ApplicationForm (which is based on the Application model) associated with an instance of a User model which is invalid. The form itself will be valid because it contains all the required information as defined by the form, but it doesn't contain enough information to create an Application object.

Using the ModelForms documentation as a guide, what you need to do is create an Application object with the user field set to request.user, create a new form object associated with this application object and populated with the request data, then save the resulting form.

Views.addapp would then become:
Python code:
@login_required
def addapp(request):

    if request.method == 'POST':

        #create an application object with the user field set to the logged in user.
        app = Application(user=request.user)

        #create a form object from the request data associated with the previously created application object.
        form = ApplicationForm(request.POST, instance=app)

        if form.is_valid():
            form.save(commit=True)
            #this then saves the object to the database. Because the Application object is newly created, the
            # ID field is blank and the resulting data is inserted into the database as a new record.

            return HttpResponseRedirect('/tracker/user/{0}/'.format(request.user.username))

        else:
            print form.errors

    else:

        form = ApplicationForm()

    content = { 'form': form }

    return render(request, 'tracker/addapp.html', content)
There is another way to create an application object and set the user value, where you use the form data to create a new object without writing to the database (app = form.save(commit=false)) and then set app.user and save the application object and then the form which it looks like you're doing based on your edit, but I think the above is simpler.

(Some of my explanations could be wrong since it's based on reading the docs and not actually looking at the code. This code is untested.)

Pollyanna
Mar 5, 2005

Milk's on them.


That's basically what I ended up doing. It works now, but it's kinda confusing as to WHY I have to do that. Bit annoying that it can't automatically decide to associate something with a user.

Also, I want to add CSS classes to the form fields. Is there a way to change that template-side? Like, the code for the title input is <input id="id_title" maxlength="64" name="title" type="text"> and since I eventually want to add Bootstrap to this, I want to associate this with a particular class.

ephphatha
Dec 18, 2009




Yep, look at the Django forms docs.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got a method on one of my models:

code:
def do_the_thing(self):
    if self.some_counter_field < 5:
        self.some_counter_field += 1
        self.save()
        return True
    else:
        return False
The only place I call do_the_thing is in one of my templates. Worked exactly as intended on my local development server. Pushed it to production and I noticed that when I hit the Django Admin page for an instance of this particular model, it's incrementing some_counter_field. Tried the same thing again on my local dev server and wasn't able to reproduce. Any idea what might be happening here?

fletcher fucked around with this message at 03:30 on Feb 25, 2014

MonkeyMaker
May 22, 2006

What's your poison, sir?
First off, `django.contrib.auth.models.User` **does** have an `id` field. All models do unless explicitly told not to. However, AnonymousUsers and unsaved Users don't a set `id` or `pk` because, well, they don't exist in the database yet.

code:
class SomeView(CreateView):
    form = MyForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super(SomeView, self).form_valid(form)
That handles setting the user on the object to the currently logged-in user. I'd also set the user field to be hidden or, better yet, not include it in the `fields` of the form.

----

fletcher: I'm not sure I understand. Your code increments the counter and, in production, it's incrementing the counter. How is that not working correctly? Nevermind, I'm stupid.

So that's just a method on the model? Nothing in the model or model admin calls that method?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MonkeyMaker posted:

fletcher: I'm not sure I understand. Your code increments the counter and, in production, it's incrementing the counter. How is that not working correctly? Nevermind, I'm stupid.

So that's just a method on the model? Nothing in the model or model admin calls that method?

Yup that is correct. I have no idea why the admin interface would be calling that method, I am certain the only caller of the method is a single spot in one of my templates. Even if it was using some sort of serializer, it wouldn't invoke my custom methods on models right? It's got me really stumped.

The field is defined in my model as:
code:
some_counter_field = models.IntegerField(blank=True, default=0)

ufarn
May 30, 2009
I asked this in the general-programming thread, but maybe someone has some ideas for my question regarding a sane URL structure in Django?

The link links to a post farther down the page, and all the posts that follow, all of which are about the question. Your browser may just load at the top of the page, even though it shouldn't.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I switched to DEBUG = True in the production clone environment, and viewing the admin page no longer increments that value. So I thought great, I can set DEBUG = False on my local dev server to debug...but I still can't reproduce it locally. :(

edit: had the 2nd true/false backwards

fletcher fucked around with this message at 19:31 on Feb 25, 2014

Adbot
ADBOT LOVES YOU

MonkeyMaker
May 22, 2006

What's your poison, sir?

fletcher posted:

I switched to DEBUG = True in the production clone environment, and viewing the admin page no longer increments that value. So I thought great, I can set DEBUG = True on my local dev server to debug...but I still can't reproduce it locally. :(

Wait, switching on DEBUG changed the way it acts?

Can you show the entire model (at least the methods of the model) and the model's custom admin if it has one?

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