Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display json value in django template?
This is my View.py code... import requests from django.http import HttpResponse from django.shortcuts import render import json def book(request): if request.method == 'POST': r = requests.post('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.POST) book=r.json() else: r = requests.get('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.GET) book=r.json() js=json.dumps(book) if r.status_code == 200: return render(request,'book.html', {'js':js}) return HttpResponse('Could not save data') and question is that how to display return render(request,'book.html', {'js':js}) in Html -
when run command makemigrations following error: IndexError: tuple index out of range
following error get when run command python manage.py makemigrations File "/home/projects/django_work/envs/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 184, in handle ProjectState.from_apps(apps), File "/home/projects/django_work/envs/env/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 174, in from_apps model_state = ModelState.from_model(model) File "/home/projects/django_work/envs/env/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 393, in from_model fields.append((name, field.clone())) File "/home/projects/django_work/envs/env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 464, in clone return self.__class__(*args, **kwargs) File "/home/projects/django_work/envs/env/local/lib/python2.7/site-packages/salesforce/fields.py", line 197, in __init__ related_object = args[0] IndexError: tuple index out of range -
Getting "Node <class 'hvad.manager.TranslationQueryset'> not in depth-first order" when try `recursetree`
In my Django-CMS project I have a model with TranslatedFields from hvad class Category(TranslatableModel, MPTTModel): __metaclass__ = classmaker() translations = TranslatedFields( name=models.CharField(max_length=255), short=RedactorField(blank=True, null=True), description=RedactorField(blank=True, null=True), product_text=RedactorField(blank=True, null=True), pricelist=RedactorField(blank=True, null=True), meta_title=models.CharField(max_length=255, null=True, blank=True), meta_keywords=models.CharField(max_length=255, null=True, blank=True), meta_description=models.TextField(max_length=255, null=True, blank=True) ) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) image = ImageFieldblank=True, null=True, upload_to=get_file_path) slug = models.CharField(unique=True, max_length=255, blank=True, null=True) active = models.BooleanField(default=True) css_class = models.CharField(max_length=255, blank=True, null=True) place = PlaceholderField('place') old_id = models.IntegerField(blank=True, null=True) image_path = models.CharField(blank=True, null=True, max_length=255) And when I try to {% recursetree categories %} on my main page I'm getting this error: Node <class 'hvad.manager.TranslationQueryset'> not in depth-first order Which comes from /env/local/lib/python2.7/site-packages/mptt/utils.py", line 240, in get_cached_trees Going deeper, looked at my queryset thought debugger and it looks like queryset = {TranslationQueryset} [<Category: Foo>, <Category: Bar >, <Category: Another one >, '...(remaining elements truncated)...'] And the thing is, Foo has node_level = {long} 1 while Bar has node_level = {long} 0. That's why in get_cached_trees I get my exeption. if node_level < root_level: # ``queryset`` was a list or other iterable (unable to order), # and was provided in an order other than depth-first raise ValueError( _('Node %s not in depth-first order') % (type(queryset),) ) I bet … -
How can I get more user information after allowing user sign up through Facebook in Django?
I'm using Python-social-auth(https://github.com/omab/python-social-auth) for user signing up through Facebook. Only defect is that I can't get more information about user if user sign up through Facebook. For example, birth, job, hobby are required field but Facebook doesn't give these information. What I want to know is here : In case of birth, Facebook could give this information. Is there any way to do this? Do I have to edit the code of Python-social-auth? I heard that there is a case where after signing up through Facebook, let new window show up for getting more infos about users. I want to see example site and how to do this. Need helps. Thanks -
How can I change the back-end in Matplotlib with Django?
I am creating a webpage that displays a graph that I created in matplotlib using Django. The script runs fine running by itself, but it doesn't work in Django for some reason. This is the error that I get: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. I import matplotlib.use() on the first line, like so: import matplotlib matplotlib.use('TkAgg') from django.shortcuts import render from django.http import HttpResponse from pylab import figure, axes, pie, title I use matplotlib.use('TkAgg) to fix my problems when the script wasn't in Django. I thought that the same solution would work in Django, but it gives me an error. Does anybody know how to fix the code? -
Oauth2 in django, grant_type:client_credentials
I am using oauth2_provider for django rest framework api authentication, Here is my view class NeOrgViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = NeOrg.objects.all() serializer_class = NeOrgSerializer def create(self, request): try: org_obj = NeOrg.objects.using('read').get(email=request.data.get('email')) return Response({'response': 'Organization exists already'}, status=status.HTTP_302_FOUND) except Exception as e: response = org_common_obj.create_organization(request) return Response(response, status=status.HTTP_200_OK) urls.py oauth2_endpoint_views = [ url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name="authorize"), url(r'^token/$', oauth2_views.TokenView.as_view(), name="token"), url(r'^revoke_token/$', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] if settings.DEBUG: # OAuth2 Application Management endpoints oauth2_endpoint_views += [ url(r'^applications/$', oauth2_views.ApplicationList.as_view(), name="list"), url(r'^applications/register/$', oauth2_views.ApplicationRegistration.as_view(), name="register"), url(r'^applications/(?P<pk>\d+)/$', oauth2_views.ApplicationDetail.as_view(), name="detail"), url(r'^applications/(?P<pk>\d+)/delete/$', oauth2_views.ApplicationDelete.as_view(), name="delete"), url(r'^applications/(?P<pk>\d+)/update/$', oauth2_views.ApplicationUpdate.as_view(), name="update"), ] # OAuth2 Token Management endpoints oauth2_endpoint_views += [ url(r'^authorized-tokens/$', oauth2_views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), url(r'^authorized-tokens/(?P<pk>\d+)/delete/$', oauth2_views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete"), ] i am requesting the token by hitting url http://localhost:8000/o/token/ with headers grant_type:client_credentials, client_id: , client_secret: and getting response like this {"access_token": "ia6PI9tqCQVwY7aCAThGSFpCOQqcq5", "token_type": "Bearer", "expires_in": 36000, "scope": "read write groups"}, but when i tried to hit my api localhost:8000/organizations/ withe that access_token in headers like Authorization: Bearer ia6PI9tqCQVwY7aCAThGSFpCOQqcq5, i am getting this response { "detail": "Authentication credentials were not provided." } -
django fullcalendar development server
I have a schedule using django with fullcalendar. Users do not want to use this program with a network server but only one single computer with the development server. Is this a problem ? -
unique_together on add case django admin
I have a vendormenu and menu items are in inlines. So on edit case it is working as expected for both unqiue_together. But on add case the form display {'__all__': [u'Menu price with this Menu and Unit already exists.']} I just wanted to have unique menu and units. But on adding the form with same units it display like mentioned above.. my model is like this: class MenuPrice(models.Model): menu = models.ForeignKey(VendorMenu, related_name='MenuPrice') unit = models.CharField( max_length=10, choices=UNITS, ) def save(self, *args, **kwargs): self.validate_unique() super(MenuPrice, self).save(*args, **kwargs) def validate_unique(self, *args, **kwargs): from django.core.exceptions import ValidationError super(MenuPrice, self).validate_unique(*args, **kwargs) qs = MenuPrice.objects.filter(menu=self.menu) ''' Here i Dont know how to check the values submitted through the form. I can not check the unit cause it is not save to database yet. so IF is the confusion to show the error. qs is empty at this time.''' #if qs.filter(menu=self.menu).exists(): # raise ValidationError({'unit':['Unit must be unique',]}) class Meta: unique_together = (('menu', 'unit'),) I am bit new to django. Please let me know what should I do to check the form submitted data so that i can compare the same units for that menu. Thanks in advanceenter code here -
Django real time notifications
I am developing a web app where a user submits some data every month. The manager of the user should get a notification when a user has submitted the data. The manager then will approve or reject the submitted data upon which the user should get a notification saying it has been accepted or rejected. I am relatively new to Web Development so can anyone provide a simple enough solution for this? -
ger permanent link of DetailView in Tastypie
I want to have permanent links in json vist view. Like this: { "datailurl" : "http://www.example.com/objects/2" }. How to use reverse function inside dehydrate function? #model.py class Kv(models.Model): short_desc = models.CharField() #view.py class KvDetailView(DetailView): model = Kv #urls.py urlpatterns = [ url( regex=r'^(?P<pk>[0-9]+)/$', view=views.KvDetailView.as_view(), name='kvdetail' ),] #api.py class KvResource(ModelResource): class Meta: queryset = Kv.objects.all() resource_name = 'kv' def dehydrate(self, bundle): bundle.data['detailurl'] = reverse(KvDetailView.as_view(), kwargs={'pk': id}) return bundle -
Django user login form user is none
I'm having some trouble logging in users. I have the following views and template: views.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect('/') else: return HttpResponseRedirect('disabled account') else: return HttpResponseRedirect('/invalid') else: return render(request, 'login_page.html', {}) login_page.html {% block content %} {% if form.errors %} <p class="error"> sorry, thats not a valid username or password</p> {% endif %} <form action="/login/" method="post"> <label for="username">User name:</label> <input type="text" name="username" value="" id="username"> <label for="password">Password:</label> <input type="text" name="password" value="" id="password"> <input type="submit" value="login" /> </form> {% endblock %} My problem is, whenever i hit submit in the login form, no matter what the values are, the page is redirected to the /invald/ url. I have a user set up using the admin function but i still keep getting this error. Does anyone know what the problem may be? Do i need a forms.py file with anything in it? -
Django Foreign Key Relation and Display In Template
I am trying to retrieve the FirstName and LastName fields related to a PartyID which is a foreign key on my ToolTransaction model. I have a mysql database which I am using to store the data. My objective is to have the names appear with the appropriate transaction as opposed to the PartyID. I have been able to have all the active transactions display but I am unable to have the First and Last Name show with them as well. Some of my code may be a bit wonky from me trying to troubleshoot the issue, so my apologies. Models: class Tool(models.Model): ToolID=models.CharField(max_length=100, primary_key = True, unique=True, db_column=b'ToolID') Quantity=models.IntegerField(null=False) Location=models.CharField(max_length=100, null=False) CategoryID=models.IntegerField(null=True) Deleted=models.BooleanField(default=0) objects=models.Manager() class Meta: managed=True db_table='Tool' def __unicode__(self): return self.ToolID def get_absolute_url(self): return reverse("ToolSearch:toolSearchResults", kwargs={"pk": self.ToolID}) class Party(models.Model): PartyID=models.AutoField(primary_key=True, db_column=b'PartyID') FirstName=models.CharField(max_length=100, null=False) LastName=models.CharField(max_length=100, null=False) PhoneNumber=models.CharField(max_length=25, null=False) Organization=models.CharField(max_length=100, null=True) Deleted=models.BooleanField(default=0) objects=models.Manager() class Meta: managed=True db_table='Party' def __unicode__(self): return str(self.PartyID) def get_absolute_url(self): return reverse("ToolSearch:borrowerUpdate", kwargs={"pk": self.PartyID}) class ToolTransaction(models.Model): CheckOutID=models.AutoField(primary_key=True) ToolID=models.ForeignKey(Tool, db_column='ToolID', on_delete=models.CASCADE, related_name='ToolID_fk',) PartyID=models.ForeignKey(Party, db_column='PartyID', on_delete=models.CASCADE, related_name='PartyID_fk',) Quantity=models.IntegerField(null=False) CheckOutDate=models.DateField(null=False, default=datetime.datetime.now) CheckInDate=models.DateField(null=True) Deleted=models.BooleanField(default=0) objects=ActiveTransactionManager() #objects=models.Manager() class Meta: managed=True db_table='ToolTransaction' ordering=('CheckOutID',) def __unicode__(self): return str(self.CheckOutID) def get_absolute_url(self): return reverse("ToolSearch:toolCheckin", kwargs={"pk": self.CheckOutID}) View: def tool_transaction_search(request): instance=ToolTransaction.objects.all() ToolTransaction.objects.filter(PartyID=instance.PartyID).select_related() context={ "Transactions": instance, } return render(request, … -
Unable to install virtualenv
I wish to start working with Django. Every guide I've seen states that the first step is to install virtual environment wrapper with pip. Every time I time I give the command pip install virtualenv, either on the power shell or the command line, I get an error saying, it retries connection 5 times and finally gives the following error- could not find a version that satisfies the requirement virtualenv (from versions) no matching versions found for virtualenv -
How I can deny a login and registration a user when already logged
good night all. How do I can deny or redirect an active user , deny the view of " login" and " record "? I want that when this current session will not allow access to those pages , but when he log , if he can see them. It can be directly in the HTML code or only in views ? For your help , thank you! -
Order Model by Dependent Field
I have 2 models, PlayerPick and Game. PlayerPick has a foreign key to the game model, showing which game the pick is for. If I want to order all of the picks by the game time, what would be the best way to do so? Is there a way to automatically add the gameTime field to the player pick model? Please see the code below class PlayerPick(models.Model): player_profile = models.ForeignKey('PlayerProfile') team = models.ForeignKey('Team') class Game(models.Model): team1 = models.ForeignKey('Team', related_name="game_set_team1") team2 = models.ForeignKey('Team', related_name="game_set_team2") time = models.DateTimeField(null=True, blank=True) -
Django ORM Show Latest Message of a conversation
I am trying to get the latest text for each group My model is: class SampleGrouping(models.Model): id1 = models.IntegerField() id2 = models.IntegerField() text = models.TextField() This will be the output if I selected SampleGrouping.objects.all(): ----------------------------------- id | id1|id2| text | order ----------------------------------- 1 | 1 | 1 | Hello World! | 1 2 | 1 | 1 | Hello World2! | 2 3 | 2 | 1 | Hello World3! | 1 4 | 2 | 1 | Hello World4! | 2 5 | 1 | 2 | Hello World5! | 3 6 | 1 | 3 | Hi World! | 1 7 | 1 | 3 | Hi World2! | 2 8 | 1 | 3 | H i World3! | 3 9 | 4 | 1 | Hi Hello! | 1 10 | 4 | 1 | Hi Hello2! | 2 11 | 4 | 1 | Hi Hello3! | 3 12 | 5 | 1 | Gintama 1! | 1 13 | 5 | 1 | Gintama 22! | 2 14 | 1 | 6 | Sakata 1! | 1 15 | 1 | 6 | Sakata 32! | 2 16 | 1 | 5 | Gintama … -
two versions of django installed in ubuntu 16.04
I have two versions installed in my envirment, django 1.8.7 and 1.10 which i have installed with pip! I want to use django 1.10 by default instead of the version 1.8.7. how can I do that ? thank you -
Serializers and ViewSets inheritance of PostgreSQL multitable models?
My environment is based on Django 1.10 & PostgreSQL 9.5 and; I have a childtable which inherits from a parenttable. For each, I have a Django model class, ChildModel and ParentModel respectively: class ParentModel(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey('auth.User', related_name='parents') class Meta: managed = False db_table = 'parenttable' class ChildModel(ParentModel): name = models.CharField(unique=True, max_length=255) abbreviation = models.CharField(unique=True, max_length=2) class Meta: managed = False db_table = 'childtable' Then, I made a serializer for each of these, and one for django.contrib.auth.models.User: class UserSerializer(serializers.HyperlinkedModelSerializer): parents = serializers.PrimaryKeyRelatedField(many=True, queryset=ParentModel.objects.all()) class Meta: model = User fields = (['id', 'username', 'parents']) class ParentModelSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.IntegerField(source='parent.id', read_only=True, allow_null=False) class Meta: model = ParentModel fields = (['id', 'owner']) class ChildModelSerializer(ParentModelSerializer): class Meta: model = ChildModel fields = (['name', 'abbreviation']) Hence, I made three ViewSets, one for each serializer: class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ParentModelViewSet(viewsets.ModelViewSet): queryset = ParentModel.objects.all() serializer_class = ParentModelSerializer permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly) def perform_create(self, serializer): serializer.save(owner=self.request.user) class ChildModelViewSet(ParentModelViewSet): queryset = ChildModel.objects.all() serializer_class = ChildModelSerializer permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly) Is it possible to have inheritance from among serializers and viewsets? I tried the former example, but every time I try to POST a new ChildModel, an exception is thrown showing that … -
Django CMS - Aldryn News Blog not working on Heroku when DEBUG = False
So I am deploying a very basic Django CMS powered blog using Aldrin-news/blog to Heroku and I am running into a very odd issue. When I push the application to Heroku with Debug = True, I am able to freely create and edit blog posts. Below is the template I am using the render the article detail section: articles.html {% load i18n apphooks_config_tags cms_tags sekizai_tags staticfiles thumbnail %} <article class="aldryn-newsblog-article{% if article.is_featured %} aldryn-newsblog-featured{% endif %}{% if not article.published %} unpublished{% endif %}{% if article.future %} future{% endif %}"> {% if detail_view %} <div class="content"> {% render_placeholder article.content language placeholder_language %} {% if not article.published %} unpublished{% endif %} </div> {% endif %} </article> {% addtoblock "css" %}<link rel="stylesheet" href="{% static 'css/aldryn-newsblog/article.css' %}">{% endaddtoblock %} When I turn DEBUG =False this is what I see in the DjangoCMS admin plug in box: Plugin Box It does not seem to want to load anything regarding the article model although as soon as I turn DEBUG = True and redeploy, everything works fine with the blog and there are not issues. Please help, greatly appreciated. -
Usage of latest() method with field types other than date field (Django)
I have just learned about the latest() method. I went to the django's documentation to find out more about it. In the docs it is written: latest(field_name=None) Returns the latest object in the table, by date, using the field_name provided as the date field. However in the tutorial ,that I am following, this method is used together with field name for models.PositiveIntegerField() field(and the model does not specify get_latest_by). I have been trying to search for explanation and similar use of this method, where the field_name is different than date field. I have found some information here where it is said that: ...it probably does work with other total-ordered types too, but not sure... and It does work with primary keys ... Also I have found similar case here, where the latest() method is used with id field. However still I did not find an answer whether it is ok to use this method with something other than date field? Is there any other method which is more appropriate for this kind of task? -
'method' object is not iterable from calling splitlines from a read method
Currently trying to setup my setup.py file for pip installation or simply python setup.py develop installation, however when I run the code, it faults saying that the method is not iterable, regarding to my read function. The code is as follows def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() And the call to the function is the following, install_requires=read('requirements.txt').splitlines() And finally the error I receive is, TypeError: 'method' object is not iterable -
custom django-admin commands - method not found
While running a django-admin command - it can't find a local method. update.py class Command(NoArgsCommand): help = 'Help Test' def handle(self, **options): test1 = 'hello' doThis() def doThis(): test2 = 'hello' running the command python3 manage.py update produces the error: File "/opt/dir/app/management/commands/updatefm.py", line 25, in handle doThis() NameError: name 'doThis' is not defined I can't quite see a reason for this in the documentation https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/#methods -
How to tag Django flat-pages using django-taggit tags?
I am currently using the django-taggit library to tag content on my website. Is there a way to also tag Django flatpages? I am aware of the django-flatpages-plus project, but unfortunately it is no longer maintained. -
Django-tinymce not loading javascript
I have (tried to) set up django-tinymce in my Django project. However, in the inspector, I don’t see the tinymce.min.js being loaded. This is in my settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8123' # TinyMCE configuration TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "articles/build/lib/node_modules/tinymce") TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, "tinymce.min.js") TINYMCE_COMPRESSOR = False TINYMCE_DEFAULT_CONFIG = { 'theme': "modern", 'toolbar': "undo redo | bold italic | bullist numlist | blockquote | removeformat", 'menubar': False, 'statusbar': False, 'schema': "html5", 'max_height': 500, 'max_width': 500, 'min_height': 100, 'min_width': 400 } Removing the TINYMCE_DEFAULT_CONFIG and changing tinymce.min.js into tinymce.js does not change anything—still no tinymce js being loaded. This is my file structure: static |-src | |-styles | |-scripts | |-images |-build | |-css | |-js | |-img | |-lib | | |-package.json | | |-node_modules | | | |-tinymce | | | | |-tinymce.js | | | | |-more_tinymce_files_here |-node_modules |-gulpfile.js |-package.json In my template I do have {{ form.media }}, but maybe that‘s the problem. I am not sure how to debug this. How can I make sure that the tinymce javascript loads? -
Django model with a list
How to implement a list in a Django model? Lets say I have a UserProfile model, and each user can have a list of mortgages (undefined quantity) defined by MortgageModel. class MortgageModel(models.Model): bank_name = models.CharField(max_length=128) sum = models.BigIntegerField() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # list of morgtages? my only idea is to make a old school list, where every mortgage can point to another one or null, like this: class MortgageModel(models.Model): bank_name = models.CharField(max_length=128) sum = models.BigIntegerField() next_mortgage = MortgageModel(null=True, default=null) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mortgages = MortgageModel(null=True, default=null) is there any other possibility?