Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to limit a StreamField to accept exactly two blocks?
The title says it all, I haven't been able to find any other information online. I'm wondering if it is possible for me to get secondary_links = StreamField([ ('Page', SerialisedPageChooserBlock())]) to accept exactly two blocks. -
Django Materialize.css Navbar
I'm working on a Django webapp and I'm using Materialize for CSS I have placed the Materialize file in the static folder in the app. I have issues with the Navbar that it works fine when in full-screen but when I resize the browser the hamburger icon for mobile navbar doesn't work. When clicked on it, it just goes to the /# page and doesn't openup from the side as it should. Do I have to make any change in the Django or Javscript files files? How can I fix this issue? -
django: blog() missing 1 required positional argument: 'blog_id'
I am attempting to add a blog to an existing test website, but I am receiving the following error message: blog() missing 1 required positional argument: 'blog_id' This may be a simple mistake I have made, but I am stumped at what I have done incorrectly and how to fix this. I have searched google and SO, but I haven't found a suitable reference. Here is my models class: class Blog(models.Model): blog_title = models.CharField(null=False, blank=False, max_length=150, unique=True) blog_description = models.CharField(null=False, blank=False, max_length=500) blog_script = models.CharField(null=True, blank=True, max_length=5000) blog_date_released = models.DateField(null=False, blank=False) blog_tags = models.CharField(null=True, blank=True, max_length=150) blog_video_url = models.URLField(null=False, blank=False, max_length=250) blog_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) blog_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) Here is my views.py file: from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from myapp.core.decorators import * from myapp.core.models import Blog def blog(request, blog_id): blog = Blog.objects.get(pk=blog_id) .... return render(request, 'blog/blog.html', { 'blog': blog, 'display_default_language': the_display_default_language, 'language_versions': language_versions, 'language_versions_num_enabled': language_versions_num_enabled, 'language_versions_num_total': language_versions_num_total, 'var_page_title': _("Blog"), }) Any help will be greatly appreciated. -
Django Form - My Image is NOT Valid
Django Form - My Image is NOT Valid This is so annoying. I'm trying to have a user profile with a logo using "ImageField()" and django's built-in "from django.contrib.auth.models import User", but my image always can't pass "is_valid()". Please HELP me. PS. Ignore the RECAPTCHA bit. It has nothing to do with the bug. Trust and believe me. This is my views.py import json import urllib import PIL from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from django.contrib.auth import logout from django.views.generic import View from .forms import UserForm, UserProfileForm from django.conf import settings def log_out(request): logout(request) form = UserProfileForm(request.POST or None) return redirect("/", request) def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return redirect("/", username=request.user.username, is_active=request.user.is_active) else: return render(request, 'Index/login.html', {'Error_Message': 'Your account has been disabled'.upper()}) else: return render(request, 'Index/login.html', {'Error_Message': 'Invalid log in'.upper()}) return render(request, 'Index/login.html', {"username": request.user.username}) def register(request): Form1 = UserForm(request.POST or None) Form2 = UserProfileForm(request.POST or None and request.FILES or None) if request.method == "POST": recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response, … -
Why my wiki is always in loading ?
I have used django-wiki to build my personal wiki. But when I launch the wiki, I find that it always displays the contents are in loading. Here is the url of my wiki: This is my wiki url Can anybody tell me how to solve the problem ? This the wiki loading state Thanks a lot -
Playing mp3 files in my Django 1.11 Template
So I am having trouble playing mp3 files on my Django application. # settings.py - Added MEDIA_ROOT and MEDIA_URLS MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') MEDIA_URL = '/uploads/' # models.py - I have a simple audio class setup class Audio(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) audio_file = models.FileField(upload_to='audio/', blank=True) description = models.TextField() featured_image = models.URLField(max_length=500) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) # views.py - Here is my view class AudioListView(ListView): context_object_name = 'audio' template_name = 'media/audio/audio_list.html' model = Audio # audio_list.html - Here is my template {% block content %} {% for aud in audio %} <p>Audio Title: {{ aud.title }}</p> <img src="{{ aud.featured_image}}" alt=""> <hr> <audio controls> <source src="{{ aud.audio_file }}" type="audio/mp3"> </audio> <hr> <p>Audio Description: {{ aud.description }}</p> {% endfor %} {% endblock %} I can go in and add an audio file and it uploads to the following directory # myapp -> uploads -> audio -> audio.mp3 With the following setup the html5 audio player doesn't even show up. When I check the source for the page I get the following: <audio controls> <source src="audio/audio.mp3" type="audio/mp3"> </audio> I have combed through the Django documentation. I have searched all over google. I wouldn't think it would be that … -
request body is empty in django
I am using create react app for front end.My problem is every POST request contains nothing from django side. Here is the view: def login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') print(request.POST) // prints <Queryset: []> user = auth.authenticate(username=username, password=password) if user: token = Token.objects.get_or_create(user=user) return JsonResponse({'token': str(token[0])}, status=status.HTTP_200_OK) else: return JsonResponse({'error': 'Username/Password is not valid'}, status=status.HTTP_401_UNAUTHORIZED) I already added "proxy": "http://localhost:8000" in package.json. Here is the react part: handleSubmit(event) { event.preventDefault(); axios({ method: "post", url: "/api/auth/", data : { "username": this.state.username, "password": this.state.password } }).then(function (response) { console.log(response); }).catch(function(error){ console.error(error.response.data["error"]); }) } I also checked front end network data, there were username and password in request body. -
Django set_password not working
I set the user password and it checks out, but I can't login in various login forms. I can't authenticate: u = User.objects.get(username='foobar') u.set_password('123') u.save() u.check_password('123') # True authenticate(username='foobar', password='123') # None?!?! I can't log the user in though I've tried various ways. -
providing download link for uploaded file to users in django
i am creating file sharing app. In which user logins and uploads files. and after login they are now able to see there uploaded files. but i am unable to provide download link for those files in front of them. I searched a lot but did not find any related stuff. requesting you to please help me out. please find below data, My model.py class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50,blank=True) def get_absolute_url(self): return '/img/%s' % self.Browse.name my view.py def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) #instance=form_new.save(commit=False) #instance.save() if form_new.is_valid(): #p=user_files(Username=user) #user_files.Username=user #p.save() instance = form_new.save(commit=False) instance.user_uploaded=request.user instance.save() return redirect('in') else: form_new = Fileupload() data = user_files.objects.filter(user_uploaded=request.user) #print(data) args = {'form_new': form_new, 'data': data}#, 'url': form_new.get_absolute_url()} return render(request, 'accounts/in.html', args) my form.py class Fileupload(forms.ModelForm): class Meta: model= user_files fields = ('Filename','Browse') my html template to show data, <form action="." method="POST" enctype="multipart/form-data" > <h3>Welcome to DropBox<br><br></h3> {% csrf_token %} {{form_new.as_p}} <p><input type="submit" value="Save" ></p> <br> <a href="{% url 'logout' %}">Logout</a> {%else%} <p>You must login first</p> <a href="{% url 'login' %}">Logout</a> {% endif %} <br><br> User is : {{request.user}} {% for da in data %} <h3>{{da.Filename}} {{da.Browse}} … -
reportlab install error in django app
I want to install reportlab to make pdf file from python script. But I got the following error. Exception: Traceback (most recent call last): File "/home/ubuntu/remoshindev/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/ubuntu/remoshindev/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/ubuntu/remoshindev/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/ubuntu/remoshindev/lib/python3.5/site-packages/pip/req/req_install.py", line 922, in install with open(inst_files_path, 'w') as f: FileNotFoundError: [Errno 2] No such file or directory: './lib/python3.5/site-packages/olefile-0.44-py3.5.egg-info/installed-files.txt' I don't have a "./lib/python3.5/site-packages/olefile-0.44-py3.5.egg-info/installed-files.txt". How can I fix it? Please let me know. -
source .env doesn't work
My .env file is: export DJANGO_SETTINGS_MODULE=taxi_framework.settings.local export TAXI_DASHBOARD_RAVEN_DSN="" export TAXI_LOCATION_BACKEND_URL='http://localhost' export TAXI_DASHBOARD_BOOKING_BACKEND_URL='http://localhost' export SECRET_KEY='here is my secret key' export TAXI_DASHBOARD_DEFAULT_DATABASE="mysql://root:rootroot@127.0.0.1/namba_taxi" I ativate it with source .env command and got .env.save file, but when I ran django project I got missing SECRET_KEY mistake. How to make this file work? -
Django: Messages not being displayed
I have following function for bulk operation of the selected rows in a ListView. I am showing messages for success and error. def archive_stores(view, queryset): if queryset.exists(): queryset.update(archive=True) success_message = messages.success(view.request, 'Archived successfully.') return HttpResponseRedirect(reverse('stores_list', success_message)) else: #The message is not shown when queryset of empty. error_message = messages.error(view.request, 'No success!.') return HttpResponseRedirect(reverse_lazy('stores_list', error_message)) The success message is being displayed correctly. But the Error message never appears. Please guide me what can be the reason? Thanks. -
Django Rest Framework add page number attribute using the PageNumberPagination class
I am building an API in Django and I am trying to add the page number on the json results. And I am trying to add the page number in the returned results for example, I am currently getting this; { "links": { "next": null, "previous": null }, "count": 1, "results": [ { "url": "http://127.0.0.1:8000/api/brands/1/?format=json", "name": "microsoft", "description": "Nothing", "top_brand": true, "guid": "microsoft" } ] } But I am trying to get something like this; { "count": 1, "results": [ { "url": "http://127.0.0.1:8000/api/brands/1/?format=json", "name": "microsoft", "description": "Nothing", "top_brand": true, "guid": "microsoft" }, ... ], "page_number": 1, "from": 1, "to": 10, "last_page": 4 } The most important attribute is the page_number but I am not so sure how to get that from the parent class using self... I see no direct way besides using a function. Here is my code; class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data, 'page_number': self.page.paginator.count, }) -
How to enable default error views in Django 1.11?
I upgraded a Django project to 1.11, and now some of the default error views don't work anymore. I have these settings: handler500 = 'myhandle_500' handler404 = 'myhandle_404' handler403 = django.views.defaults.permission_denied However, I've implemented a simple test view for the 403 error, which just raises a PermissionDenied exception, and while this used to show my custom 403.html template, now it's treated like a generic server exception and shows my 500.html template. How do I restore this functionality? -
How to run a python script inside javascript and refresh the view in django
I have a python script that takes in some data and manipulates it. However i need it to run on the client side inside the javascript to process some data and refresh the view. The python file that manipulates data works well as I have tested it inside the IDLE shell DataManipulation.py class ModifyData(object): #Bunch of functions to manipulate data below is the function used to render the view with url '.../test' which also works perfectly. views.py def test(request): template = 'app/test.html' file = 'documents/Sample.csv' #File to be loaded args = {'test': file } return render(request, template, args) After loading this page, i use a javascript library that displays the data on the page in a table, the user can then manipulate the data like multiply a column by 3, but where I am stuck is how to take my DataManipulation.py file to modify the data and updates the page with the updated column on a button click -
How do I fix my Createview in Django
I am trying to make a business card manager using django python but I don't why my business card are not being added and when press the button Add business Card it goes to the business Card list blank. I also want to know how to make the delete and update button work on the Business Card List. I think you have to add a primary key in the model but I don't know how to and how to pass it in correctly. Views from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views.generic import View from .models import BusinessInfo class BusinessCardListView(generic.ListView): model = BusinessInfo template_name = 'manager/BusinessCardList.html' context_object_name = 'all_business_cards def get_queryset(self): return BusinessInfo.objects.all() class BusinessCardCreate(CreateView): model = BusinessInfo fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title', 'fax_number', 'cell_phone_number', 'email'] class BusinessCardUpdate(UpdateView): model = BusinessInfo fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title', 'fax_number', 'cell_phone_number', 'email'] class BusinessCardDelete(DeleteView): model = BusinessInfo success_url = reverse_lazy('manager:index') Add Business Card form {% extends 'manager/base.html' %} {% block title %}Add a New Business Card{% endblock %} {% block albums_active %}active{% endblock %} {% block body … -
Change value in xlsx file with openpyxl
I parse data from xlsx file with openpyxl and than pass it to template. Parsing: def load_table(filename): wb = xls.load_workbook(filename=filename) ws = wb.worksheets[0] return list(ws.rows) def parse_date(row): text = row[0].value rs = text.split(' ') for r in rs: if len(r) == 11 and len(r.split('.')) == 4: return r def parse_data(rows): data = {} class_name = '' for row in rows: if row[-1].value is None: class_name = row[0].value.replace('-', '') if class_name not in data: data[class_name] = [] elif ':' not in row[0].value: data[class_name] += [[row[0].value, row[1].value]] return data def parse_table(filename): rows = load_table(filename) date = parse_date(rows[0]) data = parse_data(rows[2:]) return date[:-1], data data: {'1A': ['Name1', 'State1', 'Name2', 'State2'], '1B': ['Name1', 'State1', 'Name2', 'State2', 'Name3', 'State3', 'Name4', 'State4', 'Name5', 'State5'], '1C': ['Name1', 'State1'] ...} Users can change states and post it to server. In view i handle request in dict: if 'school' in request.POST: for k, v in request.POST.lists(): changed_data_values.append(v) for i in changed_data_values[1]: key = i tmp_dict[key] = list(zip(changed_data_values[2], changed_data_values[3])) dict: {'1B': [('Name1', 'State1'), ('Name2', 'State2'), ('Name3', 'State3'), ('Name4', 'State4'), ('Name5', 'State5')]} The question is how change value of state in xlsx file? I will be very grateful for any help. This is the last thing left to do in the … -
django project avoid reload page where work algorithm
I have a website where the user can be put three numbers on my html template and get some results from my personal mathematical algorithm. the result save at user personal table on my database and can see in specific tab in my website. my problem is where the algorithm to calculate result maybe take time between 5-10 minutes in this time the browser stay on reload. if user change tab or close browser or maybe have problem with internet connection then loose that request and need again to put the numbers and again wait for results. I want after the user request from my form in html to keep this request and work my algorithm without reload the page and where the algorithm finish then to send the user some email or message or just need the user visit the tab of results to see new results. that I want to avoid the problems where the algorithm is in running and user loose data or request or time. is easy to do that using suproccess,celery or RabbitMQ ? any idea ? here the code views.py def math_alg(request): if request.method == "POST": test = request.POST.get('no1') test = request.POST.get('no3') test = … -
Jwt Decode using PyJWT raises Signature verification failed
I'm running into a weird issue with decoding the jwt token in the django views. If I try jwt.decode('encoded_token', 'secret') then I see the "Signature verification failed" message. In order to escape from this issue I've set the verify flag to False: jwt.decode('eroded_token', 'secret', verify=False) This gives the decoded payload with no error but I'm trying to figure out how I can verify the token successfully without setting the verify flag to False. Any Ideas? Thanks -
django collectstatic with settings flag throws logging path error using incorrect logging path
I've recently started restructuring a project to use two scoops style configuration, with a config package, with settings inside it. Within that package, there's _base.py, development.py, staging.py and production.py. Since this is deployed as a WSGI app with Apache, I'm using a json file for environment variables, such as AWS credentials, db username/passwords and such. In short, following suggestions listed at https://medium.com/@ayarshabeer/django-best-practice-settings-file-for-multiple-environments-6d71c6966ee2 When deploying on staging, I have the wsgi app running through apache. In addition, manage.py $COMMAND is working with the --settings=config.settings.staging flag set. That is, with the exception of collectstatic. It's apparently trying to access an invalid logging path, and I can't figure out why its using that particular path which is not defined in the settings file being used. Current output of collectstatic run: (staging)ubuntu@farmer-stage:~/public_html/django/project$ ./manage.py collectstatic --help Using configuration [config.settings.staging] Using configuration [config.settings.staging] Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/utils/log.py", line 86, in configure_logging logging_config_func(logging_settings) File "/usr/local/lib/python2.7.11/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/local/lib/python2.7.11/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure … -
Extending Django filer image model to add category
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could you help me with this topic? -
Using Django-bootstrap3 . How to target individual form fields to adjust CSS
Here is my code below. I need to be able to adjust the appearance of the individual fields and labels in the CSS but I am not sure how to do this for the code below. Basically the question how to I know what class or ID selector I need to target or what settings I need to use <form action="/post/" method="post" class="form"> {% csrf_token %} {% for field in form %} {% bootstrap_field field layout='inline' %} {% endfor %} {% buttons %} <button type="submit" class="btn btn-success"> {% bootstrap_icon "pencil" %} Post </button> <button type="reset"> {% bootstrap_icon "erase" %} Clear </button> {% endbuttons %} </form> I am a complete newbie for this. I have been through the docs but I am not sure where to start -
Django runnning on heroku: have to login again after every dyno restart
I am running a django web app on Heroku. I'm using the hobby-dev plan, so the dyno doesn't go to sleep after inactivity, but it does restart once per day. After every restart, I need to re-enter my login credentials to use the admin interface. How can I make my login session persist after a dyno restart? -
Problems with MongoDB and Python
Good evening guys, I need some help. I need to implement a MongoDB database as a default or secondary (if possible) in an application made in Django. Currently my Django application works with Tweepy, I need to save the captured data in the NoSQL database. I chose MongoDb, but I found several information saying that it is only possible to use with python 2.7 (my application was built in python 3.5). Is there any way to do it? I have already tried to use pymongo, mongodbengine, among others without success ... I believe that I am not doing correct. I need guidance in this process (I did not find information for newer versions of django and python, and the documentation has not been updated) -
Delete confirmation in django
I am working on a project in django. I have this part of code, when I want to delete an album, it shows Yes or No to choose, but the problem is, whatever the choice I make, it always delete the album. I know I have to add something to the confirmation option but I don't want where or what. <form action="{% url 'music:delete_album' album.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}" /> <button type="submit" onclick="confirm('Are you sure ?')" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> and this is the delete_album view : def delete_album(request, album_id): album = Album.objects.get(pk=album_id) album.delete() albums = Album.objects.filter(user=request.user) return render(request, 'music/index.html', {'albums': albums})