Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to rename column from csv in django_import_export?
I want to import data to my django model from csv by import_export module. Unfortunatelly, field in csv is named "surname" but in model I need "last_name". Is the option to rename column? When I use last_name = Field(column_name='last_name', attribute='surname') I have no data inside. docs:http://django-import-export.readthedocs.io/en/latest/getting_started.html#declaring-fields -
Show foreign key in DJANGO REST
My first question here. Glad to be part of this community. My question: I'm using python3 and the django rest framework to create an API. I have the following models: class Game(models.Model): # id = models.AutoField(primary_key=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) url = models.CharField(max_length=100) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() summary = models.CharField(max_length=2000) first_release_date = models.BigIntegerField() category = models.SmallIntegerField() cover = models.CharField(max_length=100) def __str__(self): return self.name class ReleaseDate(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.BigIntegerField() updated_at = models.BigIntegerField() category = models.SmallIntegerField() platform = models.SmallIntegerField() date = models.BigIntegerField() region = models.SmallIntegerField() y = models.SmallIntegerField() m = models.SmallIntegerField() human = models.CharField(max_length=10) To create a serializer for the Game and ReleaseDate I'd do: class ReleaseDateSerializer(serializers.ModelSerializer): class Meta: model = ReleaseDate fields = '__all__' class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = '__all__' ... and this would provide me with: [ { "name": "God of war", "url": "efgsd" }, { "name": "Uncharted", "url": "sgdfd" }, { "name": "Fortnight", "url": "efgsd" } ] How would I go about to get this, ie: [ { "name": "God of war", "url": "efgsd" "release_dates": "[ {..}, {..} ]" }, { "name": "Uncharted", "url": "sgdfd" "release_dates": "[ {..}, {..} ]" }, { "name": "Fortnight", … -
Error on terminal while installing django taggit via pip install on ubuntu gnome
I am getting the error on installing django-taggit module... what might be the problem? Please help I have tried everythin and it̀s still bringing the same error even tried updating my setup tools :~$ pip install django-taggit Collecting django-taggit Using cached django_taggit-0.22.1-py2.py3-none-any.whl Installing collected packages: django-taggit Exception: Traceback (most recent call last): File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/taggit' -
django - AttributeError: type object 'file' has no attribute 'set_user'
I have created a model named file. It was running well, then I created an element inside the class named set_user which gave an error. So, I removed it. But, I think it's not deleted my my database as I am getting this error while trying to migrate: AttributeError: type object 'file' has no attribute 'set_user' Here's models.py: from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User class file(models.Model): title = models.CharField(max_length=250) FILE_TYPE_CHOICES = ( ('audio','Audio'), ('games','Games'), ('videos','Videos'), ('applications','Applications'), ('books','Books/Docs'), ('others','Others') ) file_type = models.CharField(max_length=12,choices=FILE_TYPE_CHOICES,default='others') description = models.TextField(max_length=6000) def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title -
Django and Python models.py indentation error
I have the following code and an error that says 'inconsistent use of spaces and indentation' but I cannot see what has been done wrong? 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) def __str__(self): return self.song_title The code above it for another class is exactly the same, but it works 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.CharField(max_length=1000) def __str__(self): #this is a string representation of this object - useful for testing/viewing purposes return self.album_title+""+self.artist The error appears to be in the line that returns the string representation of the Song object def __str__(self): return self.song_title More specifically the error seems to point to this line: def __str__(self): (if you note its position above int he Song class, the indentation looks fine...) Can anyone spot the error or suggest a fix?