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
Pumpkin Pirate
Feb 2, 2005
???????
ChoiceField automatically verifies that the submitted value is in the list or queryset provided. Since you changed the querysets to .none(), there are no values that will pass this validation. If you still want this validation, you'll need to change the querysets back, and either empty the choices with javascript on page load, or find another way of not rendering them, such as a custom widget. If you don't care about the validation you could use TextField or IntegerField with a Select widget.

Adbot
ADBOT LOVES YOU

xpander
Sep 2, 2004

Pumpkin Pirate posted:

ChoiceField automatically verifies that the submitted value is in the list or queryset provided. Since you changed the querysets to .none(), there are no values that will pass this validation. If you still want this validation, you'll need to change the querysets back, and either empty the choices with javascript on page load, or find another way of not rendering them, such as a custom widget. If you don't care about the validation you could use TextField or IntegerField with a Select widget.

Aha, that must be it. I might have to throw out the validation then, as I'm trying to avoid loading those querysets - the data for each of those fields is slim at the moment, but I also wrote some code to import additional census data, which massively increases the number of records(and load time). Entirely doable! Thank you very much.

Storgar
Oct 31, 2011
What do you guys use for integration/full site testing? I'm not sure how it all works, but what I mean is an automated test suite that simulates a user clicking on a window with your site opened and having a bunch of database fixtures and stuff to make sure each user experience flow is working. Not necessarily a django question...

The March Hare
Oct 15, 2006

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

Storgar posted:

What do you guys use for integration/full site testing? I'm not sure how it all works, but what I mean is an automated test suite that simulates a user clicking on a window with your site opened and having a bunch of database fixtures and stuff to make sure each user experience flow is working. Not necessarily a django question...

http://www.seleniumhq.org/

e;

http://chimera.labs.oreilly.com/books/1234000000754 is how I really figured out testing stuff for Django, the vook is good (and free to read online!)

Storgar
Oct 31, 2011
Ah perfect, thank you!

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I'm a hobbyist and have only worked on a developer server so far. I've realized that the site I've been developing is... basically rubbish, but it's better than nothing. So I would like to continue being able to boot it up as is, but at the same time I want to rework a new version. A natural idea seems to be to copy-paste the directory. However, then I'll have to rename it to something like "project2", and, I mean, it wouldn't influence the site's name or url if I deploy of course, but it still feels odd, considering the original "project" has no version numbers. (Because I didn't count on needing them.)

Anyway, websites seem to go through this process periodically. How's it done (in Django)?

Edit: I realized that I probably couldn't simply copy-paste a folder. The project probably would have to formally be new, although for all intents and purposes what I intend to do could be called a copy.

supermikhail fucked around with this message at 06:26 on Feb 15, 2015

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

supermikhail posted:

I'm a hobbyist and have only worked on a developer server so far. I've realized that the site I've been developing is... basically rubbish, but it's better than nothing. So I would like to continue being able to boot it up as is, but at the same time I want to rework a new version. A natural idea seems to be to copy-paste the directory. However, then I'll have to rename it to something like "project2", and, I mean, it wouldn't influence the site's name or url if I deploy of course, but it still feels odd, considering the original "project" has no version numbers. (Because I didn't count on needing them.)

Anyway, websites seem to go through this process periodically. How's it done (in Django)?

Edit: I realized that I probably couldn't simply copy-paste a folder. The project probably would have to formally be new, although for all intents and purposes what I intend to do could be called a copy.

Use source control. Your project goes into a repository, and when you want to work on a new version, you clone that repository. With modern DVCS like mercurial and git, this can be done completely on your own machine. That or you just keep working in he same space, but you can roll back to your original version easily. Make sure you are using Django Migrations for your DB stuff, and your database can be kept in sync very easily with your code.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

Lumpy posted:

Django Migrations

Oh, drat, I'm still at 1.6... Now to figure out how to update this thing. I'm using LiClipse, and I'm wondering if it comes with Django, or I installed Django with pip which is also present on my system, although I'm not sure if for a good reason. Pip lists Django, among other packages for which I didn't use pip actually. :psyduck:

Also there's a bunch of Git stuff in Eclipse, and I'm not sure which package to install. Probably "Java implementation of Git"?

Sorry. I think I'm finally beginning to get the the specialist side of the 'specialist vs. generalist' debate. At this point it would have probably cost everyone less if I just had hired a professional to do my dream site. On the other hand I'd also probably go seriously into debt. :sigh:

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Use South (for migrations) if you can't use Django 1.7. The author of south was the one who went on to bringing migrations into core Django.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

supermikhail posted:

Sorry. I think I'm finally beginning to get the the specialist side of the 'specialist vs. generalist' debate. At this point it would have probably cost everyone less if I just had hired a professional to do my dream site. On the other hand I'd also probably go seriously into debt. :sigh:

Keep at it man, it's a little painful at first but just keep googling and asking questions when you get super stuck.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Thanks. The nice thing about Django (and programming in general) as opposed to skills such as playing music is that it doesn't seem to suffer from not having time to do it for a while... Or maybe I'm at the level where you can't talk about peak performance. But even then, I'm able to produce something that's useful and looks nice.

Er. Does anybody know if in Eclipse I can only work Git from the console? I've been looking around expecting the same functionality as in Netbeans where it's all mouse-operated, without any luck.

Found it.

Now to figure out how to clone a project properly. I guess I still have to give it a new name.

I think I figured it out. But then promptly deleted my database. I guess I'm supposed to make a base commit or something. Fortunately it's reversible.


I've got no idea what's going on and how to make it work.

supermikhail fucked around with this message at 15:40 on Feb 21, 2015

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
For posterity:

I think I've managed to figure it out. The process is like this: Right-click on project, select Team -> Share, then create a Git repository with the dialog that appears. Then find the "Git depositories" window and move it to an actually useful position. There find a microscopic button that says "Clone repository" and use it. Then, in the "Projects" window, right-click -> "Import" a project and gently caress around in the next dialog so that Eclipse allows you to import the cloned project. All in all, I still have to appreciate what all the fuss is about. :rolleyes:

duck monster
Dec 15, 2004

You really want to learn how to git from the command line so you get a better appreciation for how it thinks. Good source control is pretty much an essential skill imho.

(Also, Mercurial 4eva)

Storgar
Oct 31, 2011
I'm having problems installing python Pillow (actually PIL is giving me problems) on a hosting server where I don't have superuser access, confined to my home folder, and no permissions to use gcc. It's a huge pain in the rear end. Is there an alternative, more portable package that will let me process images? I just need to crop, resize, open and save png and jpeg files for now.

8======================================D~~~~*~~~~C|===========================================8

Update:

I figured it out myself and it was a huge pain in the rear end. Most answers on stack overflow and stuff involve using sudo commands, assuming you either own the server or have a VPS where you have superuser privilege. In case there is another living human being who wants to use python Pillow and Django, I'll post the answer below. The basic gist is that I used a virtualbox on a computer with identical architecture as the VPS with a similar distro to compile my files and copy the binaries over to the server.

The Deetz

You should be using a virtual environment! When you have the replicated environment and compiled files, there will be a "PIL" and "Pillow-2.7.0-py2.7.egg-info" (or whatever version) folders in your site-packages. Copy these to the corresponding locations on the VPS. In the /bin folder under your virtual environment, there will also be a bunch of pil*.py. Copy these over too.

Some tips:

* your replicated environment needs to have the same archicture (e.g. x86_64 SMP). Use uname -a to figure this out.

* your replicated environment needs to have the same version of gcc and glibc (/lib64/libc.so*).

* If you try using pillow on the VPS and you get an error about UCS4_*, you need to run ./configure --enable-unicode=ucs[2|4]. This has something to do with unicode byte width. (google "python ucs2 ucs4")

* beer

When you think about it, it's really not worth all the effort. :sigh:

Storgar fucked around with this message at 05:53 on Mar 2, 2015

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How come you are being forced to use a VPS with no sudo access?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Are there any options for using encrypted fields in Python 3? Everything I've found is based on keyczar which doesn't seem to support Python 3.

Storgar
Oct 31, 2011

fletcher posted:

How come you are being forced to use a VPS with no sudo access?

Oops. poo poo. Pretend I said remote server from a normal hosting plan.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How do I kick off a background task after my save() override on my model finishes?

The March Hare
Oct 15, 2006

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

fletcher posted:

How do I kick off a background task after my save() override on my model finishes?

https://docs.djangoproject.com/en/1.7/ref/signals/#post-save ?

e; and also the warning at the top of that page

The March Hare fucked around with this message at 00:28 on Mar 7, 2015

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Won't that still wait for signal handlers to complete before returning a response to the user?

I want the response to be returned to the user and then have a background task kicked off. Maybe I have to use Celery?

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

I think Celery is the only way to do that

duck monster
Dec 15, 2004

Yep. Seconding Celery. The django integration is pretty tight too.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
edit: oops meant to post this in the python thread.

fletcher fucked around with this message at 22:37 on Mar 11, 2015

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Haha. I was just coming in to ask whether that was possible. I doubted considering the way processes and threads work. Trying to build a more effective cache that is never felt by the public users for all CMS content. Celery it is I guess.

duck monster
Dec 15, 2004

Why not just use redis and djangos native caching?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Its data built from a CMS, and I want to ensure the public pages are ALWAYS based on the cache, ie, the public user would never wait for a rerender so no matter how exxy the queries are to construct the page, it doesn't really affect perceived performance.

If there's a way to trigger a recache while immediately returning the cached copy that'd be great though. Djangos cache doesn't seem to have a way to do this though, or rather, its various cache decorators. I'd still use the low level cache api.

RyceCube
Dec 22, 2003
Are there any good libraries for handling user registration or a good guide I can follow? Laravel had a couple good robust registration libraries so I didn't have to make them myself.

Mulozon Empuri
Jan 23, 2006

There are a couple, people tell me https://github.com/pennersr/django-allauth is the best one nowadays

xpander
Sep 2, 2004
The system I'm working on subclasses django-extensions' TimeStampedModel. I'm making some minor additions to a template that is using this model, including putting the "modified" field on the page for the user to see. However, it never seems to have a value when used in the template - it's always blank. I've been able to print the value to the console, but that field doesn't seem to be inside the context object. Does Django not automatically pass fields from abstract base classes to context objects or something? Using {{ model.other_field }} works fine for anything listed on the model, but {{ model.modified }} does not. I can't quite seem to figure out the disconnect here.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Phiberoptik posted:

Are there any good libraries for handling user registration or a good guide I can follow? Laravel had a couple good robust registration libraries so I didn't have to make them myself.

I haven't tried django-allauth yet but python-social-auth has worked really well for me.

Hed
Mar 31, 2004

Fun Shoe

xpander posted:

The system I'm working on subclasses django-extensions' TimeStampedModel. I'm making some minor additions to a template that is using this model, including putting the "modified" field on the page for the user to see. However, it never seems to have a value when used in the template - it's always blank. I've been able to print the value to the console, but that field doesn't seem to be inside the context object. Does Django not automatically pass fields from abstract base classes to context objects or something? Using {{ model.other_field }} works fine for anything listed on the model, but {{ model.modified }} does not. I can't quite seem to figure out the disconnect here.

Are you able to print it to the debug console from the view (e.g. context['model'] from a generic view's context) or just in the Django shell? What you're talking about should work just fine in the template. The only other thing I can think of is if you had somehow coerced your model into something that responds to key lookups with an empty string or None.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I'm having a really weird issue with django-rest-framework: when I'm adding an entry to a model that uses a foreign key via the API admin interface, I see "%Object-Name% object" instead of a more useful value like the object's title:


How can I control the value that appears in that dropdown?

Here's the serializer for that particular model, though it's nothing special:

Python code:
class StationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Station
The view:

Python code:
class StationList(viewsets.ModelViewSet):
    queryset = Station.objects.all()
    serializer_class = StationSerializer
And finally the model:

Python code:
# A table of stations workers can be assigned (register, kitchen, etc...)
class Station(models.Model):
    company = models.ForeignKey(Company)
    title = models.CharField(max_length=50)
    color = models.CharField(max_length=50)

    class Meta:
        ordering = ('company', 'title',)

Roll Fizzlebeef
Sep 9, 2003


You probably need a __str__ method on the model.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Karthe posted:

I'm having a really weird issue with django-rest-framework: when I'm adding an entry to a model that uses a foreign key via the API admin interface, I see "%Object-Name% object" instead of a more useful value like the object's title

You have lots of options for controlling what is returned by your API for that company object reference. I think the simplest is what Roll Fizzlebeef suggested above. You should take a look at Serializer relations and check out what's possible.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Roll Fizzlebeef posted:

You probably need a __str__ method on the model.

fletcher posted:

You have lots of options for controlling what is returned by your API for that company object reference. I think the simplest is what Roll Fizzlebeef suggested above. You should take a look at Serializer relations and check out what's possible.
You guys were right, I just needed to add a __str__() method to my Models.

Another question for you: let's say I'm creating an employee with a company and a location. If I assign the employee to Company A and Location 2, but Location 2 isn't a child of Company A, does Django allow for throwing an error until I assign a Location that IS a child of Company A? What is the term for this? I can't think of what Django might call it so I'm not sure where in the docs I should look.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
Is every location associated with exactly one company? Is every employee in exactly one location? Is every employee in a location necessarily associated with that location's company?

If all of those are the case, you only need to assign an employee to a location -- the association with the company can be chained through the 'location' relationship.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Lysidas posted:

Is every location associated with exactly one company? Is every employee in exactly one location? Is every employee in a location necessarily associated with that location's company?

If all of those are the case, you only need to assign an employee to a location -- the association with the company can be chained through the 'location' relationship.
Those all apply, so the fix was simple - I just adjusted the Employee Model to remove the link to the Company and tweaked Location model's __str__() to include the company name!

For future reference, does Django have the ability to include logic like my original scenario? Or is that an indication that the data itself needs to be restructured?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Karthe posted:

Those all apply, so the fix was simple - I just adjusted the Employee Model to remove the link to the Company and tweaked Location model's __str__() to include the company name!

For future reference, does Django have the ability to include logic like my original scenario? Or is that an indication that the data itself needs to be restructured?

I don't know of anything out of the box that will enforce that logic, but I think you could put your own in a Model.pre_save. Or if you just want it at the API level maybe you can do it with a DRF Validator.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I'd like to have a form with several rows of radio buttons, and the data and number of those radio buttons derived from the database. Is there any way to accomplish this with Django forms? I suspect not.

Adbot
ADBOT LOVES YOU

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
I've dug into DRF's @list_route() and @detail_route() after fiddling around with drf-nested-routers and drf-extensions and being unable to get POST operations to work. Now I'm unable to POST because of a NOT NULL constraint. I'm sure I'm doing something wrong, can you guys help me figure out what?

The route I'm trying to get working is /companies/:id/locations. Here's the CompanySerializer:

Python code:
class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer

    @detail_route(methods=['get', 'post'])
    def locations(self, request, pk=None):
        owner = self.get_object()

        if request.method == 'GET':
            locations = Location.objects.filter(company_id=owner)
            context = {'request': request}
            locations_serializer = LocationSerializer(locations, many=True,
                                                      context=context)
            return Response(locations_serializer.data)
        elif request.method == 'POST':
            request_data = request.data
            request_data['company_id'] = pk
            print(request_data) # {'company_id': '2', 'title': 'Store #341'}
            locations_serializer = LocationSerializer(data=request_data)
            locations_serializer.is_valid(raise_exception=True)
            print(validated_data) # OrderedDict([('title', 'Store #341')])
            location = Location.objects.create(
                **locations_serializer.validated_data)
            return Response(locations_serializer.data)
And here's the Location model:

Python code:
# A table of stores or offices
class Location(models.Model):
    company = models.ForeignKey(Company, related_name='locations')
    title = models.CharField(max_length=100)

    class Meta:
        ordering = ('company',)

    def __str__(self):
        return '%s - %s' % (self.company.name, self.title,)
I can GET the list of locations no problem. Unfortunately, when I try and POST to create a new location, I get the following error:

quote:

NOT NULL constraint failed: serverapp_location.company_id

I tried fixing this issue with request_data['company_id'] = pk but when I print validated_data that company_id is missing. What am I doing wrong?

Edit: I've noticed that validated_data excludes additional values I try injecting into request.data before validating it. Does the validator know that I tinkered with the request?

Edit: Turns out I'd been following advice based on older versions of DRF. Here's the correct way to create a new object (or at least what's working for me right now):

Python code:
elif request.method == 'POST':
    # Grab the serializer and pass it the new data
    locations_serializer = LocationSerializer(data=request.data)
    # Verify that everything checks out
    locations_serializer.is_valid(raise_exception=True)
    # save() will create a new object because we didn't pass in
    # an existing object when we called the serializer
    locations_serializer.save(company_id=pk)
    # Return the data we created
    return Response(locations_serializer.data)

IAmKale fucked around with this message at 00:27 on Apr 7, 2015

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