Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot find my media folder while debug = False
I have a django project that works very well and shows all media files uploaded from the admin when debug = True but immediately i turn change to debug = False django cannot find my media folder yet it loads my static folder. as you can see i have set up my MEDIA_ROOT and MEDIA_URL correctly and here is my urls.py configuration as well And in the console logs i find my images output 404 errors while i can clearly see a media folder is present with the images in my directories Can someone please help me point out what i am doing wrong or why django can't find my media folder? -
How will I use template context variable's value inside Django template tags?
In Django, I have seen the trans tag, it is useful to place translation strings in templates. {% trans 'Rishikesh' %} But I want to use dynamic value in place of 'Rishikesh' that is being passed by my view function. Let you assume my view function named index as follows. def index(request): return render(request, "index.html", {"username": "Rishikesh"}) My question is, I want to use the value of username as value of trans tag in my template as something like following. {% trans "{{username}}" %} I think, I am right but it doesn't work? Please help me. -
What is some benefit of using Python Django? [on hold]
I am currently learning various backend framework such as Ruby on Rails, Python Django, and Node.JS. I just want to know the different benefit of each? -
confirmation Email and how to access and alter user's profile fields?
I am following a tutorial and everything is working fine, except being able to access the user's profile fields , and so far i am able to set the 'is_active' flag on User model, put 'user.profile.email_confirmed' is really not changing at all,so any Idea about what is that i am doing wrong. models.py class Profile(models.Model): # relations user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) tokens.py class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() urls.py url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z] {1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('home') else: return render(request, 'account_activation_invalid.html') -
Issue with Django Template for loop
so I did some searches but couldn't find the answer to my particular issue... What is happening is that: I have a model named section which have section_title field. This field can have spaces, for example: "First Section". When I pass this to Django, I am removing the space in Python with replace(), and created a filter on Django which also removes the space like so: @register.filter(name='replace_char') def replace_char(value, arg): return value.replace(arg, '') Then on my template: {% for subsection in section.section_title|replace_char:" " %} The issue is that subsection is being shown as each character from section_title, instead of the list that section_title references. Here is the dictionary being passed to the template: {'sections': [< Section: First Section>, < Section: Second Section>], 'FirstSection': [< Subsection: Subsection 1>, < Subsection: Subsection 2>], 'SecondSection': [< Subsection: Bla1>], 'teste': ['1', '2', '3']} If I hardcode: {% for subsection in FirstSection %} It works... Any ideas? Thanks! OBS: I removed the spaces because I thought they were causing the issue, but apparently not. -
Oauth2, Django Backend, Implicit Token Authorization
So I've written a chrome application that uses chrome "WebAuthFlow" in the chrome.identity API. I've got a Django-Based site running on my computer at the same time, and with a login button in my chrome extension, I can use the webauthflow with my site and client to exchange tokens. I believe I need to use this implicit token scheme because my chrome extension is in javascript. The issue I am having is that while I would like users to be able to log into or out of the app - no matter which user the client 'belongs' to, which user is logged in to my domain currently (csfr; session cookie) or which user has loggin into through the webauthflow of the extension, when using the line return HttpResponse(User.objects.get(username=request.user), status=200) In my views, I am always returned with the username of the admin. Same goes for querying the admin -- Am I stuck in a session? How can I manually log out to test this? I have been completely unable to change this response at all - I want to have the user have logged in through the webauthflow and was expecting when I sent the username back to see the … -
django how to create checkbox for single item
i know to create a multiple checkbox in the form if i have list of items. forms.py class GatewayForm(forms.Form): GATEWAY_CHOICES = ( ('Instamojo', 'Instamojo'), ('CCAvenue', 'CCAvenue'), ('ePaisa', 'ePaisa')) gateway_name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=GATEWAY_CHOICES) template.html i use a for loop to display the gateway_names. Now how can i achieve the same when there is only one item in the list???? GATEWAY_CHOICES = ( ('Instamojo', 'Instamojo'), what form field or widget should i use?? -
Docraptor API Django get PDF to download
I am trying to use Docraptor in Django 2.0 and Python 3. I can get the PDF to generate to their website but not download to my system. Here is their code from https://github.com/DocRaptor/docraptor-python What needs to change to download the pdf file? doc_api = docraptor.DocApi() try: create_response = doc_api.create_doc({ "test": True, "document_content": "<html><body>Hello World</body></html>", "name": "docraptor-python.pdf", "document_type": "pdf", }) file = open("/tmp/docraptor-python.pdf", "wb") file.write(create_response) file.close() print("Wrote PDF to /tmp/docraptor-python.pdf") except docraptor.rest.ApiException as error: print(error) print(error.message) print(error.code) print(error.response_body) I am guessing there is some sort of HttpResponse missing? This seems like a great way to produce PDF files once I overcome this issue. Their tech support is great but documentation a bit short. Thanks. -
Django model form not saving all fields to db
Django 1.11 Python 3.6 Allauth (without the social part for now) Sqlite3 db backend I am working my way through building a Django site. Allauth is handeling the basic registration/login stuff. I have a user profile that has a foreign key relationship into the user table -- it is not an extended user model per se. It is a model that links to the user table. I have a view and a form that display the profile form. I have html5 form validation plus some form validation set up that seems to work. If I enter bad form data and submit then the various field errors are reported. If I enter all the required data and hit submit a record is created in the db but not all form fields with required values are inserted into the db table. I will get first & last names, phone and birthdate. The address info never makes it to the db. I do not see any errors reported. Sorry for the length of the supporting material... The model from django.contrib.auth.models import User from django.db import models class Profile(models.Model): class Meta: unique_together = [ ("last_name", "first_name", "middle_name", "birthdate"), ] get_latest_by = "dateCreated" ordering = … -
template not working in django
im following a django tutorial on how to make a blog, and we are at the template tags, the thing is, only the head is showing up and not the articles that i placed into my template, this is my code: views from django.shortcuts import render from.models import Narticle def narticle_list(request): narticle= Narticle.objects.all().order_by('date') return render(request,'narticle/narticle_list', {'narticle': narticle}) template narticle_list <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Narticle</title> </head> <body> <h1>narticle_list</h1> <div class="narticle"> <h2> <a href="#">{{Narticle.title}}</a> </h2> <p>{{Narticle.body}}</p> <p>{{Narticle.date}}</p> </div> </body> </html> in case you want to see my urls from django.conf.urls import url, include from django.contrib import admin from. import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^narticle/', include ('narticle.urls')), url(r'^about/$', views.about), url(r'^$',views.homepage), url for narticle from django.conf.urls import url from. import views urlpatterns = [ url(r'^$',views.narticle_list), ] when i request the narticle url, my articles are not showing up, just the header which is "narticle_list" -
Filtering Distinct and Ordered Data
I'm trying to create a messaging App where user can see the list of people who messaged him & also whom he messaged, so that he can click on their names & see the conversation occurred. Problem is that I couldn't filter out the distinct & ordered list of users who messaged request.user or whom request.user messaged. Here's the Model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField(max_length=8000) created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, def profiles(request): users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('sender__first_name', 'receiver__first_name', 'receiver__id', 'sender__id').annotate(Max('id')).order_by('-id__max') return render(request, 'chat/users.html', {'users': users}) Here's the template, {% for user in users %} {% if user.sender__id != request.user.id %} {{ user.sender__first_name }} {% else %} {{ user.receiver__first_name }} {% endif %} {% endfor %} This code seems working fine but it's returning the same user twice as long as request.user sent him a message & he replies back to it. How can I solve this issue? Thank You . . . -
Python/Django - Value is reverting back after for loop
I'm trying to pass the URL's of a list of photos to the template. I'm concatenating my MEDIA_URL to every photo name. When print(a) is run, I can see in the console that the concatenation was successfully added. The result is something like media/photo.jpg. However by the time the loop finishes, the result reverts back to the original photo.jpg as if no concatenation happened. print(photos) shows a list of photos with no changes. Why? def get_property_data(request): property_id = request.GET.get('id') photos = ListingPhoto.objects.values_list('photo', flat=True).filter(listing__id=property_id) for a in photos: a = settings.MEDIA_URL + a print(a) print(photos) return JsonResponse({'property': list(photos)}) -
ModuleNotFoundError: No module named 'bootstrapform'
I got an error,ModuleNotFoundError: No module named 'bootstrapform' . When I run by python manage.py runserver,this error happens. Traceback says Traceback (most recent call last): File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Users/XXX/anaconda/envs/py36/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrapform' I wrote in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'bootflat.github.io'), ] Directory structure is like -PythonServer -PythonServer -logic -static -index.css -templates -index.html -boolflat.github.io -bower_components I run pip install django-versatileimagefield==1.2.2 & pip install rules, but same error happens.How should I fix this error? -
DB Browser for SQLite datatype mismatch & rowid error
I'm having trouble making migration to work after manipulating my database with DB Browser for SQLite. After making the migration, migrating my app (blog) keep producing the "datatype mismatch" error: Operations to perform: Apply all migrations: blog Running migrations: Rendering model states... DONE Applying blog.0027_auto_20171217_1829...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 390 in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 441 in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.p ", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 1 0, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial= ake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 1 7, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 15, in apply operation.database_forwards(self.app_label, schema_editor, old_state, proje t_state) File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py , line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 84, in alter_field old_db_params, new_db_params, strict) File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", li e 200, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", li e 144, in _remake_table self.quote_name(model._meta.db_table), File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 07, in execute cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\utils.py", line … -
Django Serializer - Returning Specific Fields
I want to return a specific field from my model, a field that, for example, has a specific Foreign Key. If I have a Question Model, and I have an Answer Model, and Answer has a Foreign Key to a Question, I want to return the Answer field that corresponds to the Question Foreign key views.py (right now it returns everything) class FindAnswer(APIView): def get(self, request): answer = Answer.objects.all() serializer = AnswerSerializer(answer, many=True) return Response(serializer.data) def post(self): pass serializers.py from rest_framework import serializers from .models import * class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = '__all__' models.py class Question(models.Model): question_text = models.CharField(max_length=256) exam = models.ForeignKey(Exam) def __str__(self): return self.question_text class Answer(models.Model): text = models.CharField(max_length=128) question = models.ForeignKey(Question) def __str__(self): return self.text What is the best way to achieve this? -
Git/Heroku - How hide my SECRET_KEY?
Im using Python and Django to create a Heroku web app and Heroku gives me this error after the command 'git push heroku master': ModuleNotFoundError: No module named 'dlist.secret_settings' when attempting to do this: #settings.py from .secret_settings import * # from secret_settings.py import * doesn't work for some reason. Here is what secret_settings.py (which is in the same folder as settings.py) contains: #secret_settings.py SECRET_KEY = 'string here' The problem is, this works when I test my web app on my local server (ie http://127.0.0.1:8000/), but its not working when I push these changes to Heroku. All I want to do is hide my SECRET_KEY, per others advice, as you can see. Ive looked at others suggestions and I can't seem to figure it out, choosing this method because it was understandable. Very frustrating. Beginner friendly answers/steps are greatly appreciated. -
Import JSON Data to Django models
I'm building a Django Rest Api with an empty database as of now. I want to load a big JSON file I got from another API in my models. The models I created respect the data type as well as the names of the json types. What's best practice for this? Will an import script be the best solution? If so I'd like to know where to 'run' my import code, would running the code in my get APIView class be good? Thank you -
Bootstrap grid content position
I have the following code for django-oscar <ul class="row"> {% for product in products %} <li class="col-xs-6 col-sm-4 col-md-3 col-lg-3">{% render_product product %}</li> {% endfor %} </ul> it works find except on the phone. As you can see from the screen shot, there is a weird space in the grid system when the size is reduced to the phone (it actually displays like this on the phone). On the desktop, the grid system displays correctly until the size of the browser becomes less than certain px. Is there a way to fix this? (I think I am using bootstrap3) Grid system working well Phone mode -
Django field cleaning ValidationErrors don't prevent form from processing
I'm designing a Django form with custom cleaning methods for both fields, and the form itself. Ideally, I'd love for my form to stop processing and throw an error if my fields don't validate. However, the custom clean() method that I wrote for my form runs even when fields throw ValidationErrors. Here's an example: forms.py from django import forms from .models import User class BasicsForm(forms.Form): email = forms.EmailField(label='E-mail address', max_length=128) def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError("E-mail is already taken.") return email def clean(self): # Call the parent clean method cleaned_data = super().clean() email = cleaned_data.get('email') u = User(email=email) u.save() If I attempt to submit the above form with an invalid e-mail address (for example, an e-mail already registered on the site, which will raise the ValidationError within clean_email), I get an IntegrityError that says I can't add a NULL e-mail to my database. What's happening is that even though clean_email catches an error, the lines that create a user in my clean() method (i.e., u = User(email=email) and u.save()) still run. How do I make it so that if my clean_email() method catches an error, clean() doesn't run, and my form instead shows the error thrown by … -
How do you split a Django queryset without evaluating it?
I am dealing with a Queryset of over 5 million + items (For batch ML purposes) and I need to split the queryset (so I can perform multithreading operations) without evaluating the queryset as I only ever need to access each item in the queryset once and thus I don't want to cache the queryset items which evaluating causes. Is it possible to select the items into one queryset and split this without evaluating? or am I going to have to approach it by querying for multiple querysets using Limits [:size] to achieve this behaviour? N.B: I am aware that an Iterable can be used to cycle through a queryset without evaluating it but my question is related to how I can I split a queryset (if possible) to then run an iterable on each of the splitted querysets. -
Django shows 404 error on media files when debug = False in production
I'm trying to put a django website live and after going through the deployment checklist and turning debug = False django gives out a 404 error and only static files are loaded no media files uploaded from users are displayed. However with debug=True all the images and files work properly. below are the configurations of the project with debug = True. The console logs show multiple missing files.can someone point to me what i'm doing wrong? settings.py urls.py console errors -
How to update Heroku superuser password after changing Django superuser password?
I have a web app on Heroku and I recently changed the pw to the admin site through terminal with command python manage.py changepassword <user_name>. When I log into the admin site through the local address (http://127.0.0.1:8000/admin) the updated password works, but when I try to log in to the admin site through my heroku web app with the same newly created password, it doesn't work and I have to use the old admin password, defeating the purpose entirely. How do I update the admin password on my heroku website? -
Machine learning web service
I want to build a webservice that takes as input some parameters and a .h5 file , runs a Random Forest model and then populate a chart with the model's output . I'm wondering what is the best framework to accomplish this project ? I start learning both Django and Flask but I'm not sure about the suitable solution . I think there is another alternative by using Ajax and D3js . Could anyone help me to decide ? I will appreciate any recommendation . Many thanks -
Django FormWizard Post to database with FK
I am using the Django Form Wizard and I have successfully created a multistep form that is able to create a new User. I have a second model called UserAddon that I set a OnetoOne relation to. I cant figure out how to POST to that model and to create that relation in the UserAddon. Also if someone knows, should I be using the checks like if form.is_valid(): or if request.method == 'POST': Within this before I post? Thanks! Wizard class ContactWizard(SessionWizardView): template_name = "wizardApp/contact_form.html" def done(self, form_list, **kwargs): process_form_data(form_list) return HttpResponseRedirect('../home') Process form data def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] first_name = form_data[0]['first_name'] last_name = form_data[0]['last_name'] email = form_data[0]['email'] print(last_name) print(first_name) print(email) user = User.objects.create_user(email) user.first_name = first_name user.last_name = last_name user.email = email user.save() ##### SOMETHING LIKE THIS #### user_addon = UserAddon.objects.create(user.email) return form_data Its also worth noting my code is written to set the users email address as the username -
Django error in assigning path using variable album_id and a new path
I have the following urls.py file and an error in the path calling favourite. urlpatterns = [ #this is matching /music/ path('', views.index, name='index'), path("<album_id>/", views.detail, name="detail") #music/<album_id>/favorite/ path("<album_id>/favorite/", views.favorite, name='favorite'), ] The error (while running server) is: INVALID SYNTAX referring to this line: path("<album_id>/favorite/", views.favorite, name='favorite'), Is anyone able to fix/spot the error?