Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get django to return both an HttpResponse AND render a different template
i have a method in views.py that can download a file i've constructed via an HttpResponse['Content-Disposition'] attachment: response = HttpResponse(content_type='text/json') response['Content-Disposition'] = 'attachment; filename="%s"' % (dgjf) response.write(dgjson) this works fine if my the method returns response but, after the download i want to redirect to a confirmation page that i render like this: confirmMsg = render(request,'confirmation.html',context) which i would normally return from the same method. but how can i get the response to do download AND also redirect to the confirmation? -
How to copy django admin change_list functionality to an app?
I want to copy out the object list functionality from the django admin site into my app. Specifically, I have a page that I want to copy the change_list.html or change_list_results.html templates and into my app. I don't want to customize the admin site, I want to use that functionality in my app. For example, how do I create the c1.formset variable that is used these templates in my view, so that I can use the templates in my app? Also, where is that admin code for this? I can't seem to find it. Thanks! T -
Creating Django File from local PNG raises UnicodeDecodeError
I'm working on a Django web app that allows users to upload presentations. The presentation needs to be converted to images, one for each slide, and the images need to be saved to an ImageField as part of a model. However, when I try to save the local image to the model, Django throws a UnicodeDecodeError on the header of the image file. UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I did a little reading, and found that this is part of the valid header for a PNG image file. It seems that for whatever reason, Django is attempting to decode the binary file as unicode. Here's the model I'm attempting to save the image to: class PresentationSlide(models.Model): ... image = models.ImageField(upload_to=upload_to) The upload_to function saves uploaded files with a base64 encoded UUID. In a view, I validate the form, get the presentation file, and use a custom library to convert it to individual images in a temporary directory. The idea then is to create a PresentationSlide instance for each of these images. Below is how I attempt to create the model instances and save the images. presentation = Presentation.objects.create( description=form.cleaned_data['description']) slides = [PresentationSlide.objects.create( … -
Query Django Wagtail Document Model
I have a client that has hundreds of documents that are tagged that we need to query and list on a page. I want to write a TemplateTag so its more reusable, but I have no idea how to query the builtin Wagtail image and document models. The below code is what I am starting with Document.objects.all() added for placement only. Any help would be appreciated. @register.inclusion_tag( 'tags/_document_snippets.html', takes_context=True ) def document_snippets(context): documents = Documents.objects.all() return { 'documents': documents, 'request': context['request'], } -
Django - show result (error) with javascript
I have form, that accepts number between 1-6 and a file. You can see code in my other question: Django-Javascript Modal form validation I have to validate form, without having to reload it as it is modal form and it closes on refresh (or is should open it on refresh, but i don't really like the idea of reloading). So i want the modal to show error, if there is any (wrong file type, model already exists...) How would i achieve this? Somebody suggested me to post form asynchronously and show error with javascript. How would i send javascript message from views in django, without the page having to reload? Could it be done with Json? How? Thank you in advance! -
Django autocomplete light not working for my widget
Hey I'm trying to implement django-autocomplete-light in my django project, but unable to get it to work. I think its a problem with the urls.py file in my app. urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<playlist_id>[0-9]+)/$', views.detail, name='detail'), url(r'^create_playlist/$', views.create_playlist, name='create_playlist'), url(r'^(?P<playlist_id>[0-9]+)/create_song/$', views.create_song, name='create_song'), url(r'^song-autocomplete/$', SongAutocomplete.as_view(), name='song-autocomplete'), url(r'^(?P<playlist_id>[0-9]+)/delete_song/(?P<song_id>[0-9]+)/$', views.delete_song, name='delete_song'), url(r'^(?P<playlist_id>[0-9]+)/delete_album/$', views.delete_playlist, name='delete_playlist'), url(r'^(?P<playlist_id>[0-9]+)/add_preferences/$', views.add_preferences, name='add_preferences'), ] This is my form. class SongForm(forms.ModelForm): song_title = forms.ModelChoiceField( queryset=Sngs.objects.all(), widget=autocomplete.ModelSelect2(url="login:song-autocomplete") ) class Meta: model = Song fields = ['song_title'] This is the class based view class SongAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Sngs.objects.none() qs = Sngs.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs the widget does not suggest any content and I'm unable to type into it. but when I go to the url of the view it shows me data. also when i change the url like: url(r'^(?P<playlist_id>[0-9]+)/create_song/song-autocomplete/$', SongAutocomplete.as_view(), name='song-autocomplete'), It gives me an error: Reverse for 'song-autocomplete' with no arguments not found. 1 pattern(s) tried: ['login/(?P<playlist_id>[0-9]+)/create_song/song-autocomplete/$'] I'm new to Django and still learning so help would be highly appreciated. Thank you. -
What kind of widget to use?
I am new in Django and want to know how create next thing: 1) As you can see from the picture I have form with 3 field. 2) First field must be select widget but in the same time all fields must be editable as normal CharField. 3) When user select lets say 'Manager' in first field I want to load other information to fields. TABLE: (What kind of array I need to use?) "Manager" - "M" - 'Manager is the person...' "Developer" - "DEV" - 'Developer is the person...' "ADMIN" - "AD" - 'ADMIN is the person...' "Analist" - "AN" - 'Analist is the person...' modals.py: class Characteristic(models.Model): class = models.CharField(_('Class'), max_length=250) symbol = models.CharField(_('Symbol'), max_length=250) description = models.TextField(_('Description')) -
csrftoken tag not working after upgrade to Django 1.11
I have inherited a Django app that I initially got working on Django 1.9. Recently I have migrated it to Django 1.11 and Python 3.4 (from 2.7). Since then, some admin view that I have has started failing with a 403 Forbidden error, CSRF verification failed. I looked at the documentation, and checked the following things: I'm still using MIDDLEWARE_CLASSES, but django.middleware.csrf.CsrfViewMiddleware is included in my configuration (it's second, after SessionMiddleware and CommonMiddleware). The template used includes the {% csrf_token %} stuff. The view uses render_to_response(), and passes RequestContext(request) as the third argument to it. (None of these changed during or after the Django/Python upgrades, as far as I know.) I'm not that experienced with Django, although I have quite a bit of Python web programming experience. What am I missing/how could I debug further? -
Handling many request simultaneously in Python/Django
I have been asked this question many time but may be i didn't get the exact answer of this. SO let say we have one file, which has got the (read,write) access to all the user. when one user try to access this file and doing some modification in it , same time another user will try to access it and will delete some of the details from it. So how we can handle this that both the user should be allow to access or make the changes simultaneously in the file and changes from both the user should be present there. Multi threading is one concept but as i am aware python is not with multi threading . Then how we can write to resolve such issue ?? Thanks in advance Anendra -
'HttpResponseForbidden' object has no attribute
I'm trying to create an api for our users. I've decided to use Django-rest-framework. Users need only GET requests. Each GET request has to have 'token' attribute to determine which data should we return. So I've created a function which tries to get user object from request object. def get_user(request): token = request.GET.get('token') if not token: return HttpResponseForbidden() user = get_object_or_404(User,auth_token=token) return user I want to use this function in my view: @api_view(['GET']) def products(request): user = get_user(request) products = user.products.all() serializer = ProductSerializer(products, many=True) return JsonResponse(serializer.data, safe=False) The problem is that when I doesn't provide token attribute, it raises: AttributeError at /api/products/ Exception Value: 'HttpResponseForbidden' object has no attribute 'products' Instead of proper response. I can do: @api_view(['GET']) def products(request): user_or_response = get_user(request) if user_or_response.__class__ != User: return _or_response products = _or_response.products.all() serializer = ProductSerializer(products, many=True) return JsonResponse(serializer.data, safe=False) As you can see, it doesn't automatically return forbidden response, instead, it returns it as user. I can return it in products view but maybe there is a better way to do this with Django-rest-framework. What should I do? Do you have a better approach or any advice? -
Getting { "detail": "Method \"POST\" not allowed." } from ModelViewSet in DRF
Hi I'm trying to send POST request to create_mole() method, but I get { "detail": "Method \"POST\" not allowed." } Tokens are correct views.py class MoleViewSet(ModelViewSet): queryset = Mole.objects.all() permission_classes = [AllowAny] def get_serializer_class(self): if self.request.method in SAFE_METHODS: return MoleReadSerializer return MoleWriteSerializer def get_queryset(self): if self.request.method in SAFE_METHODS: return self.queryset.filter(owner=self.request.user.id) return self.queryset def create(self, request, format=None,*args, **kwargs): print(allowed_methods(self)) return Response(request.data,status=200) @parser_classes((FormParser, MultiPartParser)) def create_mole(self, request,*args,**kwargs): owner = request.user.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.data['owner'] = owner serializer.data['malignant'] = 13 serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) urls.py from channels.routing import route from rest_framework.routers import DefaultRouter from .views import MoleViewSet router = DefaultRouter() router.register(r'moles', MoleViewSet, base_name='moles') models.py class Mole(models.Model): class Type: UNDEFINED = 0 BENIGN = 1 MALIGNANT = 2 title = models.CharField(max_length=42, null=True) owner = models.ForeignKey(to=Person, related_name='moles', null=True) image = models.ImageField(upload_to=get_image_path, ) malignant = models.IntegerField(null=True) body_part = models.ForeignKey(BodyPart, related_name='moles', null=True) date = models.DateField(auto_now_add=True, null=True) ModelViewSet's create() method sends the same error ............................................. -
Pass data from template to view in Django
I'm building a bus reservation website using Django. After user searches buses on a specific route, a list is displayed showing available buses. Each list item i.e. bus has a book button which leads to new page called 'seats.html'. I want to pass the bus number and other information to the view of 'seats' so that I can display the number of seats available and javascript can also use this info. Here is my code views.py def find_bus(request): form = forms.FormFindBus template = 'home.html' context = {'form': form} return render(request, template, context) def select(request): bus_type = request.GET.get('bus_type') bus_from = request.GET.get('bus_from') bus_to = request.GET.get('bus_to') date_string = request.GET.get('date') qs = Bus.objects.filter(type_of_bus=bus_type, route__location_from=bus_from, route__location_to=bus_to, date=date_string) context = {'qs': qs,} template = 'select.html' return render(request, template, context) def seats(request): template = 'seats.html' context = {} return render(request, template, context) select.html {% for info in qs %} <a href="{% url 'book:seats' %}">Book</a> <ul> <li><b>Bus Number -</b> {{ info.bus_number }}</li> <li><b>Route -</b> {{ info.route }}</li> <li><b>Date -</b> {{ info.date }}</li> <li><b>Time -</b>{{ info.time }}</li> </ul> </div> {% endfor %} As you can see query set gets passed in select.html where I use for loop to display all the buses available along with their information. I then … -
Developing a Podcast Website
I recently got a client who is looking to have a website built with the main purpose of it being an audio podcast. As I get ready to start planning and building this site I wanted to check what are the best options for building a podcast site? A lot of the Q/As I found on stackoverflow were from 2009 so I feel a lot has changed since then. Does anyone have experience in the recent past developing a podcast site? What are the best options for CMS or other system? So some of the info of needs for the podcast site are it will be weekly updated with a podcast and an accompanying blog post/description and that is really about it. Maybe some kind of sign in option for comments if that function is available as it is on WP. That's about it. If you need any other info I will gladly provide it. Thanks for the help! -
When preparing to upgrade Django is there an upgrade check?
Is there an easy way it identify potential issues when upgrading Django? What features have been deprecated? What 3rd party libraries have compatibility issues? I know there are release notes with some of this information. I'm upgrading several sites and several different version at the same time. -
Django 1.11 is not loading css files
I have the next configuration: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^manager/', include('manager.urls')), #Static pages url(r'^index', TemplateView.as_view(template_name='index.html'), name='index'), url(r'^', TemplateView.as_view(template_name='index.html'), name='index'), url(r'^contact', TemplateView.as_view(template_name='contact.html'), name='contact'), url(r'^services', TemplateView.as_view(template_name='services.html'), name='services'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'pf.app.pfs', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), #'/var/www/static/', ] I executed the command: python manage.py collectstatic And the files are generated, also I added a css file with a single rule but and executed the command again. But, in the momento to add it to my html file <head> {% load static %} <link rel="stylesheet" href="{% static '/css/style.css' %}" /> </head> in the html I get: <link rel="stylesheet" href="/static/css/style.css"> And in the terminal: "GET /static/css/style.css HTTP/1.1" 404 1766 What I have wrong in my static files configuration? -
django channels send many in single function
I am new in django channels. It is a image uploads app. Since it takes a long time. I am trying to print log onto front end. My code is like: def upload(m): m.reply_channel.send({ 'accept': True, }) socket_handler = SocketHandler(m) inst = ImageUpload(socket_handler=socket_handler) inst.newPic(m) m.reply_channel.send({ 'close': True, }) return And SocketHandler is like: class SocketHandler(logging.Handler): def __init__(self, message, *args, **kwargs): super().__init__(*args, **kwargs) self.message = message def emit(self, content, *args, **kwargs): self.message.reply_channel.send({ 'text': '['+datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')+'] '+content.name+' '+content.msg, }) But not like my expectation, the logging only shows up on front end after the upload function returned. I would like to list the logs one by one. So what can I do? -
Is it possible for me to install django-cors-headers version 1.1.0? If so, how?
When I try to install django-cors-headers v1.1.0 on Django 1.7, I'm getting the pip error "No matching distribution found for django-cors-headers-1.1.0" Is it possible for me to install version 1.1.0? If so, how? -
geodjango with mysql getting error django.db.utils.OperationalError: (1045, "Access denied for user
seetings.py DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql','django.contrib.gis.db.backends.mysql' 'OPTIONS': { 'read_default_file': os.path.join(PROJECT_ROOT,"my.cnf"), }, }, } without 'django.contrib.gis.db.backends.mysql' the code is working fine but since i want to use django geolocation using mysql i added this (if I don't add I get "'databaseoperations' object has no attribute 'geo_db_type'" error), and now I am getting "django.db.utils.OperationalError: (1045, "Access denied for user ---" error although the user has full privileges. Please help I am new to django Thank you -
Python/Django : form data validation in TemplateView
I'm beginner in Django and have a little trouble with TemplateView and Forms and trying to write something similar to StackOverflow. So I have a section with question and a section with answers. views.py class QuestionPageView(TemplateView): question_form = QuestionCreationForm(prefix = 'question_form') AnswerFormSet = formset_factory(AnswerCreationForm, extra = 2) answer_form = AnswerFormSet(prefix = 'answer_form') template_name = 'app/ask_question.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['question_form'] = self.question_form context['answer_form'] = self.answer_form return self.render_to_response(context) def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['question_form'] = QuestionCreationForm(request.POST) context['answer_form'] = self.AnswerFormSet(request.POST) if context['question_form'].is_valid(): context['question_form'].save() return self.render_to_response(context) And forms.py class QuestionCreationForm(forms.ModelForm): title = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Title of your question' }), required = False ) text = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Text of your question' }), required = False ) language = forms.ModelChoiceField(queryset = Language.objects.all()) class Meta: model = Question fields = ('title', 'text', 'language') def save(self, commit = False): return super(QuestionCreationForm, self).save(False) def clean(self): results = super(QuestionCreationForm, self).clean() return results class AnswerCreationForm(forms.ModelForm): text = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Text of your answer' }), required = False ) correct_answer = forms.BooleanField(widget = forms.CheckboxInput, label = _('Is answer correct?'), required = False) class Meta: model = Answer fields = ('text', 'correct_answer') … -
Progress bar for back end python programs on Django or other web frameworks
I've been searching and iterating a lot recently trying to figure out how to have a real time progress bar on the webpage to show the progress of programs running at the backend at the server. Right now I'm using Django for building the website as I need to run python programs on the server. So far when the web user click "submit" button, it will take the python program (written in views.py) about one minute to present the result and having a progress bar can really help here. Hope I provided enough detail about my question and thank you in advance for any one who can help. -
django execute collectstatic command
I'm trying to execute the command: $ python manage.py collectstatic ** settings.py ** import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), #'/var/www/static/', ] And my ** manage.py ** #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "piefinance.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) But, when I execute the command $ python manage.py collectstatic I get this error: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect for path, storage in finder.list(self.ignore_patterns): File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", … -
form is not populated with data
I have a form for user profile. I am trying to update the profile. The form is shown but the form is not popluated with the data even when passing instance from the view. Here is my view def post(self, request, token=None, format=None): """ update a profile when token is provided """ profile=None if not token is None: try: profile = Profile.objects.filter(user=request.user).get(token=token) print ('profile', profile) serialized_data = self.serializer_class(instance=profile, data=request.data, partial=True) except Profile.DoesNotExist: return error.RequestedResourceNotFound().as_response() except: return error.UnknownError().as_response() reply={} if not serialized_data.is_valid(): return error.ValidationError(serialized_data.errors).as_response() profile = serialized_data.save(user=request.user) reply['data']=self.serializer_class(instance=profile, many=False).data return Response(reply, status.HTTP_200_OK) Here is my serializer class ProfileSerializer(serializers.ModelSerializer): # url = serializers.HyperlinkedRelatedField(source="user", view_name="user_profile") class Meta: model = Profile fields = ('token', 'user','current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) -
How to track the time Django takes to run migrations?
I have multiple Django apps with loads of migrations, and they can take a long time to run when building on a VM. For logistic reasons, and to identify areas where we can increase speed I'd like to be able to view the time it took for all migrations to run. What would be the preferred way of doing so? Maybe a management command that kicks off when you run migrate? Can't seem to find much on the topic. -
Access Gunicorn worker from django request
From a Django request, how do I access the Gunicorn worker that is running that request? -
Block malicious user creation with Django?
I have an issue with a user who is creating many malicious accounts with the intent of spamming our service. I'd like to block this user from creating additional accounts. My first thought is to store users' IPs, identify the IP this user is posting from, and then require all users posting from the user's IP to go through additional verification (some kind of real ID, tax ID, phone number, etc. -- something that isn't as easily duplicated as an email address) (along the lines of this question How can I track IPs to block malicious users?). Are there other ways that are recommended for preventing the creation of malicious accounts, more generally? Is there a specific Django best practice to avoid this problem? I am thinking that I will save the IP in an associated Profile model, but wanted to make sure that there wasn't another, accepted way of preventing this issue, since it must be a fairly common problem.