Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search with sorting mongodb
My data in mongodb: [{ "name": "Foo", "points": [{ "order": 1, "point_name": "A" }, { "order": 2, "point_name": "B" }, { "order": 3, "point_name": "C" }] }, { "name": "Bar", "points": [{ "order": 1, "point_name": "B" }, { "order": 2, "point_name": "C" }, { "order": 3, "point_name": "A" }] }, { "name": "Fizz", "points": [{ "order": 1, "point_name": "C" }, { "order": 2, "point_name": "B" }, { "order": 3, "point_name": "A" }] } ] I'm doing a search for B -> C the result should be Foo, Bar How the query will look through Django ORM ? Perhaps this can be done easily by rebuilding data or by using hashing functions. Thank you! -
Can django admin.py be replace with a directory?
I know I meant to give what I've tried but I just want to know if the functionality is available first. I'm build a project which is basically only using the django admin functionality (ie I'm not building custom views or if I am I'm building them within the admin functionality). It is making admin.pyrather large and I just wondered if it is possible to do something similar to models and models.py can be replaced by a models directory with init.py defining where the models are found. If the answer is yes, could you point me to some documentation? -
Copy Django App to a New Project but Model Data is Lost
I made a development django project on my pc, and I added a bunch of data for one of the apps "things" by logging in the ADMIN panel. When I copy and paste this app folder into a new project on Ubuntu, add this app in setting, then I find all the data in the model is gone. I used "makemigrations, migrate". Still nothing. What should I do to have those data in this new project? -
Django views.register returning none instead of a HTTPresponse
I'm trying to make a custom user registration form Here is my views.py code from django.shortcuts import render, redirect from django.views.generic import TemplateView from .forms import RegistrationForm # Create your views here. def register(request): if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect("profile/") else: form = RegistrationForm() context = {'form': form} return render(request, 'accounts/registration.html', context) Here is my forms.py code from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user When I run this code it's working but when I try to register a user it is returning ValueError at /accounts/registration/ The view accounts.views.register didn't return an HttpResponse object. It returned None instead. Here accounts is the name of my Django app -
Django+fastcgi+nginx logging
I was given django project from another developer. It based on windows server(Django+fastcgi+nginx). In settings.py present option DEBUG=True but the anyone of the errorlog-files does not contain debugging information nginx.conf worker_processes auto; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log notice; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log info; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log error; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 8080; server_name localhost; client_max_body_size 32m; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log notice; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log info; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log error; location / { fastcgi_pass 127.0.0.1:8888; fastcgi_pass_header Authorization; fastcgi_hide_header X-Accel-Redirect; fastcgi_hide_header X-Sendfile; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param REQUEST_URI $request_uri; fastcgi_param SERVER_NAME $server_name; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_PROTOCOL $server_protocol; } location /media/ { alias H:/AUCTION/; } location /static/ { alias C:/PATH_TO_PROJECT/static/; } location /static_ac_invoice/ { alias C:/PATH_TO_PROJECT/tender/ac_invoice/static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } Running server: c:\PATH_TO_PROJECT\Scripts\python.exe c:\PATH_TO_PROJECT\tender\manage.py runfcgi method=threaded host=127.0.0.1 port=8888 C:\PATH_TO_PROJECT\nginx\nginx.exe How can I get debug info without reconfigure project for running in non fastcgi mode? -
How to make the Django template include work
I have three pages main,one and two. i requirement is when i visit the page main i need to see the page one and two. HTML: main.html {% extends 'base.html' %} {% load staticfiles %} {% load my_tag %} {% block title %} <title>Main TAB</title> {% endblock %} {% block body %} <div> {% include ‘test/one/’ %} </div> <div class="container"> {{name}} </div> <script type="text/javascript" src="{% static "js/testquery.js"%}"> </script> {% endblock %} one.html <div class="container"> {{name}} </div> two.html <div class="container"> {{name}} </div> view.py def main_page(request): try: main_data = {'name':"main"} return render(request, 'task/main.html', {'name': main_data}) except Exception as e: raise def one_page(request): try: main_data = "one" return render(request, 'task/one.html', {'name': main_data}) except Exception as e: raise def two_page(request): try: main_data = "Two" return render(request, 'task/two.html', {'name': main_data}) except Exception as e: raise url.py urlpatterns = [ url(r'^$', taskpage,name="task_master"), path('Task/<int:taskid>', show_task,name='show_task'), path('Task/<int:taskid>/update', updatetaskpage,name='updatetask_page'), path('Test/Main/', main_page,name='main'), path('Test/one/', one_page,name='one'), path('Test/two/', two_page,name='two'), ] I am getting the following error : TemplateSyntaxError at /taskmaster/Test/Main/ Could not parse the remainder: '‘test/one.html’' from '‘test/one.html’' Request Method: GET Request URL: http://localhost:8000/taskmaster/Test/Main/ Django Version: 2.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '‘test/one.html’' from '‘test/one.html’' Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django\template\base.py in init, line 668 Python Executable: C:\Program Files … -
rpc api using django
I am trying to build an RPC API for machine learning. Is there any way to build RPC API using Django framework. Earlier I have made a restful API using Django rest framework. please suggest me if there is any other way to build the RPC API. -
error deploying django 2.0 to heroku
I have created my first Django 2.0 project and trying to deploy it into Heroku. I have have setup all and all push and pull goes well. But when I access my application endpoint with https://jotitdown.herokuapp.com It is not loading and heroku logs gives this error 2017-12-23T07:04:45.333450+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=jotitdown.herokuapp.com request_id=cd2a9bb6-fae8-4317-af39-b271c1d74af5 fwd="45.115.107.34" dyno= connect= service= status=503 bytes= protocol=https I have set this in settings.py, here ` DEBUG = True ALLOWED_HOSTS = ['*', 'jotitdown.herokuapp.com', '*.herokuapp.com'] and Profile web: gunicorn notepad.wsgi --log-file - -
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