Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Extending the User Model

Hey guys,

I'm new to Python and Django so I apologize if this is a dumb question, but I'm looking for some guidance/help from your more experienced folks regarding extending the User model.

I want to be able to create users, but add one simple custom field for the user for "region". When a user registers (via a 'sign up' view/html form) I just want to them choose from regions I've specified and it be a value attached to that user.

I thought User.objects.create_user() would have a way to pass a custom field for a user but it seems not? Any help would be great, thanks!

/r/django
https://redd.it/69p7bt
How can I use a form to populate empty fields in a model class' pre-existing instances?

[This is a snapshot of the django site I'm creating.](http://imgur.com/a/LmJen) Each of the content boxes (Corvette, Nathalie Emmanuel, etc.) is produced by iterating through instances of a model called "Noun."

There's one exception... the "Rating score" form field. That's pointed to a separate model called "NounScore." I can't figure out how to get each "Rating score" field to correlate with each "Noun" that surrounds it.

Every time a new Noun object is created, a corresponding NounScore object is created along with it (using a one to one field and django signals). I linked them together with a one to one field instead of a foreign key because each item is supposed to be rated only once... by a single user. Nouns only appear on the homepage of the user they were created for.

My goal is to increment the primary key of each NounScore object every time the template's for loop prints a new "Rating score" field to the screen.

I'm sorry if this is explained poorly, but I don't really have a clue what I'm doing. [Hopefully the example code helps](https://pastebin.com/mKHWGtBx). Thank you for any help! I'll be sure to pass it on in time.

/r/django
https://redd.it/69nm3a
What's the preferred approach to defining these relations (models and Django Rest Framework serializers)

I've read that circular imports is a 'code smell' and is fundamentally a bad design choice. I have an app that has models, User, Deck, Hand. I want the User to be able to create a Hand without needing to create a Deck, but also give the User the choice to put the Hand in the Deck if wanted. So I end up with something like this:

models.py:

class User(AbstractUser):
pass

class Deck(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, unique=True,
blank=False, null=False)
user = models.ForeignKey('users.User', related_name='decks',
on_delete=models.CASCADE, null=False)


class Hand(models.Model):
created = models.DateTimeField(auto_now_add=True)
deck = models.ForeignKey('goals.Deck', related_name='hands', on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, blank=False, null=False)
user = models.ForeignKey('users.User', related_name='hands', on_delete=models.CASCADE, null=False)


serializers.py:

class HandSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
deck = serializers.CharField(required=False, source='deck.name')

class Meta:
model = Hand
fields = ('url', 'id', 'created',
'deck', 'name', 'user')
extra_kwargs = {
'url': {
'view_name': 'goals:hand-detail',
}
}


class DeckSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
hands = HandSerializer(many=True, read_only=True)

class Meta:
model = Deck
fields = ('url', 'id', 'created', 'name', 'user')
extra_kwargs = {
'url': {
'view_name': 'goals:deck-detail',
}
}

class UserSerializer(serializers.HyperlinkedModelSerializer):
decks = DeckSerializer(many=True)
hands = HandSerializer(many=True)

...

Is this the correct approach API-design-wise in order to achieve what I want app-design-wise? If not, how should I go about doing this? And if so, how do I get around the circular import errors when I change user from a ReadOnlyField to a UserSerializer() field?

/r/django
https://redd.it/69zh7q
Best way to test Django REST API with Authentication?

I've successfully built a Django REST API with a few preliminary endpoints. They work fine and I can test them in a browser or with 'curl' in Terminal.

However, now I'd like to implement Authentication. Once Authentication is in place, is using something like Postman the only way to test the endpoints?

Currently reading this: http://www.django-rest-framework.org/api-guide/authentication/ Which Authentication approach have you used for your REST APIs? Session? Token? Something else?

Robert

/r/django
https://redd.it/69ztz0
Not understanding field__icontains?

I'm having a problem implementing a database query using a string.
I've tried many different methods with all of the same results, and am nowhere closer to the goal.

#urls.py
url(r'^api/v1/item/nomen/contains/(?P<nomen>[\w\-]+)/$', views.ItemListContainsNomen.as_view(), name='item_lookup_contains_nomen'),


#views.py
class ItemListContainsNomen(generics.ListAPIView):
serializer_class = ItemSerializer

def get_queryset(self):
nomen = self.kwargs['nomen']
return Item.objects.filter(nomenclature__icontains=nomen)

class Item(models.Model):
id = models.IntegerField(primary_key=True)
nomenclature = models.CharField(max_length=35)

This nets me a warning such as
> "/.virtualenvs/realDjango/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py:110: Warning: Truncated incorrect DOUBLE value: 'nomen/contains/CLOSER'
>
> return self.cursor.execute(query, args)
>
> Not Found: /api/v1/item/nomen/contains/CLOSER/"

I can successfully run this query using the MYSQL console and raw MYSQL with LIKE, and I can successfully query another database's TextField using the same syntax in Django.....but this column just doesn't seem to work no matter what. There has to be something I'm missing. I should also note, replacing icontains=nomen with say, icontains="CLOSER" also yields the same errors.
Checking datatype in console shows

> +-----------+
> | DATA_TYPE |
> +-----------+
> | varchar |
> +-----------+
> 1 row in set (1.39 sec)

/r/django
https://redd.it/6a0tz9
Anyone familiar with Django deployment with AWS?

I am able to deploy my django app to AWS with no issues with Nginx and Gunicorn. My site functions properly at the public IP. Now I'm trying to point my domain name to the AWS instance.

I followed the instructions [here](https://u.osu.edu/walujo.1/2016/07/07/associate-namecheap-domain-to-amazon-ec2-instance/) and I can't even access the elastic IP (Bad Request 400 error). AWS is configured properly to allow incoming HTTP/S requests.

I'm willing to pay for someone to help me get this resolved, if anyone was so inclined. I'm brand new to deployment and can't wrap my head around what's going wrong.

/r/djangolearning
https://redd.it/69sk3x
How to read a csv file with multiple header rows into pandas?

https://github.com/Tresanne/IS362-JUPYTERNOTEBOOK/blob/master/Impact_Poverty-%20fixed.csv

I am not sure how to read the multiple rows. Do i have to do it without the rows and then do it manually in pandas? Or is there a way to read the whole csv file into pandas?

/r/IPython
https://redd.it/69zaw3
Override save and DjangoAdmin

I have a custom User model where I overrode the save() method with one that assigns the user to appropriate UserGroups based on a field. However, based on [this](http://stackoverflow.com/questions/1925383/issue-with-manytomany-relationships-not-updating-inmediatly-after-save), it seems that DjangoAdmin will ignore any changes I make to an M2M field. What are my options to solve this?

/r/djangolearning
https://redd.it/69p9ki
[AF] Flask serving up static files as variables

I'm having a very strange issue. I provide an URL for users to access their personal reports (http://subdomain.domain.net/<input_str>) and when I test it it works just fine, but in production the MSISDN variable is always a static file from the app directory. Has anybody encountered an issue like this before?
[Tue May 09 00:28:48.398973 2017] [wsgi:error] [pid 30477:tid 140308822042368] User MSISDN is: apple-touch-icon.png
[Tue May 09 00:35:30.320477 2017] [wsgi:error] [pid 30740:tid 140308922754816] User MSISDN is: license.txt
[Tue May 09 00:35:30.332013 2017] [wsgi:error] [pid 30740:tid 140308914362112] User MSISDN is: rss
[Tue May 09 00:35:30.336705 2017] [wsgi:error] [pid 30740:tid 140308889184000] User MSISDN is: robots.txt
[Tue May 09 00:35:30.337023 2017] [wsgi:error] [pid 30740:tid 140308905969408] User MSISDN is: sitemap.xml
[Tue May 09 01:11:56.253829 2017] [wsgi:error] [pid 32139:tid 140308830435072] User MSISDN is: 254799369284
[Tue May 09 01:14:11.350096 2017] [wsgi:error] [pid 32074:tid 140308763293440] User MSISDN is: 2544722210
[Tue May 09 01:14:52.530269 2017] [wsgi:error] [pid 32074:tid 140309007640320] User MSISDN is: 2544722039475
[Tue May 09 01:14:59.801512 2017] [wsgi:error] [pid 32139:tid 140308738115328] User MSISDN is: favicon.ico
[Tue May 09 01:15:40.100122 2017] [wsgi:error] [pid 32292:tid 140309007640320] User MSISDN is: 2544722039475
[Tue May 09 01:16:35.712011 2017] [wsgi:error] [pid 32293:tid 140308771686144] User MSISDN is: 2544722039475

Pastebin to application code:
https://pastebin.com/e9dNU1r8

/r/flask
https://redd.it/6a22xp
user permissions and own admin panel

So I'm learning Django for an inventory management web app I'm building.

Basically, I want users to be able to track their inventory, adding to it and deleting etc...but obviously **only their** items. I don't want to expose them to the *project's* Admin app though.

So how would I go about doing this? Do I *need* something like django-guardian? And how can I utilize all the batteries inside the admin app *without* sharing the *project's* admin app with them?

Each sign up user (owner) can add other users (employees) through their admin panel, with whom they will share it afterwards. Obviously those invited users will have less permissions: they can add items, but not invite other users to the owner's panel. And all users will have less permission than the admin (me).

Any pointers are very much appreciated!

/r/djangolearning
https://redd.it/69koz4
Returning two lists

I have two classes (Series & Episode) in my models.py

Code:

class Series(models.Model):
genre = models.CharField(max_length=100)
year = models.CharField(max_length=4)
logo = models.FileField()
show_title = models.CharField(max_length=200)

def __str__(self):
return self.show_title + ' - ' + self.year

class Episode(models.Model):
series = models.ForeignKey(Series, on_delete=models.CASCADE)
episode_title = models.CharField(max_length=200)
episode_num = models.CharField(max_length=3)
season = models.CharField(max_length=3)

My function detail in views.py:

def detail(request, show_title, episode_title):
series = get_object_or_404(Series, id=show_title)
episode = get_object_or_404(Episode, id=episode_title)
return render(request, 'shows/detail.html', {'series':series,'episode':episode})

Everything works if I get rid of:

- episode = get_object_or_404(Episode, id=episode_title)
- 'episode':episode
- and remove the parameter 'episode)title

But I want to access the variables that are in Episode, and print those variables in my table. I currently only have access to Series.

Html:

<table>
<tr class = "table-header">
<td>Episode</td>
<td>Episode Title</td>
<td>Genre</td>
<td>Year</td>
</tr>
<tr>
<td>S3E14</td>
<td>{{ episode.episode_title }}</td>
<td>{{ series.genre }}</td>
<td>{{ series.year }}</td>
</tr>
</table>


Error code:

TypeError: detail() missing 1 required positional argument: 'episode_title'

I am not understanding this error code. How am I able to get this code working?

/r/djangolearning
https://redd.it/6a3q0w
What's everyone working on this week?

Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.


/r/Python
https://redd.it/6a5m37
Hiring | Simons Foundation | Full Stack Software Engineer | Onsite/Full time | New York City, NY

Simons Foundation is looking for a passionate Full Stack Software Engineer!

Simons Foundation exists to support basic - or discovery-driven - scientific research. We do this through direct grants in four areas: Mathematics and Physical Sciences, Life Sciences, Autism Research (SFARI), and Education & Outreach. This is only a quick blurb of what we do! If you want to find out more, please visit www.simonsfoundation.org. I'm certain you'll be interested!

This role specifically is for my team. We're a small (9) team of passionate engineers. You'll be joining a yet young project creating Software critical to Simons Foundation's mission.

What we're looking for: Passion (aka desire/enthusiasm, not any sort of JS library), Design Patterns, Python, Django, React, Single Page App experience, webpack, APIs.

If you're interested, please either reach out to me (the hiring manager) @ sford@simonsfoundation.org, or apply directly below.

https://simonsfoundation.wd1.myworkdayjobs.com/en-US/simonsfoundationcareers/job/160-Fifth-Avenue/Software-Engineer_R0000050.

/r/django
https://redd.it/6a52js