Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make unicode \\r\\n to \r\n
I have a Object named Post in Django. I used get_object_or_404() to get this object. And there is a TextField named text. this text Field has some string like this This is the some content.\r\n\r\nThis is another line. But when I call print funcition, this string still have no format. I want this: This is some content. This is another line. But that is : This is the some content.\r\n\r\nThis is another line. I feel so puzzled. So I run debug -> post.text is unicode, when print called, it change \r\n\r\n to \\r\\n\\r\\n. I don't know how to solve this problem. Any help will be appreciated. -
How to render Django template to show on Nginx server error message
I have done up a false system for Error 502 and linked my django HTML template, however django shows the plain html and not rendered django HTML template. unable to render Django HTML template How to configure my server setting(Nginx) so that django html template can be shown? error_page 500 502 503 504 /500.html; location = /500.html; { alias /home/user/myapp/myapp/templates/500.html; } -
Django | ORM | Get records that are divisible by an integer
Using Django's ORM, is it possible to query the db for records that has a column with value that is divisible by an integer? For example, get only records that their num column is divisible by 2 (num % 2 == 0). I hope that this is clear enough. THANKS!! -
Inexplicable, simple, 'list index out of range' -- Python
I keep trying to use this for loop. Actually a variety of for loops. I keep getting the error, 'list index out of range'. No idea. for q in range(0, len(list(package_ids))-1): if (q==0): query = 'Zero' + package_ids[q] else: query = 'More' + package_ids[q] -
ansible django deploy permission denied pip packages
I am trying to deploy my django to aws ubuntu machine. However, I keep getting this permission denied on my packages. How can I solve this ? Thanks. Here is the error: Downloading from URL https://pypi.python.org/packages/a6/1c/72a18c8c7502ee1b38a604a5c5243aa8c2a64f4bba4e6631b1b8972235dd/futures-3.1.1-py2-none-any.whl#md5=61a88f749eb3655042f95d198f783ef3 (from https://pypi.python.org/simple/futures/) Installing collected packages: boto3, botocore, certifi, cffi, chardet, coreapi, coreschema, cryptography, Django, django-bootstrap3, django-countries, django-datatable, django-rest-swagger, django-storages, djangorestframework, docutils, gunicorn, idna, itypes, Jinja2, jmespath, MarkupSafe, olefile, openapi-codec, paramiko, Pillow, psycopg2, pyasn1, pycparser, PyNaCl, python-dateutil, python-decouple, pytz, PyYAML, requests, s3transfer, simplejson, six, sorl-thumbnail, uritemplate, urllib3, dj-database-url, asn1crypto, bcrypt, futures Cleaning up... Removing temporary dir /tmp/pip_build_deploy... Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/boto3-1.4.7.dist-info' Below are some other related code: requirements/production.txt https://gist.github.com/anonymous/79f4d0b43f39fc317d33e09dbd1c58ba deploy.yaml https://gist.github.com/anonymous/02f68f05dab3f6858ab6aa10c89f5e09 Ubuntu: 14.04 -
Django : How to query users based on latest post
The question is simple. im building a recipe website with multiple users to submit their recipes. i want to build one page listing all the users and arrange the user hierarchy based on their latest post. what is the best way to query the users in the views.py and pass to the context? the code snippet is something like this; models.py class UserRecipe(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) so in order to query users and arrange them based on their UserRecipe created_date what is the best way to do it? -
How can I use non-Python dependencies for my Django Zappa project?
I'm using a Python package called natto-py which requires a non-python Japanese tokeniser called MeCab. Is it possible to use this for my Zappa project? How can MeCab be installed on Lambda (since pip does not work)? Django 1.10 & Python 3.5 -
How to capture HTML5 data attribute when form is submitted to views.py of Django
As you can probably tell from the nature of my question, I'm a little new to this. I have read similar post on this subject matter but most of it went right past my head and I did not feel like it was 100% applicable to the circumstance that I was facing so I thought I'd ask the question in a simplified way. The question: let's say I'm running the below HTMl form and a user submits the form to my views.py as shown in the views section below, I would able to store the value of the user selection by using: car_selection = request.POST.get('car') . My question is, how would I be able to capture the HTML5 data of " data-animal-type="spider" " ? I know there are Gurus out there but please do not explode my head. I would really need simplified help. Thanks for helping. Example HTML Form: <select name="carlist" > option data-car-type="premium" name= "car" value="audi">Audi</option> </select> Example Django View Function def getcar(request): ... if request.method == 'POST' ... selected_carn = request.POST.get('car') -
GeoDjango equivalent of ST_GeomFromGeoJson?
What is the equivalent of ST_GeomFromGeojson() in GeoDjango? I'm looking for it in GeoDjango's documentation but there's only AsGeoJSON as its output format. This can be done both using annotate and serialize. But what if I want to have a GeoJson object that I need to turn back to Geom? Use Case: geom_test = Geom.objects.filter(poly__within = [ST_GeomFromGeoJSON(d)]) -
ModelForm field attrs
According to the django docs, a modelform field accepts attrs. When I attempt to apply attrs I get TypeError: init() got an unexpected keyword argument 'attrs' The form I'm attempting to make is pretty simple, I just want to apply style to it. What am I doing wrong? forms.py from django import forms from .models import ServiceReportModel class ServiceReportCreateForm(forms.ModelForm): class Meta: model = ServiceReportModel fields = [ 'request_number', 'request_reason', 'actions_taken', ] class ServiceReportUpdateForm(forms.ModelForm): class Meta: model = ServiceReportModel fields = [ 'report_number', 'request_number', 'request_reason', 'actions_taken', ] widgets = { 'report_number': forms.CharField(attrs={'class': 'form-control'}), 'request_number': forms.CharField(attrs={'class': 'form-control'}), 'request_reason': forms.CharField(attrs={'class': 'form-control'}), 'actions_taken': forms.Textarea(attrs={'class': 'form-control'}), } views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .forms import ServiceReportCreateForm, ServiceReportUpdateForm from .models import ServiceReportModel class ReportCreateView(CreateView): form_class = ServiceReportCreateForm model = ServiceReportModel class ReportCreateView(UpdateView): form_class = ServiceReportUpdateForm model = ServiceReportModel class ReportDeleteView(DeleteView): model = ServiceReportModel success_url = reverse_lazy('reports-list') models.py import uuid from django.urls import reverse from django.db import models from django.forms import ModelForm from main import models as main_models from customers import models as customers_models class ServiceReportModel(models.Model): report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, related_name='s_report_number' ) reported_by = models.ForeignKey(main_models.MyUser, editable=False, related_name='reports') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(main_models.MyUser, editable=True, blank=True, … -
Sort queryset using two columns then paginate efficiently
I've a queryset which I want to sort using one of the columns, say date1, and if the value of date1 is None then use another column date2 for sorting and if date2 is also None then use datetime.max. So, this is what I came up with : queryset = sorted(queryset, key= lambda row: row.date1 if row.date1 else row.date2 if row.date2 else datetime.max) and then for paginating (with say 20 in one page) I'm sending back the id of last record of previous request and using that to get the next 20 items (since after sorting ids are now in in random order). Also the entries can be deleted by the users so, using Paginator.page and just fetching the consecutive pages in requests won't work. This is how I find the index of the lastRecord for getting the next 20: lastRecordIndex = next(i for (i, d) in enumerate(queryset) if d.id == lastRecord) queryset = queryset[lastRecordIndex+1: lastRecordIndex+20+1] So, the problem is that this approach works, but is way too slow. Is there anything better I can do? using raw query or something else in django? -
Django - filtering by user
I want to render data from the Route model that belongs to the Driver in their 'accounts' page - so displaying the leave_from, destination etc data they have saved in the database so far. Models.py: class Driver(models.Model): user = models.OneToOneField(User, default=1) first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) tel = models.CharField(max_length=120, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("account", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(Driver, self).save(*args, **kwargs) class Route(models.Model): leave_from = models.CharField(max_length=120, blank=True, null=True) destination = models.CharField(max_length=120, blank=True, null=True) date = models.DateField(auto_now_add=False, auto_now=False) time = models.TimeField(auto_now_add=False, auto_now=False) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) def __str__(self): return self.leave_from I've played with various querysets and the below is the closest to getting there (I think... I'm new to coding and Django). Views.py: def route(request, slug): routedetails = Driver.objects.filter(route=request.user.driver.route_set.all()) context = { "routedetails": routedetails, } return render(request, "route.html", context) With that I am able to get user to display the same number of instances of data in Route for that Driver. Template: {% for route in routedetails %} <p>{{ route.user }}</p> {% endfor %} I've tried all different variations but I feel this has … -
Can't enable huey service on deploy server
I'm working in a Django project deployment. I have integrated huey to run asynchronous tasks. Locally all runs perfectly but now, at the deployment step, I'm getting troubles about huey service activation. I really can't find any information about that because I think that solution should be so simple, bat I really can't find it :(. I'm using nginx and gunicorn services. App runs perfectly on deploy server but huey tasks are not running. I have created a huey.service file located in /etc/systemd/system/, with the following content: [Unit] Description=Huey Service After=redis.service [Service] User=deploy Group=www-data WorkingDirectory=/home/deploy/projects/myproject/ ExecStart=/usr/bin/python3.6 manage.py run_huey Restart=always [Install] WantedBy=multi-user.target But I'm getting following bug: Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: File "manage.py", line 17, in <module> Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: "Couldn't import Django. Are you sure it's installe Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: ImportError: Couldn't import Django. Are you sure it's Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Main process exited, code=exited, stat Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Unit entered failed state. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Failed with result 'exit-code'. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Service hold-off time over, scheduling Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: Stopped Huey Service. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Start … -
django : how to use filter option in this case?
I have one question here is my code view.py class testView(ListView): model = Photo template_name = 'photo/photo_detail.html' context_object_name = 'main_list' def get_context_data(self, **kwargs): context = super(testView, self).get_context_data(**kwargs) context['extra_value'] = Album.objects.filter(Album__name=Photo.album.name) return context and model.py class Album(models.Model): name = models.CharField(max_length=50) description = models.CharField('One Line Description', max_length=100, blank= True) owner = models.ForeignKey(User, null=True) Category = models.ForeignKey(Categories, null=True) price = models.CharField(max_length=20, null=True) productInfo = models.CharField(max_length=50, null=True) objects = models.Manager() second_manager = SecondAlbumManager() class Meta: ordering = ['name'] verbose_name = 'Album' verbose_name_plural = 'Albums' def __str__(self): return self.name def get_absolute_url(self): return reverse('photo:album_detail', args=(self.id,)) @python_2_unicode_compatible class Photo(models.Model): album = models.ForeignKey(Album) title = models.CharField(max_length=50) image = ThumbnailImageField(upload_to='photo/%Y/%m') description = models.TextField('Photo Description', blank=True) upload_date = models.DateTimeField('Upload Date', auto_now_add=True) owner = models.ForeignKey(User, null=True) class Meta: ordering = ['title'] verbose_name = 'Photo' verbose_name_plural = 'Photos' def __str__(self): return self.title def get_absolute_url(self): return reverse('photo:test', args=(self.id,)) Photo object has ForeignKey(Album) so, I want to use Filtered Album objects in template(photo_detail.html) However, I would like to compare the Album foreign value of one Photo object with Album__name and output it to the template, but I do not know how to change Photo.album.name part. Please let me know. i'm sorry Translated into Google Translator. Thank you for reading -
UNIQUE constraint failed: rango_category.name
Hi im following the tango with django tutorial.. I've searched for a solution to this but nothing! the error: IntegrityError at /rango/add_category/ UNIQUE constraint failed: rango_category.name my model: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __unicode__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category) #ForeignKey denotes a relationship between page and category title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __unicode__(self): return self.title my add_category view: def add_category(request): # Get the context from the request. context = RequestContext(request) # A HTTP POST? if request.method == 'POST': form = CategoryForm(request.POST) #Have we been provided with a valid form? if form.is_valid(): #save the new category to the database form.save(commit=True) # Now call the index() view. # The user will be shown the Homepage. return index(request) else: # The supplied form contained errors - just print them to the terminal print (form.errors) else: form = CategoryForm() # Bad form (or form details), no form supplied... # Render the form with error message(if any). return render_to_response('rango/add_category.html', {'form':form}, context) my forms: from django import forms from rango.models import Page, Category class CategoryForm(forms.ModelForm): names = forms.CharField(max_length=128, help_text="please enter the category … -
Django celery tasks number limit issue
I have problem run celery workers to execute same task multiple times in parallel. I ran 3 workers and set --concurrency to 2 for all workers. But it only executes 3 tasks over all 3 workers. I hope to run about 10 workers. celery -A my_app worker -l info -c 2 -n worker1 celery -A my_app worker -l info -c 2 -n worker2 celery -A my_app worker -l info -c 2 -n worker3 Please help me whether I can run more than 3 tasks at a time. -
Django Rest Framework: filtering using a method
I am using Django Rest Framework as a backend for an app. I have a User that has one Wallet. Then I have Item. If a User wants an Item it creates an instance in his/her Wallet called WalletItem. All works well. Now I want to limit the number of items for the User using an attribute limit_usage. First, I added a check to post method adding new instance that checks the number of item instances in User's Wallet. So the user gets 403 when trying to add third WalletItem if limit_usage == 2 for this Item. I would like to override a get_queryset() method or queryset in list()/retrieve() methods so that if anonymous user calls /items/ there are unfiltered items in response. However if the user is authenticated I would like to filter only those Items that s/he is allowed to put in the Wallet, i.e. those that have not exceeded limit_usage for current user. class Wallet(models.Model): user = models.OneToOneField('auth.User', related_name='wallet') class Item(models.Model): valid_from = models.DateTimeField() valid_to = models.DateTimeField() limit_usage = models.PositiveSmallIntegerField(default=0) class WalletItem(models.Model): wallet = models.ForeignKey('Wallet', related_name='%(class)ss') offer = models.ForeignKey('Item', related_name='offer') class ItemViewSet(viewsets.ReadOnlyModelViewSet): queryset = Item.objects.all().order_by('-created_at') serializer_class = ItemSerializer def list(self, request, *args, **kwargs): time_now = now() self.queryset … -
Django admin showing duplicate entries
I'm building an internal application tool with Django where I need to keep track of Point() objects. These objects are connected to Reservation model with custom through relationship. The problem Django seems to be duplicating some Waypoint objects in the admin list view. I think it's got something to do with ordering = ('reservationwaypoint__order',) since if I remove it, the count is correct. So to override I tried adding order_by() to distinct but it didn't work. Seems like order_by is not overriding ordering for some reason.. Admin PostgreSQL models.py class Waypoint(models.Model): class Meta: ordering = ('reservationwaypoint__order',) coords = models.PointField(geography=True) place_id = models.CharField(max_length=100) name = models.CharField(max_length=50) alias = models.CharField(max_length=30, blank=True) client = models.ForeignKey(Client) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @property def get_alias(self): return '{} *'.format(self.alias) if self.alias else None def __str__(self): return self.name.encode('utf-8') def __repr__(self): return self.name.encode('utf-8') class Reservation(models.Model): # .. some other fields route = models.ManyToManyField( Waypoint, through='ReservationWaypoint', related_name='route', ) class ReservationWaypoint(models.Model): class Meta: ordering = ['order'] reservation = models.ForeignKey(Reservation) waypoint = models.ForeignKey(Waypoint) order = models.PositiveIntegerField(default=0) admin.py class WaypointAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'alias', 'client', 'place_id'] list_filter = ('client',) def get_queryset(self, request): return super(WaypointAdmin, self).get_queryset(request).order_by().distinct() admin.site.register(Waypoint, WaypointAdmin) -
Django models not displaying in html tempate
Here is the models I am trying to pass into the html template. It is a model that adds on to the user profile. Every with the models is working correctly and I have already created an object with the model. class Profile(models.Model): # ----- Model Choices ----- STATE_CHOICES = (('AL', 'Alabama'), ('AK', 'Alaska'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('AA', 'Armed Forces Americas'), ('AE', 'Armed Forces Europe'), ('AP', 'Armed Forces Pacific'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('MP', 'Northern Mariana Islands'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('PR', 'Puerto Rico'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VI', 'Virgin Islands'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming')) FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' … -
django easy pdf can't display include static files (css/ images)
I am trying to include some images and css into my pdf using django-easy-pdf, however they aren't showing up. getFile '/static/open-iconic/font/css/open-iconic-bootstrap.css' '...\\mysite\\__dummy__' '...\\mysite\\__dummy__' Traceback (most recent call last): File "...\Python\Python36-32\lib\site-packages\xhtml2pdf\context.py", line 828, in _getFileDeprecated nv = self.pathCallback(name, relative) File "...\Python\Python36-32\lib\site-packages\easy_pdf\rendering.py", line 35, in fetch_resources path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, "")) File "...\Python\Python36-32\lib\ntpath.py", line 75, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType line 0, msg: getFile %r %r %r, fragment: My template file: {% load static %} <link href="{% static '/open-iconic/font/css/open-iconic-bootstrap.css' %}" rel="stylesheet"> my folder structure: mysite - mysite - app -static The static files are working when serving normal webpages, but not in the pdf. Any suggestions? -
How to check if model has an attribute (OneToOneField) with queryset?
I am using the default User model with Agent acting as a OneToOne profile model. I want to create a queryset of all users who has Agent as a field. I'm aware of hasattr but it returns a True/False boolean value so I couldn't implement that into my query. views class AgentSearchResults(ListView): model = User template_name = 'agent_search_results.html' def get_queryset(self): queryset = super(AgentSearchResults, self).get_queryset() # Write something here to check if all users in 'queryset' has 'agent'. return queryset models for reference class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='agent') -
Access the filer plugin directly to link pages with thumbnails
I'm looking at creating a thumbnail based upon the first image which is placed on a page. I was thinking that the best way of doing this would be by accessing the filer plugin directly. The documentation isn't clear on how I can do this. Does anybody know? I know that I can access the Page Titles using: from cms.models import Title Title.objects.all() Is there a similar method for accessing the images on each page? -
Combining DRF unrelated models
I cant seem to figure this out. I want to sort by user joined time and user's photo time. views.py class UserExploreAPIView(generics.ListAPIView): """ User explore API view. """ serializer_class = TimelineSerializer permission_classes = (IsAuthenticated,) pagination_class = SmallResultsSetPagination def get_queryset(self): merged_queryset = Places.get_explore_queryset(self.request.user) queryset = Places.objects.filter(pk__in=merged_queryset) ann_user = User.objects.annotate(photo_time=Extract('date_joined','epoch')) return list(chain(ann_user, queryset)) serializers.py class SomeUserModelSerializer(serializers.ModelSerializer): class Meta: model = SomeUserModel fields = ('photo','id') class PlacesSerializer(serializers.ModelSerializer, IdFieldMixin): photo_link = serializers.CharField(read_only=True) user = UserRelatedSerializer() class Meta: fields = ['id', 'user'] model = Places class TimelineSerializer(serializers.Serializer): photo_time = serializers.CharField(read_only=True) places= PlacesSerializer() #this is the error someuser= SomeUserModelSerializer() class Meta: fields = ['photo_time', 'someuser','places'] ordering = ('photo_time') When I try to get places it says, User has no attribute places. Well yes. places is a foreignkey to user, user wouldn't have places only the reverse. How do I combine these two models? SomeUserModel works because it has onetoone with user, but it doesn't work with places. -
django-tables2 header row urls wrong....can't sort
I can't figure out how to solve this issue about sorting my table: table is rendered at this url: 127.0.0.1:8000/ip_teams/ but when I click on the name of the column to sort the table, url became: 127.0.0.1:8000/?sort=name it excludes the "ip_teams/" path. This is my view: class PagedFilteredTableView(SingleTableView): """ Generic class from http://kuttler.eu/post/using-django-tables2-filters-crispy-forms-together/ which should probably be in a utility file """ filter_class = None #formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, self).get_queryset() self.filter = self.filter_class(self.request.GET, queryset=qs) #self.filter.form.helper = self.formhelper_class() return self.filter.qs def get_table(self, **kwargs): table = super(PagedFilteredTableView, self).get_table() if('page' not in self.kwargs.keys()): self.kwargs['page'] = 1 RequestConfig(self.request, paginate={'page': self.kwargs['page'], "per_page": self.paginate_by}).configure(table) return table def get_context_data(self, **kwargs): context = super(PagedFilteredTableView, self).get_context_data() context[self.context_filter_name] = self.filter return context class FoundationIPTypeList(PagedFilteredTableView): model = tracker_models.FoundationIPType table_class = tables.FoundationIPTypeTable filter_class = tracker_filters.FoundationIPTypeFilter table_pagination = { 'per_page': 10 } this is my table: class FoundationIPTypeTable(django_tables.Table): name = django_tables.Column() class Meta: model = FoundationIPType attrs = {'class': "table table-striped table-condensed table-hover"} fields = ["name", "help_contact_email"] this is my urls: urlpatterns = [ # url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named url(r'^about/$', views.AboutPageView.as_view(), name='about'), url(r'^ip_teams/$', views.FoundationIPTypeList.as_view(), name="ip_team_list"), this is my template: {% extends "base.html" %} {% load render_table from django_tables2 %} … -
ConnectionError 111 in Django admin when hitting FB api
I'm making a custom django admin page that hits up our fb account in python requests to create a user using the fb test users and authenticate with our service. The function hits up: https://graph.facebook.com/v2.10/{}/accounts/test-users to create a new fb user and uses the access token returned in the response to authenticate with our service. When importing the create_new_user function directly it works in a python shell however when using the django admin page and filling out the form the page will throw a ConnectionError 111. Function: def create_new_user(gender, location, registered_date) new_user = status_ok(requests.post( FACEBOOK_URL + TEST_USERS.format(settings.FACEBOOK_APP_ID) + '?' + ACCESS_TOKEN + '&installed=true')) logging.info(new_user) # Now we should authenticate and signup with the app authentication_body = json.dumps({'access_token': new_user['access_token']}) login_response = requests.post(ENV + LOGIN, data=authentication_body, headers=HEADERS) coordinates = Nominatim().geocode(location) payload = {'gender': gender, 'latitude': coordinates.latitude, 'longitude': coordinates.longitude} status_ok(requests.put(ENV + PATH_PROFILE, data=json.dumps(payload), headers=HEADERS)) profile = Profile.objects.get(uid=new_user['id']) profile.registered_date = registered_date profile.save() Form: class CreateTestUserForm(forms.Form): gender = forms.ChoiceField(choices=(('m', 'm'), ('f', 'f')), widget=forms.RadioSelect()) location = forms.CharField(initial='San Francisco') registered_date = forms.DateTimeField(initial=datetime.datetime.now(), widget=forms.SplitDateTimeWidget())