Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to encrypt a password field in django
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field. I referred to this link Password field in Django model But the answer is old and need to know what the present approach is. My model is as below class Crew(models.Model): crew_id = models.AutoField(primary_key=True) crew_code = models.CharField(max_length=200, null=False, unique=True) crew_name = models.CharField(max_length=200, null=False) crew_password = models.CharField(max_length=200, null=False) -
How can i make a custom list of files in django?
I have an app in Django where users upload some files(xlsx), the information gets extracted and the files are stored in /media. I want a page/view where the users should be able to browse through the files by folder structure or alphabetically and they should be able to download them from the server. What i have now is as basic as it gets: this is the .html {% block Content%} {% if documents %} <ul id="files_ul"> {% for document in documents %} <li> <a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a> </li> {% endfor %} </ul> {% else %} <p> No documents. </p> {% endif %} {% endblock %} I have a model named Document and i've added this: + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) to urls.py which i know it's not secure. I don't need something like Filer because i already have that but i didn't yet figure out how to configure. I only know python and that not extensively and i'm new to Django so any help would be really appreciated. It would be of great help if you could show me at least how to change the name of the files that appear now in this view, document.docfile.name Results in … -
How to use django default group permission with dejango-graphene?
I want to do a API with django-graphene, but i want to apply the django default group permission when i user make a request this will have permission if his user-group allow him to CRUD. Thanks. -
Pythonanywhere Django Error running WSGI application ImportError:
I am trying to build a webapp in Pythonanywhere, and am trying to install django-filter module. I have installed the module through PIP and made all the required changes in settings.py, and app's views, models and the HTML page. Though the module is working in my local machine, in Pythonanywhere I am getting the following error 2017-06-09 05:07:18,654: Error running WSGI application 2017-06-09 05:07:18,656: ImportError: No module named 'django_filters' 2017-06-09 05:07:18,656: File "/var/www/user_pythonanywhere_com_wsgi.py", line 29, in <module> 2017-06-09 05:07:18,656: application = get_wsgi_application() 2017-06-09 05:07:18,657: 2017-06-09 05:07:18,657: File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2017-06-09 05:07:18,657: django.setup(set_prefix=False) 2017-06-09 05:07:18,657: 2017-06-09 05:07:18,657: File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup 2017-06-09 05:07:18,657: apps.populate(settings.INSTALLED_APPS) 2017-06-09 05:07:18,657: 2017-06-09 05:07:18,658: File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate 2017-06-09 05:07:18,658: app_config = AppConfig.create(entry) 2017-06-09 05:07:18,658: 2017-06-09 05:07:18,658: File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 90, in create 2017-06-09 05:07:18,658: module = import_module(entry) My wsgi file is as follows. I don't know how to edit it. # This file contains the WSGI configuration required to serve up your # web application at http://user.pythonanywhere.com/ # It works by setting the variable 'application' to a WSGI handler of some # description. # # The below has been auto-generated for your Django project import os import sys # … -
is_paginated not working properly for class based views in Django
book_list.html {% extends "base.html" %} {% block content %} <h3> Available books </h3> {% if book_list %} <ul> {% for book in book_list %} <li> <a href = "{{ book.get_absolute_url }}">{{book.title }}</a> <small> by {{book.author }}</small></li> <p>{{ book.summary }} {% endfor %} <ul> {% endif %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% else %} <h4> pagination not working</h4> {% endif %} {% endblock %} class in views.py : class BookListView(generic.ListView): model = Book paginate_by = 2 queryset =Book.objects.all() urls.py : urlpatterns =[ url('^$',views.index, name ='index'), # matching with an empty string url('^books/$',views.BookListView.as_view(),name ='books'), url('^book/(?P<pk>\d+)/$',views.BookDetailView.as_view(),name='book-detail'), ] Book model : class Book(models.Model): title=models.CharField(max_length=100) author = models.ForeignKey('Author',on_delete=models.SET_NULL,null = True) summary = models.TextField(max_length=200,help_text="Enter the description") isbn = models.CharField('ISBN',max_length=13 ,help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>' ) genre = models.ManyToManyField(Genre,help_text = 'selct a genre for this book') class Meta: ordering =["title"] def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail',args=[str(self.id)] ) The book_list gets rendered perfectly, the problem is with the paginator, the is_paginated condition is … -
How to listen to channels in a running code?
Hie, I am working on a project of service hailing app. Its has a request/accept service mechanism just like uber. I have successfully created different channels for each of the service provider. When a request arrives I want to send the request to each service provider one at a time with a time period of 30 seconds to accept or reject it. If someone reject it or timeout occurs then send the request to next provider. If accepted then terminate the sending request operation. I am able to send the request periodically but I am unable to handle the feedback from the provider. How do I do it? Should I create a separate channel for internal communication? If so how to listen to it while looping over the service provider list? -
How to handle asynchronous tasks in Django python
How to perform asynchronous tasks using Django. Does Celery supports callbacks and what is the difference in using Celery or asyncio. -
How can I return user ID with token in Django?
I generate tokens using default view in Django: url(r'^login/', rest_auth_views.obtain_auth_token), I have a problem because my frontend doesn't know what is the currently logged in user ID. Should I return it with token or maybe create other request? I know that there is a lot of different ways, but I would like to choose the most optimal solution. -
jQuery/Ajax like button not working properly second time
I'm trying to create an Ajax like button for my Django project(Python's framework). Basically, what I'm doing is making a partial update on index.html when the Ajax call is a success. It works fine the first time, but when a button with the same id is clicked for the second time, it will reload the entire page, which is not what I expect. Could anyone teach me how to prevent this from happening? I'm not sure if the Python side has anything to do with this, but I'm going to paste some of the codes anyway. Thank you. main.js $('button').on('click', function(event){ event.preventDefault(); var element = $(this); $.ajax({ url : element.attr("data-id") + '/like/', type : 'POST', data : { card_id : element.attr("data-id")}, success : function(response){ console.log(response); $('#like-area-' + element.attr("data-id")).load(document.URL + ' #like-area-' + element.attr("data-id")); } }) }) // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } … -
Limit display rows in Admin Panel Django
I have Admin.py as follows . from django.contrib import admin from do.models import * class NewsAdmin(admin.ModelAdmin): list_display=['time','message'] admin.site.register(do_model,NewsAdmin) I while i go to the admin panel and go to the do_models , it is showing me huge lots of data . I dont want to see all data from the beginning date , is it possible that i can limit data till 20 or 30 lines of data and rest of data should not be shown like paginating so that it load easily . Kindly suggest . -
Get fields from a third model based on the foreign key of a second model
I have three models, one of which has an ID from each of the others to join them. The issue I am trying to solve is how I can get the values From table one into table three using table two to join them in the serializer, or if that is even the approach I should be taking to begin with. model class ModelOne(models.Model): color = models.CharField() size = models.CharField() class ModelTwo(models.Model): One_id = models.ForeignKey(ModelOne) Three_id = models.CharField() class ModelThree(models.Model): example serializer class ModelThree Serializer model = ModelThree fields = ('color', 'size') def get_color(self, obj): ??? def get_size(self, obj): ??? my db structure ModelOne ------------------------------------- id color size ModelTwo ------------------------------------- id ModelOneID ModelThreeID ModelThree ------------------------------------- id -
Serializer perform_create not being called
I'm a little messed here with this thing... Lost few hours and did try lots of variants of this code, but with no success. I need create an related object called ContaCorrente to each user as Usuario when it creates an account. Those are my models: class Usuario(models.Model): """Classe que ira gerir o cliente final, cadastrado via APP ou Webapp""" nome = models.CharField(max_length=60) sobrenome = models.CharField(max_length=60) telefone = models.CharField(max_length=20) .... FOR THE SAKE OF BREVITY def __str__(self): return self.nome + ' ' + self.sobrenome class ContaCorrente(models.Model): """Controle financeiro do Cliente/Usuario cadastrado""" pontos = models.DecimalField(max_digits=10, decimal_places=2, default=0) saldo_reais = models.DecimalField(max_digits=10, decimal_places=2, default=0) usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, related_name='conta_corrente') And this is my Serializers: class ContaCorrenteSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ContaCorrente fields = ('pontos', 'saldo_reais', 'usuario_id') class UsuariosSerializer(serializers.HyperlinkedModelSerializer): conta_corrente = ContaCorrenteSerializer(read_only=True) id = serializers.ReadOnlyField() class Meta: model = Usuario fields = ( 'id', 'nome', 'sobrenome', 'telefone', ... FOR THE SAKE OF BREVITY ... 'updated_at', 'conta_corrente' ) def perform_create(self, serializer): conta = ContaCorrente.objects.create(usuario_id=self.kwargs.get('pk'), saldo_reais=0, pontos=0) conta.save() serializer.save() return serializer I did try lots and lots of variants of this code, but can't find where it explodes. The Usuario model get persisted, but the ContaCorrente not! Someone has any help to give? Thanks! -
merge two multi dimension lists into one list python
I have two lists: a_list = [['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......] b_list = [['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......] I need to merge a_list with b_list so it becomes: combined_list = [['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......] How would I achieve this? -
django many to many field does not save
I have the following models: class Offering(models.Model): entity = models.OneToOneField('companies.entity') company_type = models.ManyToManyField(CompanyTypeChoice, blank=True) @python_2_unicode_compatible class Tag(models.Model): word = models.CharField(max_length=64) @python_2_unicode_compatible class Entity(models.Model): tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True) I have the following loop that I want to create a M2M tag relation: offerings = Offering.objects.all() for o in offerings: for ct in o.company_type.all(): tag = Tag.objects.get(word=ct.title) e = Entity.objects.get(pk=o.entity.id) e.tags.add(tag) This does not save the M2M relationship. What am I doing wrong? -
how do I allow user to delete their model objects in django?
Ive been struggling to come up with a solution to allow a logged in user in django to delete their own created model objects. Im testing on service objects (a service order they create with a ServiceForm(ModelForm). I have django-safedelete in use to preserve the deleted objects in django admin, but disappear for the user. I have this behavior working, but cannot actually delete the objects, tried a lot of permutations with in the delete_service url, pk=id in the view, a lot of different things but still get same type of error. (As noted below on the service page, there is a context showing the model object's data in a panel, and below that a delete button/modal popup which uses a context for the DeleteServiceForm function to delete the object. I heard you cant use more than one context per template but if not how is one to get around this problem) Im using python3.5, django1.11, postgresql db, apache2, on ubuntu16.04 vm. ''' #ERROR Exception Type: NoReverseMatch at /dashboard/service/ Exception Value: Reverse for 'delete_service' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['dashboard/deleteservice/(?P<pk>\\d+)/$'] ''' # dashboard/urls.py url(r'^dashboard/deleteservice/(?P<pk>\d+)/$', views.delete_service, name='delete_service'), url(r'^dashboard/service/$', views.service, name='service'), # dashboard models.py # django-safedelete model … -
Mezzanine, filebrowser and image upload src wrong
I have a problem with the media, but I can't understand where to look to fix the problem. If I upload a file through the filebrowser, is correctly uploaded in the static/media/uploads. The first problem is the thumbnail that is not generated and I got the missing image icon in the list of the media. I tried to fix this reinstalling Pillow. Nothing. In a post or a page, I can select the uploaded image and I see the image the rich text editor. The url is correct /static/media/uploads/foo.jpeg. The second problem is in the published post (or page) even if the image was correctly previewed in the rich text editor, in the published post I get the image load error icon and the img src is just /static/media/ I already setup the 777 for the media folder. Any clue where is the problem? -
IntegrityError on update_or_create
I'm getting an IntegrityError that seems like an impossibility: ShippingAddress.objects.update_or_create( subscription=subscription, defaults=address_dict, ) (where "subscription" is an instance of a model related via a OneToOneField) raises the error IntegrityError: (1062, "Duplicate entry '42' for key 'subscription_id'") despite subscription being the only key added to the filter. Even more strangely, neither ShippingAddress.objects.get( subscription=subscription, ) nor ShippingAddress.objects.filter( subscription=subscription, ) raise the same error. What could be messing up the update() call? -
Django REST extend UserSerializer with ProfileSerializer coming as 'null' when ProfileSerializer exists
In Django REST API, when I login I over-rode ObtainAuthToken to send back a user model. E.g; serializer_context = { 'request': request } user_serializer = UserSerializer(user, context=serializer_context).data Response({'token': token.key, 'user': user_serializer}) I want my UserSerializer (which successfully sends the User object) to include Profile, which has a FK to the User table. In my serializers: class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = '__all__' class UserSerializer(serializers.HyperlinkedModelSerializer): profile = ProfileSerializer( ) class Meta: model = User fields = ('id', 'email', 'profile', 'username') I successfully get back a javascript object that has all of user properties in it, but user.profile = null. Why? :( -
How to automate django_haystack's rebuild_index command on production or live
I have used Django_Haystack with Whoosh for effective search on an application I worked on, which worked fine for what I need it for. To build index on development mode, Django_Haystack documentation advised to run the following command: python manage.py rebuild_index However, after deploy, I figured out that all new details input to that site are not indexed and they fall out of search because there is no measures that automatically build those details into index. Kindly assist me, how do I automate django_haystack's building index on production such that new details gets indexed automatically? -
How to disable middleware for certain functions using a decorator?
I would like to mimic the behavior of csrf_exempt(see here and here). The problem with following the CSRF middleware way of doing it is that it uses from django.utils.deprecation import MiddlewareMixin, which is deprecated. Is there a way I can do this using the recommended way of creating middleware in Django 1.11? I am also aware of from django.utils.decorators import decorator_from_middleware but that's the opposite of what I want. Anybody have any ideas? -
Database indexes in Django 1.11: difference between db_true, indexes and index_together
Django 1.11 offers new ways to create database indexes. So far we had db_index=True in each field: # example 1 class Person(models.Model): name = models.CharField(db_index=True) age = models.IntegerField(db_index=True) Now we have models.Index and the possibility of declaring indexes within the class Meta block — or even index_together. That said I have two doubts: 1. Is the code from example 1 doing the same thing as example 2 below? # example 2 class Person(models.Model): name = models.CharField() age = models.IntegerField() class Meta: indexes = [ models.Index(fields=['name']), models.Index(fields=['age']) ] 2. What about index with multiple fields and index_together: are examples 3 and 4 below doing exactly the same thing? # example 3 class Person(models.Model): name = models.CharField() age = models.IntegerField() class Meta: indexes = [ models.Index(fields=['name', 'age']) ] # example 4 class Person(models.Model): name = models.CharField() age = models.IntegerField() class Meta: index_together = [['name', 'age']] What are the diferences between 1 and 2, and differences between 3 and 4? What am I missing? Many thanks. -
How to check existance of an object in DetailView class inside the ListView class?
I am doing Django official tutorial and I want to improve my IndexView in a way that it returns the questions with at least one choice. I tried to work on the get_queryset method but I couldn't succeed. View class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): cons = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) Model: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text @python_2_unicode_compatible class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Urls urlpatterns=[ #/polls/ url(r'^$',views.IndexView.as_view(),name='index'), #/polls/5/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] -
NoReverseMatch Error Django/Apache
I have an HTML page with a drop-down menu and linked submit button, to post the value of the selected option. The post works fine, and the code executed from the post, but I receive a 'NoReverseMatch' error at the 'HttpResponseRedirect' line in the view dedicated to processing the post data. Here's snippets from the program: In the app/urls.py file: ... url(r'^classifications/(?<class_list>[\w-]+)/$', 'Event_Classification_View'), url(r'^class_submit/$', 'Event_Classification_Submit_View'), ... In the app/views.py file: ... def Event_Classification_View(request, class_list): if class_list == 'NULL': return render_to_response('app/Classifications.html', context_instance=RequestContext(request)) else: return render_to_response('app/Classifications.html', {'class_list': class_list}, context_instance=RequestContext(request)) def Event_Classification_Submit_View(request): ... classification_event_list = #list of items return HttpResponseRedirect(reverse('app.views.Event_Classification_View', args=(classification_event_list,))) ... What should happen is the user clicks a button on the Home page that takes them to /localhost/app/classifications/NULL/, which is accounted for in the first listed urls.py line. This loads the Event_Classification_View, and since class_list == NULL nothing is passed to the HTML file, and it (which contains the post and drop-down) is loaded. This works fine. When the user selects an option in the drop-down and clicks the "Submit" button with it, this loads the url /localhost/app/class_submit/, which runs the Event_Classification_Submit_View method. After processing the post and running extra code, this should create the object classification_event_list, which is then returned … -
Django rest framework: Do I really need two separate serializers?
I have an APIView class with post and patch. The serializer for this class is a ModelSerializer. The thing is: I would like post to require all fields, but patch to allow only a subset of those fields, any subset as long as the field name is legitimate. Do I really have to create two separate serializers for it? I can't find a way to define those two different behaviors in one. -
Cannot get succes_url to be configured correctly for django
views.py class SongDelete(DeleteView): model = Song success_url=return reverse_lazy("music:detail", song) models.py class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() def get_absolute_url(self): return reverse('music:detail', kwargs={'pk':self.pk}) #return details of the album page we just created with the primary key def __str__(self): return self.album_title + " - " + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) is_favorite = models.BooleanField(default=False) song_file = models.FileField(null=True) def get_absolute_url(self): return reverse('music:detail', kwargs={'pk':self.album_id}) def __str__(self): return self.song_title urls: url(r'(?P<pk>[0-9]+)/song/delete/$', views.SongDelete.as_view(), name='song-delete'), Problem: I want to redirect to the details view music/ after deleting a song from the page. I can redirect to the index page but having problems redirecting to the details of the album page which has a primary key. I am sure it's the reverse_lazy function in the success_url which needs to be fixed. Any suggestions?