Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save POST data with multiple checkboxes using Django ?
Django version=1.10.2 and python 2.7 Im learning django and trying to clone to-do list item like this Here is the models file for todo:- class Todo(models.Model): title = models.CharField(max_length=200) # text = models.TextField() completed = models.BooleanField(null=False,default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title #this makes djangoadmin page show title inthe list The views file from django.shortcuts import render from models import Todo def index(request): todos = Todo.objects.all() context = { 'todos':todos } if request.method == 'POST': title = request.POST['title'] todo = Todo(title=title) todo.save() return render(request,'index.html',context) else: return render(request,'index.html',context) def show_completed(request): #show completed task only todos = Todo.objects.filter(completed=True) context = { 'todos': todos } return render(request, 'index.html', context) def show_active(request): #show active task list todos = Todo.objects.filter(completed=False) context = { 'todos': todos } return render(request, 'index.html', context) def clear_completed(request): #Delete the completed tasks Todo.objects.filter(completed=True).delete() todos = Todo.objects.all() context = { 'todos': todos } return render(request, 'index.html', context) def save_state(request): pass The template file "index.html" <!DOCTYPE html> <html lang="en"> <head> </head> <body> <h3>Todo List:</h3><hr> <form method="post" action="{% url 'index' %}"> {% csrf_token %} <input type="text" name="title" id="title"/> <input type="submit" value="submit" /> </form> <hr><br> <form method="post" action="{% url 'save_state'%}"> {% csrf_token %} <ul>{% for todo in todos %} <li> <input type="checkbox" name="completed" value="True" … -
Duplicate key error in django-treebeard using MP and node_order_by
I have an account system that has a nested group structure per account. Each Account consists of multiple users that each can have permissions based on the groups they are in (a User has the permissions of the group they are in and of all the children of that Group. My Group model looks as follows. It is basically coupled to an Account has a title and contains Users. Each Account has one "main"/root-level Group linked to it so we can easily access the tree for an Account class Group(MP_Node): node_order_by = ['title'] account = models.ForeignKey(Account, related_name='groups', verbose_name=_('account')) title = models.CharField(_('title'), max_length=255) users = models.ManyToManyField(User, related_name='groups', verbose_name=_('users')) When adding a new Account and corresponding "main"/root-level group for that Account I sometimes get the following error: IntegrityError: duplicate key value violates unique constraint "accounts_group_path_key" DETAIL: Key (path)=(003A) already exists. It looks like it has something to do with the title of a Group. When adding "LLL-MIDDLE" the error shoots, when adding "ZZZ-END" it does not. I can't seem to figure out what I'm doing wrong that is leading to this error popping up from time to time. Can anybody help me? -
Is it a good practice to use serializer as query parameters validators?
Serializer would not be used for its intended purpose of creating some django model but it would be used for query parameters validation, creation of filtering query to elasticsearch, swagger documentation describing API. from rest_framework import views, serializers, fields from rest_framework.response import Response class TestQueryParams(serializers.Serializer): id = fields.IntegerField(min_value=0) date = fields.DateField(format='%Y%m%d') class TestView(views.APIView): def get(self, request): qp = TestQueryParams(data=request.query_params) qp.is_valid(raise_exception=True) # parameters would not be used to create some model # but they would be used to get data return Response({'some': 'data'}) -
How does default_token_generator store tokens?
I recently built a Django-based authentication system using a tutorial. Within this System I created a token within a forms.py. This Token is then send (as a link) in an activation activation mail. from django.contrib.auth.tokens import default_token_generator token = default_token_generator.make_token(user) The view which receives the get request matches the token and the user-id supplied in this link and checks the token using: default_token_generator.check_token(user, token) This verifies that the token was sent though my site. But I don't understand the process. The token is unique but I don't seem to save the token somewhere? So how does check_token()verify the token? Also - is there any setting for the token_generator to set, how long the token should be valid? -
Unit test form with ImageField in django
I have model with ImageField. I am trying to write unit test to my form but it always raise error. Can someone say me where is my mistake? From error I understand that form is not valid. print str(form.errors) return me this: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Error: Traceback (most recent call last): File "/home/nurzhan/CA/slider/tests.py", in test_form_valid self.assertTrue(form.is_valid()) AssertionError: False is not true tests.py: def test_form_valid(self): self.image_file = open( os.path.join(BASE_DIR, 'static/images/test.jpg'), "rb" ) data = { 'image': self.image_file } form = ArticleForm(data=data) self.assertTrue(form.is_valid()) print data return me: {'image': <open file '/home/nurzhan/CA/static/images/test.jpg', mode 'rb' at 0x7efe24b47b70>} Also I tried to use this: data = { 'image': SimpleUploadedFile( self.image_file.name, self.image_file.read() ) } In this case print data return me {'image': <SimpleUploadedFile: test.jpg (text/plain)>} forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('image',) def __init__(self, *args, **kwargs): super(SlideForm, self).__init__(*args, **kwargs) self.fields['image'].widget.attrs = { 'accept': 'image/png, image/jpeg, image/gif', 'id': 'image', } models.py: from django.db.models.signals import pre_save from django.dispatch import receiver class Article(models.Model): image = models.ImageField( upload_to='article/images/%Y/%m/%d/', blank=False, ) @receiver(pre_save, sender=Article) def delete_old_slide_image(sender, instance, *args, **kwargs): if instance.pk: article = article.objects.get(pk=instance.pk) if instance.image and article.image != instance.image: article.image.delete(False) -
Invoke a Javascript function in HTTPResponse
Following up on this SO answer, I am trying to run a JS on the page in HTTPResponse return HttpResponse("<script>alert('Yep, JS running.');window.location.href='/path/to/original/url'; parent.show_modal_form('" + json.dumps(my_list) + "');};</script>") But the js function is defined in the page referenced above and it tries to execute the script before loading (and not after loading) the page, and hence fails to find the function. Any ideas on how to make it execute after the window.location.href has loaded the page, so that it can find the js function being called ($(document).ready won't work because JQuery is also not loaded yet. I tried window.load but that also does not work (i.e it fails to find the javascript function) My use case is that the user performs an action in the Django Admin page, and as a result the user needs to see a modal dialog form on the same page (after executing some logic back in the view) -
How to connect Django to external DB without migrations
I would like to connect my DjangoApp to an external MySQL database. I don't want to make migrations to this table, I mean I don't want to create new tables ,just pull data. And my question is - how to do this ? If i add this table to DATABASES in my settings file then the console shows an error about mandatory migration. What can you recommend me ? Thanks in advance, -
Compute multiple model properties in one call
I have Django Model which have two properties: class M(Model): @property def p1(self): return process_result(SomeModel.objects.filter(val_gt=1)) @property def p2(self): return process_result(SomeModel.objects.filter(val_lt=1)) And both used in Django Admin list_lisplay = ('p1','p2',) I want to replace 2 database queries with 1, something like this class M(Model): def some_hook(self): res = SomeModel.objects.all() self.p1 = process_result(filter(lambda l:l.val > 10, res)) self.p2 = process_result(filter(lambda l:l.val < 10, res)) PS: problem with >10 or <10 is just an example for simplification, I only want to find a way how to define multiple properties with performing one common database query -
Django Best way to store price history of millions of products?
I am running a web scraping spider that scrapes nearly 1 million products on a daily basis. I am considering 2 approaches: 1) store all products prices history in one table product_id, date, price but this would yield a multi million records in this table. 2) store data in multiple tables & make separate table for each product. Table1: product_id, current_price Table_product_id: date, price Table_product_id: date, price Table_product_id: date, price But I will have nearly 1 million tables! -
NameError: name 'convert_symbol_to_int' is not defined
I got an error,NameError: name 'convert_symbol_to_int' is not defined when I run this code. I wrote class ReadData(): def __init__(self, sheet_path): self.book = xlrd.open_workbook(sheet_path) self.sheet = self.book.sheet_by_index(1) self.users = [] def read(self): for row_index in range(2, self.sheet.nrows): rows = self.sheet.row_values(row_index) if rows[1] != '' and rows[2] != '' and rows[4] != '': woman = convert_symbol_to_int(row[8]) man = convert_symbol_to_int(row[9]) def convert_symbol_to_int(self,arg): if arg == '○': return 2 elif arg == '×': return 1 elif arg == '△': return 0 else: return -1 x = ReadData('./data/excel1.xlsx') x.read() I really cannot understand why this error happens. Why can't I access convert_symbol_to_int?How should I fix this? -
Cannot change thread mode after it is set IIS django
I have created a project using django and i have used COMtypes for accessing power-point. It is working fine on local host development but when i hosted it on IIS its giving me error "Cannot change thread mode after it is set". comtypes.CoInitializeEx(comtypes.COINIT_MULTITHREADED) powerpoint = comtypes.client.CreateObject("PowerPoint.Application") powerpoint.Visible = 1 powerpoint_file = powerpoint.Presentations.Open(download_path) powerpoint_file.SaveAs(convert_path, 32) powerpoint_file.Close() powerpoint.Quit() comtypes.CoUninitialize() -
Django ORM get only field in foreignkey relationship
I have database tables like this class Message(models.Model): text = models.CharField(max_length=200) length = models.CharField(max_length=100) receivers = models.IntegerField() Network(models.Model): name = models.CharField(max_length=100) is_down = models.BooleanField(default=False) class SMSLog(models.Model): receiver = models.CharField(max_length=200) message = models.ForeignKey(Message, related_name='log') network = models.ForeignKey(Network) status = models.CharField(max_length=200) I need just three fields in my query i.e. text, log__receiver and log__network__name. I tried like this Message.objects.all().prefetch_related('log').only('text', 'log__receiver', 'log__network__name') The above query does not work. How to do query like above in django ORM ? -
admin specific app in django
I'm using Django 1.11 I want to create an admin specific app which is only accessible by admin interface. I want to create an app to add country and state records which can be added or edited only by Admin from /admin. Also, these records can be used by any application to populate a select field in adding a record like address. Where to create a model for this? Is it possible to create a admin specific app only? -
NameError: name 'sheet' is not defined
I got an error,NameError: name 'sheet' is not defined .I wanna parse excel and print the content. I wrote class ReadData(): def __init__(self, sheet_path): self.book = xlrd.open_workbook(sheet_path) self.sheet = self.book.sheet_by_index(1) self.companies = [] def read(self): for row_index in range(2, sheet.nrows): rows = sheet.row_values(row_index) print(rows) x = ReadData('./data/excel1.xlsx') x.read() I really cannot understand why this error happens.Should I add something to use init ?How can I fix this? -
django user management adding user with ajax
In django library, there is a user management where it allows adding of users to the database. I have a web page that allows creation of user, but what I want to do is to be able to create users remotely from another domain, by posting the username password etc over ajax to django. in urls.py: url(r'^user/add/$', UserCreateView.as_view(), name='user_add'), views.py: class UserCreateView(SingleObjectCreateView): user = UserForm view_permission = permission_user_create def form_valid(self, form): user = form.save(commit=False) user.set_unusable_password() user.save() messages.success( self.request, _('User "$s" created successfully.') % user ) return HttpResponseRedirect( reverse('user_management:user_set_password', args=(user.pk,)) ) my ajax post from the other domain: $.ajax({ type: "POST", url: "https://mydjangourl/accounts/user/add/", data: { username: "testusername", first_name: "firstname", last_name: "lastname", is_active: "on", submit: "" } }); When I created a user from my django app, I compared the form data being posted with my personal JavaScript app, both posted the same form data over, but when I checked the database no new user was being created from my personal app.. Am I posting it wrongly? Note: csrftoken authentication has been disabled as it is not required. We are running in an offline environment. -
Compare with return value from a simple_tag
I'm using simple_tag to compute a value in django template. My current code looks like, {% for param_a in params_A %} {% for param_b in params_B %} <p>{% awesome_tag param_a param_b %}</p> # other_stuffs {% endfor %} {% endfor %} Now I want to skip other_stuffs if the returned value from awesome_tag is foo. I know I can do this in the view and then pass the items in the context, but I was wondering if there's any better Django template way to do this. -
Custom Authentication Backend in Django
How to write a custom authentication backend in Django taking scenario as Phone Number & OTP(One-Time Password) to authenticate against each user. How to authenticate each user in form of multiple conditions. If email is verified and password exist ( authenticate using email and password). If phone is verified and exist( authenticate using phone and otp or if password exist then auth using phone and password). -
Full Calendar in Django show events
I am new to both Django & FullCalendar so any assistance that can be provided is greatly appreciated. My ultimate aim is to display events from an O365 calendar in Django using FullCalendar. Putting aside the O365 integration for now at this stage I am just trying to get FullCalendar to display the current events in my model. I have tried to emulate the solutions posted here FullCalendar in Django and here Fullcalendar Does not display data but unfortunately the events are not displaying. Here is my code: models.py from my app called "bookings" from django.db import models class Events(models.Model): event_id = models.AutoField(primary_key=True) exchange_id = models.CharField(max_length=255,null=True,blank=True) event_start = models.DateTimeField(null=True,blank=True) event_end = models.DateTimeField(null=True,blank=True) event_subject = models.CharField(max_length=255,null=True,blank=True) event_location = models.CharField(max_length=255,null=True,blank=True) event_category = models.CharField(max_length=255,null=True,blank=True) event_attendees = models.CharField(max_length=255,null=True,blank=True) def __str__(self): return self.event_subject views.py. I've commented out the bits from the other solutions posted that relate to drop selection of category type. I have also tested using the below script in bookings.views.py, without success. from bookings.models import Events @method_decorator(login_required, name='dispatch') class CalendarPage(TemplateView): template_name = 'calendar.html' def event(request): all_events = Events.objects.all() # get_event_types = Events.objects.only('event_category') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] # … -
Trying to use CSS in Django Hello World
Right now I'm trying to use some basic CSS in my Django Hello World program. I can get "Hello World" to display, but the CSS effect isn't work. Currently this is what I have in my main URL: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), ] And this is what I have in my app URL. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] This is my views file. from django.shortcuts import render from django.http import HttpResponse def index(request): context = {"variable":"Hello World"} return render(request, "base.html", context) My base.html file {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> <link rel='stylesheet' href='{% static "css/base.css" %}'/> </head> <html> <p>{{ variable }}</p> <script src="{% static "base.js'" %}"></script> </body> </html> And my base.css file. h1 { color: 00FFFF; } Lastly, I added this piece of code on the bottom of my settings file. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") Ideally the page should show up with "Hello World" in a cyan color...unfortunately it just shows "Hello World" in … -
Validate and get the user using the jwt token inside a view
I am using django-rest-framework for the REST API. Also, for JSON web token authentication I am using django-rest-framework-jwt. After a successful login, the user is provided with a token. I have found how to verify a token with the api call, but is there any way to validate the token inside a view and get the user of that token, similar to request.user? -
Static Files are not found (404) when Debug is False
I want to see how my app works in production and i changed settings in my local machine, so i used below settings in settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I used python manage.py collectstatic which copied all the files from folder static to assets when i set Debug = True files served from assets with 200, one example (http://localhost:8000/assets/js/jquery-2.2.4.js) but when i set Debug = False the static files are not found with 404 error. -
How to resolve “django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: users” in Django 1.7?
Show me this error, Im working on Django 1.7, What's the problem and how do I resolve it? -
How do you integrate Brackets LivePreview with a Django project?
How do you integrate Brackets LivePreview with a Django project running the built in web server (i.e. manage.py server). The LivePreview is taking the absolute path of the html files. Anybody knows? -
Restrict form field choices based on previous model choice in Django
I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this: I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand. So far I have this: models.py class Race(models.Model): race_name = models.CharField(max_length=200) race_size = models.CharField( max_length=2, choices=SIZE_CHOICE, default='M') race_speed = models.IntegerField( default=30) race_lang = models.CharField(max_length=200, null=True, blank=True) race_str = models.IntegerField(default=0, null=True, blank=True) race_dex = models.IntegerField(default=0, null=True, blank=True) race_con = models.IntegerField(default=0, null=True, blank=True) race_int = models.IntegerField(default=0, null=True, blank=True) race_wis = models.IntegerField(default=0, null=True, blank=True) race_cha = models.IntegerField(default=0, null=True, blank=True) skill_spend = models.IntegerField(default=0, null=True, blank=True) race_extra = models.TextField(max_length=2000, blank=True, null=True) race_source = models.CharField(max_length=200, blank=True) def __str__(self): return self.race_name class Meta: verbose_name = 'Race' verbose_name_plural = 'Races' class Subrace(models.Model): sub_name … -
Django 404 page goes to 500 page when there is a closing body tag in the template
We use Django 1.11 in our platform which is made up of quite a few applications. I am currently updating the look of our current 404 and 500 pages. I have an Error page Template and the 404 and 500 extend that template. When testing using an incorrect URL I am always diverted to the 500 page instead of the 404. If I remove the closing body tag from the template the 404/500 uses the and test with an incorrect URL the 404 page test fine. To Note: I have also tried hard coding a simple 404.html and whenever adding a closing body tag this issue still happens. Any ideas why the body tag could/would affect the 404 page loading in this way?