Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Serializer Field Optional
Right now I have an input and two checkboxes that will return a variable to python back end. I would like to have the two checkbox with default value false and if they are checked to return true. I think my problem is as I'm using a Serializer, that I don't get a value from the two checkboxes if they are unchecked. If the checkbox are checked my code works and the value is saved in the model. If not I get an error html <input type="text" ng-model="var.name"> <input ng-model="var.pem" type="checkbox"> <input ng-model="var.key" type="checkbox"> Serializer class CreateSerializer(serializers.ModelSerializer): class Meta: model = Thing fields = ( 'name', 'pem', 'key', ) model class Thing(models.Model): name = models.CharField(max_length=50) pem = models.BooleanField(default=False) key = models.BooleanField(default=False) Would it be possible to have an existing value for the Serializer if the checkbox stay unchecked? -
Django web page + DRF structure
I am developing an Android app which needs an API, I built an API using Django Rest Framework and now I need to develop a web page which will have the tasks of being the landing page, register users and upload content for the Android app, I am thinking on doing this also using Django (mostly because it´s the only framework I know a little so far and it would be faster for me), but I am confused about what to do about the structure of the project, should I put the web page in the same project in which I have the API (i.e. the code together with DRF) or should I create another project and then share the db between them? I haven´t been able to find any examples or answers to this, last it´s even advisable to do this using Django for both backend and UI web page development or should I use another thing like react or angular (Which btw I don´t know, I´ve just have heard from them)? -
Web development with Python without using a Framework like Django
I´m trying to port my web development skills with PHP to Python, but I would like to know first if it´s possible the web development with Python without using a Framework like Django, and use it like backend such as PHP development, i mean, using HTML/Jquery AJAX to send POST parameters to .PY file and recive a response, create an "index.py" and use HTML/Python code mixed such as PHP or connect to MySql Data base for example. -
Issues With Block Title in Django Template
I'm trying to add a custom Title to my product pages using the block title tag in Django. I have a view function to return data to a template for the product page: def deal_by_detail(request, slug): deal_detail = Deal.objects.filter(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) and URL for the deal_detail page: url(r'^(?P<slug>.*)/$', deal_by_detail, name='deal_detail'), In my 'deal_detail.html' page I have successfully displayed all the information from a particular product... like so: {% for deal in deal_detail%} {{ deal.title}} {{ deal.price}} {% endfor %} However i'm having an issue with the block title. Since it comes before the aforementioned loop, i realize I can't reference the title like so: {% block title %}{{deal.title}}{% endblock %} I've also tried it like this: {% block title %}{{deal_detail.title}}{% endblock %} But that doesn't work either --nor does just {{ title }} I also experimented with a duplicate of the other loop and that doesn't work either. Here is what I have on the base template page that is extended from this deal_detail template: <title>My Site - {% block title %}{% endblock title %}</title> Just kind of stumped and not sure if I need a class based view or something I'm totally missing here. Thanks in … -
Using os.path.join in Django's annotate function
I store images on my file system writing file names in a db table. Now, my goal is to get the full name (that is, full path plus the file name) of these images in a Django template. To achieve this, right now I am doing the following (assuming that the images are all stored in one directory): MyModel.values(...).\ annotate(photo_fullpath = Value(os.path.join(settings.CONTACT_PHOTOS_DIR, F('photo_file')), output_field=CharField())) However, this code yields an error, namely: photo_file is the column that stored file name of the image. join() argument must be str or bytes, not 'F' I have tried all reasonable and unreasonable variations, but still have no success. I could overcome this issue writing the full path to the database, but this is bad solution clearly (in terms of portability of the code, etc...). Any ideas? -
Change Password Django
I have the following functions to change a password and display the users profile, but upon submitting the form instead of being redirected to the 'profile/' page I get an error saying The view core.views.change_password didn't return an HttpResponse object. It returned None instead., why is this? from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash def change_password(request): if request.method == "POST": form = PasswordChangeForm(data= request.POST, user = request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) #this function keeps the user logged in afte they change their password # request.user could not have been passed in because that would pass in 'AnonymousUser', however #form.user gets the user who was filling in the form and passes it to the function return redirect('/profile') else: form = PasswordChangeForm(user = request.user) args = {'form': form} # gives access to the form in the template return render(request, 'core/change_password.html', args) def view_profile(request): args = {'user': request.user} # return render(request, 'core/profile.html', args) Note: The profile page does work on other parts of the site, for example after logging in the user is redirected to their profile page with no issue. -
Heroku Django ValueError: invalid literal for int() with base 10: '-'
I keep getting ValueError when running migrate on Heroku. My django application works with no problems locally. From what I can see I think the problem is with this model, but I can't find what it could be. Specially because running makemigrations and migrate locally works just fine. The error I get: (note: only on heroku when running: heroku run python manage.py migrate) Running python manage.py migrate on ⬢ nameless-sands-... up, run.1867 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, narocilnice, sessions Running migrations: Applying narocilnice.0012_auto_20170808_1312...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 215, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, … -
Django - Using stringformat in template is not working
I am trying to add leading zeros so that '1' becomes '01' and '13' stays '13'. code: <td>S{{ x.nextepiseason|stringformat:"02d" }}E{{ x.nextepinumber|stringformat:"02d" }}</td> adding: |stringformat:"02d" does not display anything, but once I remove that, everything ends up working. Why isn't the leading zeros working? -
Create a hyperlink to external website in django
I have a litlle problem about a creating the hyperlink to external website in django for example in to the google.com I have in my html file something like : Adres www: <a href="{{ det_wpisu.adres_www }}">{{ det_wpisu.adres_www }}</a> <br /> but the www address when I click showing me : http://localhost:8000/detale/3/www.google.com and returned the 404 page. -
Django database design - Use an attribute or a method
I have what I thought was a simple question. I am designing a database and I have a doubt about it. this is the model class DailyCash(models.Model): # Relations # Attributes - Mandatory initial_cash = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('initial cash'), ) daily_incomes = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('daily incomes'), ) daily_expenses = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('daily expenses'), ) next_initial_cash = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('next initial cash'), ) # Attributes - Optional # Object Manager objects = managers.DailyCashManager() # Custom Properties # Methods # Meta and String class Meta: verbose_name = _("Daily Cash") verbose_name_plural = _("Daily Cash") ordering = ('id') def __str__(self): pass Well, my dobut is I need to calculate the daily balance but I'm not sure if is better use a attribute for this value or use a property what is fastest for future uses when the daily cash have more than 3 years or something like that to make the monthly balances or year or what i need, what is better for this in a future. use a field daily_balance and store in the database the value or calculate this value each time it's needed like this @property def daily_balance(self): return self.initial_cash + self.daily_incomes - self.daily_expenses - self.next_initial_cash Well, … -
Rolling back a set of db transactions upon exception in Django
To start off with, this GitHub project contains the code I'm discussing and asking about in this post. It's a non-proprietary and short example of something that's actually being worked on by my team. I'm working on a project where we use Django database transactions to do updates on a table in preparation for conversion to XML that can be used for business purposes. We have fixed formerly broken code by using transaction.atomic() context managers to make sure that errors are handled correctly. Each UPDATE statement sits within a context manager, which, in turn, sits within a function. There are three of these functions (set_yes(), set_no(), and broken_query()) called within another function (bulk_set()) in the program: models.py from __future__ import unicode_literals from django.db import connection, DatabaseError, transaction import pandas as pd from django.db import models class TestTable(models.Model): value1 = models.IntegerField() value2 = models.IntegerField() same = models.CharField(max_length=3, null=True) def setup_table(): """ sets up the basic table. several rows will have matching values, some won't. :return: None """ row1 = TestTable(value1=1, value2=1) row1.save() row2 = TestTable(value1=2, value2=1) row2.save() row3 = TestTable(value1=56, value2=1) row3.save() row4 = TestTable(value1=10, value2=10) row4.save() def set_yes(): """ sets "same" column on rows with matching value1 and value2 columns … -
Is there a way to add "Collation" in to Django 1.3 query?
I need to make a get query like: obj = Current.objects.get(Code='M01.C0001') But the query giving "Multiple Objects Returned' error because of the database has another record with similar unicode string 'M01.Ç0001' [<obj: M01.Ç0001>, <obj: M01.C0001>] I try to fetch data with field lookup functions, but it does not work anyway. I googled around but I didn't find a way to temporarily set the Collation for this query. Is it possible to temporarily set collation during executing a get query in Django 1.3? -
Can't open my website both in production and localhost from other IP. Everything works from home IP
I have developed a django project from home IP. It works both locally and in production from home. But when I work from other place(coworking),I can't open both localhost and proaction. No error, just eternal loading. Connection is fine :) What could it be?? -
404 Page not found Django
Yesterday I was working on my django project and it was working pretty well, but today when I ran the server and try to access my page, it didn't work. error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Oraculum_Data/cancerColo/ Using the URLconf defined in Oraculum.urls, Django tried these URL patterns, in this order: ^admin/ ^Oraculum_Data/ ^$ ^Oraculum_Data/ ^Oraculum_Data/login/$ ^Oraculum_Data/ ^Oraculum_Data/cancerColo/$ ^Oraculum_Data/ ^Oraculum_Data/api/data/$ ^Oraculum_Data/ ^Oraculum_Data/api/chart/data/$ The current path, Oraculum_Data/cancerColo/, didn't match any of these. my url patterns: urlpatterns = [ url(r'^admin/', include('Oraculum_Data.urls')), url(r'^Oraculum_Data/', include('Oraculum_Data.urls')) ] my url patterns in Oraculum_Data app: from django.conf.urls import url from . import views from django.contrib.auth.views import login urlpatterns = [ url(r'^$', views.home), url(r'^Oraculum_Data/login/$', login, {'template_name': 'Oraculum_Data/login.html'}), url(r'^Oraculum_Data/cancerColo/$', views.cancerColo), url(r'^Oraculum_Data/api/data/$', views.get_data), url(r'^Oraculum_Data/api/chart/data/$', views.ChartData.as_view()), ] my Oraculum_Data app views.py file: from django.http import JsonResponse from django.shortcuts import render, HttpResponse import requests import pandas as pd from rest_framework.views import APIView from rest_framework.response import Response def home(request): name = "Test name" args = {'MyName' : name} return render(request, 'Pages/HomePage.html', args) def cancerColo(request): response = requests.get('http://sage.saude.gov.br/graficos/cancerMamaColo/cancerColo3544.php?output=json') response_json = response.json() df = pd.DataFrame(response_json['resultset'], columns=['Ano', 'Branca', 'Amarela', 'Ignorada', 'Indigena', 'Parda', 'Preta']) args = {'dataframe' : df.to_html(classes="table table-striped"), 'name' : 'Câncer de colo de útero (por raça)'} return render(request, 'Pages/CancerColo.html', … -
Registration form django that inherits form UserCreationForm
I am following a tutorial that has created the following registration form: 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 Why isemail = forms.EmailField(required = True) the only field mentioned outside of class Meta, what is the purpose of this? -
allauth account edit in django
I am building an application with django and I decided to opt for the allauth authentication. now I have a profile page and I want users to be able to edit their account to Include Bios, Last_name ,first_name and thingx like that and possibly include a display picture but I inplemented some codes and I got an error an I have been stocked at it for a long time. the Error is error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Olar/Desktop/arbithub/src/profiles/models.py", line 27, in <module> class Profile(models.Model): File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 331, in add_to_class value.contribute_to_class(cls, name) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/options.py", line 206, in contribute_to_class raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) TypeError: 'class Meta' got invalid attribute(s): fields,model model.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Profile(models.Model): username = models.CharField(max_length=125) email = models.EmailField(max_length=125) first_name = … -
send notification when delete user
How can I send email notification when delete user from list? I have a form on the site. With it, I add the user.When the user is added, I receive a notification to the mail. How can I get notified when a user is deleted? Views.py: class CreateUser(CreateView): template_name = 'staffweb/add_user.html' form_class = AddUserForm model = StaffPersonal context_object_name = 'staff' success_url = reverse_lazy('home') def form_valid(self, form): new_user = form.save() new_user_name = new_user.full_name msg_args = ['New user added: ' + new_user_name] send_to_bot('\n'.join((msg_args))) email_text = make_letter(*msg_args) send_to_email(settings.ADMIN_EMAIL, email_text) return super(CreateUser, self).form_valid(form) class DetailUser(DetailView): template_name = 'staffweb/user.html' model = StaffPersonal context_object_name = 'user' class DeleteUser(DeleteView): model = StaffPersonal success_url = reverse_lazy('home') Thank you! -
Generate multiple line charts in Django with ChatJS
(my english is not good) i'm working in Django, to draw some graph in function of my modules. ie: if i have 2 modules, i want 2 charts , if 8 modules, 8 charts. Modules are integreted in a plugin. so i can list all modules found in a plugin. i do this in Django: def plugin_graph(request, hub_uid, plugin_uid): request.session['is_admin'] = True hub = Hub.objects.get(mac=hub_uid) fields = [] if request.method == 'GET': if 'field' in request.GET: fields.append(request.GET['field']) plugin = Plugin.objects.get(uid=plugin_uid, hub=Hub.objects.get(mac=hub_uid)) #on recupere lensemble desmodules de ce plug modules = plugin.get_modules_list() #pour chak module, tracer son graph for m in modules: modules_list = {'uid':m.uid, 'name':m.name, 'version':m.version, 'type':m.type, 'time':m.last_time(), 'rssi':m.rssi(), 'status_icon':m.status_icon()} module = Module.objects.get(uid=m.uid, plugin=Plugin.objects.get(uid=plugin_uid, hub=Hub.objects.get(mac=hub_uid))) historic = sorted(ModuleDocument.objects.filter(module=module), key=getKey) values = get_graph_values(historic=historic, dates=None, fields=fields) print values field = None if len(fields) < 1 else fields[0] return render(request, "admin/graph2.html", { 'values': values, 'hub': hub_uid, 'plugin': plugin_uid, 'uid': m.uid, 'module': module, 'fields': module.get_number_fields(), 'field': field, 'level': 'module', } ) After recuperate all my modules i draw the charts like that in javascript: <script> var ctx = document.querySelector("#chart"); var data = JSON.parse('{{ values }}'.replace(/&quot;/g, '"')); var labels = []; var values = []; var beginAtZero = true; for (obj in data) { labels.push(data[obj].x); … -
Django formsets values in jQuery
How to get Django formset values using jquery. I have another field in which I want to populate all the choices entered in formset. What to do.... -
Why won't the user input go into the database?
As of now, my database works fine. I can manually create dummy email address' via Terminal and they'll appear with no problems. This time, I want to the user input to go into the database. I feel that I'm pretty close with the code I have now. But I keep getting this error in Chrome: Here's the error: TypeError at /content/content/ 'name' is an invalid keyword argument for this function Request Method: POST Request URL: http://127.0.0.1:8000/content/content/ Django Version: 1.11.3 Exception Type: TypeError Exception Value: 'name' is an invalid keyword argument for this function Here's basic.html: {% extends "personal/header.html" %} {% block content %} <style type="text/css"> h1 { color: #2e6da4; font-family: Chalkboard; } .text { text-align: center; } </style> {% for c in content %} <h1>{{c}}</h1> {% endfor %} <div class="form-group"> <form method="POST" action="content/"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Submit</button> </form> </div> {% endblock %} Here's views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Email from django.core.exceptions import * def index(request): return render(request, 'personal/home.html') def contact(request): if request.method == "GET": return render(request, 'personal/basic.html', {'content': ['If you would like more information, leave your email.']}) elif request.method == "POST": email = Email(name=request.POST.get("textfield")) email.save() return render(request, 'basic.html') def … -
Django positional/keyword argument issue in form
I'm getting a __init__() got multiple values for keyword argument 'school' error when trying to submit a form. There's something hinky with the arguments, but I can't quite nail it down. view: if "AddCourse" in request.POST: #"AddCourse" is the name of the submit button in the template f = CourseAddForm(request.POST, prefix='crs')#, school=this_school) #use Instance to edit previous stuff g = SectionAddwCourseForm(request.POST, prefix='sctn', school=this_school) if f.is_valid() and g.is_valid(): new_course = f.save() new_section = g.save(commit=False) new_section.course = new_course new_section.save() g.save_m2m() s=Scollection.objects.create(Name="All Standards",Active=True,course=new_course) else: print 'invalid' form: class SectionAddwCourseForm(forms.ModelForm): class Meta: model = Section fields = ['Name','teacher'] labels = { "Name":"Section Name", } def init(self, school, *args, **kwargs): super(SectionAddwCourseForm, self).init(*args, **kwargs) print school try: #self.fields['standards'].queryset = self.instance.standards.all() #works to get current ass't stds self.fields['teacher'].queryset = Teacher.objects.filter(school=school).order_by('LastName') except: print "except teacher list for this school" pass -
Django data correct on dev server, but not after apache deployment
Extremely baffling problem. I recently created a django app that would get SQL data (_mysql query), load it into json format, and then load it into a web interface. The way I have it loaded in the web interface is creating a single list (it's ordered correctly) with all of the data in it, as I do not know how many rows there will be and then using: {% for item in big_list %} {% cycle '<tr>' '' '' '' '' '' '' '' '' '' '' '' ''%} <td style="...">{{item}}</td> {% cycle '' '' '' '' '' '' '' '' '' '' '' '' '</tr>' %} {% endfor %} This code allows me to cycle through the list, and create a new row for every 13th item as this table has 13 columns each corresponding to a specific field. There can only be a multiple of 13 items in the list (i.e. if the list had 39 items then there would be 3 rows). This works completely fine on django's dev server. However I deployed my proj on apache using mod_wsgi, and now the data does not fall under the correct column. The data will stay together (there is … -
Django/VueJS/PostgreSQL adding leading/trailing whitespace tabs
I have a text-field in Django I'm maintaining using Django-admin that requires preservation of white-space. As a result I'm wrapping it in a <pre> </pre> tag to do this when rendering using vueJS and vue-material. The whitespace appears to be retained when using this method, and when looking at the descrip field of my model manually in python manage.py shell the whitespace is indeed stored in my db. However, for some reason there is a mysterious leading white-space tab both at the beginning and end of my HTML when rendered, shown here: And showing up in the HTML here: Code snippets: relevant html and css <md-layout md-column md-flex-xsmall="100" md-flex-small="55" md-flex-medium="70" md-flex-large="80" id="summary_block"> <md-layout > <pre class="md-body"> [[ product.descrip ]] </pre> </md-layout> </md-layout> #summary_block > div.md-layout > pre { white-space: pre-wrap; word-wrap: break-word; font-family: inherit; } Could this be a postgres issue? If so why wouldn't the whitespace show up when looking at object.descrip in the python shell? I'm using postgres, vuejs, django v 1.10, python 3.5 and vue-material if any/all of that helps. -
Django : use uuslug with allow unicode
I'm using django.utils.text.slugify to generate slug and this function has allow_unicode parameter; when I want to generate slug by Unicode characters like Persian and Arabic, I used this. Now I want work with uuslug and need to generate slug with Unicode characters. What's your suggestion to do that? -
django-tables2 module missing
I am trying to use django-tables2 in my django project but I keep getting "ModuleNotFoundError: No module named 'django-tables2'" error. installed it with pip install - everything OK. added django-tables2 to INSTALLED_APPS (it seems the problem is here). Thanks you.