Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset count() method raise "TypeError: unorderable types: NoneType() > int()"
My environment is Python3.5, Django1.8.3 and cx_Oracle5.3(They are checked by pip3 freeze). Django query set raises a Type Error exception when count() method is called. When it comes to Python2 + cx_oracle or Python3 + sqlite3 works fine without any exception but Python3 + cx_oracle. Thue, I tried to update cx_Oracle version to 6.1(latest version) because I thought I could be some compatibility problem between cx_Oracle and Python3. However, It generates a different error. I detail with the below code block, please refer it. P.S: I Need to keep Django version to 1.8.3 for compatibility with my Apps. models.py from django.db import models class Device(models.Model): deviceClass = models.CharField(max_length=10) class Meta: db_table = 'TST_G2S_DEVICE' cx_Oracle5.3 $ python3 manage.py shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: from polls.models import Device; In [2]: dev = Device.objects.all() In [3]: dev Out[3]: [] In [4]: type(dev) Out[4]: django.db.models.query.QuerySet In [5]: dev.count() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-72a7bdf9f7f7> … -
Referencing SQL model in mongoengine model field
I'm using mongoengine in my workout calendar Django project to store workouts with varying fields, depending on which lifts a user has done, how many of them, etc. I have defined a Workout object that represents one workout done by one person at a certain date. class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) Some of you might notice that there is no field representing the person who did the workout. That is where my question comes in. In my Django project, I have defined a custom User model that I've used instead of the normal django.contrib.auth.models.User object: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( unique=True, }, ) This model is a normal Django model, and is represented in an SQL database, SQLite in my case. I would like this model to act as the user field in my Workout mongoengine model. Something like this: class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) person = ReferenceField(User) #New row Is this possible to achieve in some way? Or do I need to introduce redundancy to my web app by simply adding an email … -
Django: how to correctly pass an URL in include template tag?
In two different templates, I have two blocks almost identical, only the url is different: template1.html <div class="col-sm-4"> <a href="{% url 'bo:article-list' %}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> template2.html <div class="col-sm-4"> <a href="{{ article.get_absolute_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> I'd like to make this dry, creating a template, and making an include then. For example: _cancel.html <div class="col-sm-4"> <a href="{{ cancel_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> For template2.html, it will work with: {% include 'includes/_cancel.html' with cancel_url=article.get_absolute_url %} But what about template1.html ? This obviously does NOT work : {% include 'includes/_cancel.html' with cancel_url={% url 'bo:article-list' %} I guess there is a trick. Thanks for your help :) -
OneToOneField is nor related
this me again. I have some trouble with my code. I made a form from ModelForm which have a model with 8 attributes, but i want to user fill only one of them,and one from the system. The one that user fill is okay, but the one filled with system is not working. models.py class SeminarProposal(md.Model): # diisi oleh mahasiswa fileProposal = models.FileField() # This is the one is filled with system proposal = models.OneToOneField(Proposal, on_delete=models.CASCADE, related_name="propSid", unique=True, blank=True, null=True) masabimbingan = models.BooleanField(default=True) # disi oleh admin tanggal = models.DateField(default=timezone.now, blank=True,null=True) tempat = models.CharField(max_length=30, blank=True, null=True) # diisi oleh dosen pembimbing dospemsetuju = models.BooleanField(default=False, blank=True) # diisi oleh kaprodi penguji1 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji1", blank=True, null=True) penguji2 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji2", blank=True, null=True) def __str__(self): return "Sidang untuk " + self.proposal.judul view.py def daftarSeminar(request): if request.method == 'POST': form = FormSeminar(request.POST, request.FILES) print(request.user) if form.is_valid(): form.save(commit=False) form.cleaned_data['proposal'] print(request.user) prop = Proposal.objects.get(akun=request.user) form.proposal = prop print(form.proposal) #to confirm that this is not None form.save() return redirect('proposal:bimbingan') else: return render(request, 'sidprop.html' , {'oke': 'oke'}) return redirect('proposal:index') form.py class FormSeminar(forms.ModelForm): class Meta: model = SeminarProposal fields = ['fileProposal','proposal'] Thanks in advance. Terimakasih. -
django_apscheduler remove_all_jobs on django startup
I have used django_apscheduler to schedule jobs. And it's working fine. When I start server new job is added and periodically it's doing what I need to do. However if I exit django and start it again then django will fail with error. apscheduler.jobstores.base.ConflictingIdError: u'Job identifier (myapp_db.jobs.test_job) conflicts with an existing job' Basically old job exists in database and new job can not be created. How can I remove all jobs during django startup. I notice there is remove_all_job() function in apscheduler but I do not know from where to execute it? I'm starting job.py from url.py with import myapp.jobs Thanks. -
invalid view function or pattern name in Django project
I keep getting an error which says "Reverse for favourite not found". It has something to do with either my favourite function in the views.py or presumably the way I have called it in the detail.html file. music/views.py code from django.shortcuts import render, get_object_or_404 from .models import Album, Song # Create your views here. #each URL is connected to a view or an Http Response def index(request): all_albums = Album.objects.all() return render(request,'music/index.html',{'all_albums':all_albums}) def detail(request,album_id): album = get_object_or_404(Album,pk=album_id) return render(request,'music/detail.html', {'album':album}) def favorite(request,album_id): album = get_object_or_404(Album,pk=album_id) try: selected_song=album.song_set.get(pk=request.POST['song']) except(KeyError,Song.DoesNotExist): return render(request,'music/detail/html',{ 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite=True selected_song.save() music/templates/music/detail.html code <img src="{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}}</h3> {% if error_message %} <p>{{error_message}}</p> {% endif %} <form action="{%url 'music:favorite' album.id %}" method="post"> {%csrf_token%} {%for song in album.song_set.all%} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}"> <label for="song{{forloop.counter}}"> {{song.song_title}} {%if song.is_favorite%} <img src="http://www.iconninja.com/files/51/927/609/favourite-favorite-star-bookmark-icon.png"/> {%endif%} </label><br> {%endfor%} <input type="submit" value="Favorite"> </form> Error message: (on page load) The error message seems to suggest that the favourite function is not valid, but I cannot see what I have done wrong. NoReverseMatch at /music/1/ Reverse for 'favorite' not found. 'favorite' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/music/1/ Django Version: 2.0 … -
how to switch to path instead of url in urlpatterns [django]
django noobie. ive been going through tutorials but in urlpatterns they use url instead of path which is now introduced in django 2.0 i want to make /appname/anything-gibberish take the user back to the view im giving in /appname/ urlpatterns = [ path('', views.index, name='index'), path('contact/', views.contact, name='contact'), ] i want 127.0.0.1:8000/contact/asaskhask to go to views.contact is there any way to do this without using url and regular expression? -
How to create a survey with some options in django
I want to create survey. I have below models: class Survey(models.Model): question = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, null=True) end_date = models.DateTimeField() class SurveyOptions(models.Model): survey = models.ForeignKey(Survey, related_name='s_id', on_delete=models.CASCADE) text = models.CharField(max_length=50) the survey options might be 2 or 3 or 10 or etc. How can I create that? I don't know how to create a form for it. I googled it, but I didn't find any useful links. I need an example of it. thanks. -
Override setting for unittest in django
django version: 1.11, python version: 3.6.3 When writing unit tests, avoiding interaction with external services (for example the filesystem or network) is considered best practice because you can’t rely on external services’ availability, nor do they present a consistent, predictable state when running your tests. I have a model which uses a custom storage location for image: from django.conf import settings from django.db import models from django.core.files.storage import FileSystemStorage class Example(models.Model): media = models.ImageField( storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) protected root is defined in settings.py: PROTECTED_ROOT = os.path.join(BASE_DIR, "cdn", "protected") then in the tests.py: import tempfile from example_app.models import Example from django.test import TestCase, override_settings from django.conf import settings temp_directory = tempfile.mkdtemp() @override_settings(PROTECTED_ROOT=temp_directory) class LoginTestCase(TestCase): @classmethod def setUpTestData(cls): cls.example = Example.objects.create( media = 'mock_file_or_image' ) To avoid the file system for as much as possible i would like to use temporary directory, however, files are still added to PROTECTED_ROOT, why? What can i do about it? Or is my thought process completely off and should i go for a different approach altogether? -
Preventing security exceptions in production
I am developing a Django App and I was writing a method in a class model when I realised that there was a possibility in which I would accidentally call the method with a key out of the dictionary that it uses to check the Tier level: def has_tier(self, tier_code="01A"): # it defaults to tier 1 current_tier = self.__verification_tier() # Type: int tiers = {'00X': 0, '01A': 1, '02A': 2, '02B': 3} required = tiers[tier_code] return bool(current_tier >= required) I was going to write a try-except clause since I thought: what if in production the method is accidentally called with a tier level out of the dictionary and it raises a KeyError? But then I also thought: that won't possibly happen since I am the one writing the validations and manually injecting the string into the method, it is not user input that might "mis-processed". Also if I don't catch the exception, I might assure in development stage that the application won't rise any error once all of its functionalities are tested. That way I am able to correct all the errors. I also thought that I could implement a logging module that writes into a file/database all the exceptions … -
Static file in django without Using {% static "abc.jpg" %}
I had static files in django. Project Structure Sample I have project structure like above i want to use js and img from asset folder. How can i do this ? How i can avoid using {% static "abc.jpg" %} ? -
Custom primary key in Django model
Here is my model: class InvitationCode(models.Model): code = models.CharField(max_length=6, primary_key=True) group = models.OneToOneField(Group, on_delete=models.PROTECT) According to doc, primary_key=True implies null=False and unique=True. However this is not what I see: >>> from app.models import InvitationCode >>> c = InvitationCode(group_id=1) >>> c.save() >>> c.pk '' >>> c1 = InvitationCode(group_id=1) >>> c1.save() >>> InvitationCode.objects.all() <QuerySet [<InvitationCode: InvitationCode object ()>]> Why Django allowed me to have primary key as empty string? Why uniqueness constrain didn't work? -
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.