Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - jinja template couldn't set variable
I want to set a flag in django template - for showing only first error in form - to avoid too much error log. But I'm getting TemplateSyntaxError: 'set', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Code I'm working with: # template.html <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="display: none">{{ field.help_text }}</small> {% endif %} {% if field.errors and errflag is not True %} {% set errflag = True %} # <-- Get err here {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endif %} </p> {% endfor %} <input type="submit" value="Submit"> </form> # views.py ... def post(self, request): form = UserRegistrationForm(request.POST) if form.is_valid(): return HttpResponse("Form submitted corectly") else: return render(request, self.template, { 'form': form, 'errflag': False }) Any sugestions? Thanks -
Django AutoOneToOneField migration and existing entries
Before starting working on new features, I had this model : class AppUser(models.Model): user = models.OneToOneField(User, primary_key=True) #Django standard user # And various standard data that we don't need here Now I needed to extend my database to store more information about the users I have in Django and I came accros django-annoying to build relations between like this : class TutorialProgression(models.Model): has_seen_home_tutorial = models.BooleanField(default=False) has_seen_revision_tutorial = models.BooleanField(default=False) has_seen_lists_tutorial = models.BooleanField(default=False) class AppUser(models.Model): user= models.OneToOneField(User, primary_key=True) #Django standard user # Various standard data tutorial_progression = AutoOneToOneField(TutorialProgression) What it does here is that when a new AppUser is created, a brand new TutorialProgression would be as well. But I have a problem with existing entries. I tried to migrate my postgres database with theses modifications and it asks me to provide a one-off default or to add a default in my models. I understand this, but how should I proceed to give each existing AppUser a unique TutorialProgression? -
Reverse for 'index' with arguments '()' and keyword arguments '{'request': <WSGIRequest: POST '/search/'>}' not found. 0 pattern(s) tried: []
I have a question: Why is this error? Reverse for 'index' with arguments '()' and keyword arguments '{'request': }' not found. 0 pattern(s) tried: [] views.py def index(request): ... def book(request, cate): ... def search(request): if request.method == 'POST': searchbooktitle = request.POST.get('search') print(searchbooktitle) try: searchbook = Book.objects.filter(title__contains=searchbooktitle) return redirect(book, request=request, cate=searchbook.pk) except: print(request) return redirect(index, request=request) return redirect(index, request=request) urls.py urlpatterns = [ url(r'^index/$', views.index, name='index'), url(r'^book/(?P<cate>[a-zA-Z]+)/$', views.book, name='book'), url(r'^chapter/(?P<pk>[0-9]+)/$', views.chapter, name='chapter'), url(r'^content/(?P<bookpk>[0-9]+)/(?P<chapterpk>[0-9]+)/$', views.content, name='content'), url(r'^search/$', views.search, name='search'), ] Traceback Switch to copy-and-paste view D:\Django1.8_env\lib\site-packages\django\core\handlers\base.py in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars D:\Djangodemo\bookmarks\account\views.py in search return redirect('index', request=request) ... ▶ Local vars -
Extracting data with BeautifulSoup and using FuzzyWuzzy to match Pandas data
I have a CSV file with a list of Towns, Countys, and Country. Town County Country Ampthill Bedfordshire England Arlesey Bedfordshire England Here is my script: df = pd.read_csv('Towns_List.csv') towns = list(df['Town']) request = requests.get('https://www.foo.com') soup = BeautifulSoup(request.content, 'lxml') location = product.find('div', {'class': 'listing-location'}).text test = fuzz.partial_ratio(towns, location) if test > 40: print(location + 'Found with ' + str(test) + ' ratio & Country:') else: pass If there is a fuzz ratio of 40 or higher then I want to print out the associated Country with that match. Any thoughts? Thanks, -
Django 1.9 foreign key for existing data
Based on answer from here, I try add foreign keys to existing data. My models: class ModelInteractions(models.Model): id1 = models.IntegerField(primary_key=True) id2 = models.IntegerField() comm = models.TextField(blank=True, null=True) class Meta: managed = False unique_together = (('id1', 'id2'),) class Models(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() And I added this line for Models model: interaction = models.ForeignKey(ModelInteractions, on_delete=models.CASCADE) makemigrations returns: You are trying to add a non-nullable field 'interaction' to models without a default; we can't do that (the database needs something to populate existing rows). ModelInteractions.id2 = Models.id in my case. From what I understand, ForeignKey default value must be ModelInteractions.id1, so I tried with the following code (even though I'm not sure it's the right way to do!): class Models(models.Model): def default_id(id): return ModelInteractions.objects.filter(id2=id).values('id1')[0] id = models.IntegerField(primary_key=True) name = models.TextField() # for ModelInteractions comm interaction = models.ForeignKey(ModelInteractions, on_delete=models.CASCADE, default=default_id(id)) But I get: TypeError: int() argument must be a string, a bytes-like object or a number, not 'IntegerField'. How can I make this work? -
Django: invalid literal for int() with base 10: 'number'
here is my code: **urls.py: ** from django.conf.urls import url, include from base_app import views from django.contrib.auth import views as auth_views app_name = 'base_app' urlpatterns = [ url(r'^forms/$', views.form, name='form'), url(r'^tables/$', views.table, name='table'), url(r'^register/', views.register, name='register'), url(r'^login/$', views.user_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'),# line added ] **views.py: ** def form(request): registered = False if request.method == 'POST': user_form = FormName(data=request.POST) if user_form.is_valid(): user = user_form.save() user.save() registered = True else: print(user_form.errors) else: user_form = FormName() return render(request, 'base_app/form-samples.html', {'user_form':user_form, 'registered':registered}) return render(request, 'base_app/form-samples.html') **models.py: ** class InfoForm(models.Model): username = models.CharField(max_length=256, default='username') email = models.EmailField(max_length=256, default='email') number = models.PositiveIntegerField(max_length=256, null=True) def __str__(self): return self.user.username **forms.py: ** class FormName(forms.ModelForm): class Meta: model = InfoForm fields = ('username', 'email', 'number') after that when i want to run "python manage.py migrate" i get this message -> ValueError: invalid literal for int() with base 10: 'number' where is the problem? -
capturing mouse clicks and images from desktop context from within Django web application
I have developed a windows desktop application (in python + kivy + win32 api) that creates content through recording mouse clicks and capturing the underlying images from desktop applications. I want to make migrate this application to the web and am thinking of using Django for this. But what would be the best approach for being able to record the mouse clicks and capturing images from the full desktop context of the end-user (i.e. not just what's happening in the browser context)? -
Can I implement a Zinnia blog app in my Django 1.11 project?
I searched all over the internet to find out whether I can use Zinnia with Django 1.11. I did not find a definitive answer. On the Zinnia Homepage they write: Django >= 1.10,<1.11. So, this means that I cannot use it. I found one user online who wrote that he uses Zinnia with Django 1.11 but he did not explain very much so I could not extract anything really. Do you know: Is this possible or will I run into errors? Thanks! -
Django Admin model html file
I'm trying to add javascript to my admin model so it refreshes automatically in 5 minute intervals. Where would I find the html file? -
Example Cron with Django
Has anyone made an scheduled task using any modules or app with Django? I have my current application working and I want to run a task every day. I've seen in other post that this can be made using cron and custom managment commands but I can't find any example. I've also tried to use: django-crontab django-kronos But neither of them worked for me, probabli because there must be some missing dependency. If any one has any working example, please share :). -
How to speed up performance of Django Rest Framework serializer with source from Model's method?
I have API endpoint based on DRF 3.6.3 which already responsive (<1s response time). But after I add new serializer field with source from model's method, it perform very slow (more than 30s response time). this is my snippet code: class Product(models.Model): a_name = models.CharField() b_name = models.CharField() def all_name(self): return u'%s %s' % (self.a_name, self.b_name) Serializer: class ProductSerializer(serializers.ModelSerializer): productid = serializers.ReadOnlyField(source='id') productallname = serializers.CharField(source='all_name') class Meta: model = Product fields = ('productid', 'productallname') read_only_fields = ('productallname', ) I only need to do small customization of my API output, and I don't think override setup_eager_loading(queryset) or to_representation() is right approach for this. thank you for your help. -
How does python resolve imports (especially in context of django)?
I am doing a tutorial to get to know Django. The last chapter I did was this one http://www.tangowithdjango.com/book17/chapters/models.html I am using a virtual-environment managed via virtualenvironmentwrapper. What I was wondering about is, how the imports really work. For example we have this statement: from rango.models import Category, Page where we work on the file admin.py which is located in the same folder .../rango/ as models.py so I would expect from models import Category, Page to be the import statement (which seems to work, too as far as i can test it). Ok, .../rango/ contains an __init__.py and therefore is considered as package as far as I know but why would I use the longer import-statement over the shorter one? But most important to me would be: When I use the shell to see sys.path I only get the directories created by my virtualenvwrapper where i would have expected it to contain (besides others) something like [...]/rango/.. (the path to the parent-directory of rango). How does the interpreter know where to search for those modules/packages in the first place? -
Create a dashboard file with unlimited number of widgets and dashboards... Where?
So i jus found an app called django-controlcenter which i would like to mess around with and look at, but in the installation instructions there is a line that says Create a dashboard file with unlimited number of widgets and dashboards: This gives me no information to where abouts in the project i should create this file, can anyone give me advice as to where the file would be best to go? Thanks Jordan. EDIT: ADDING DJANGO PACKAGE LINK http://django-controlcenter.readthedocs.io/en/latest/ -
How to find the number of objects in wagtail admin changelist?
How can I find the number of items in each changelist view of the wagtail admin? for instance the number of users registered in the system or the number of added blogposts. If it helps I'm looking for something similar to django admin. -
Unhandled exception in thread started by <function wrapper at 0x7f2f82ee3aa0> on Django
Unhandled exception occurs while passing function inside models.py in Django (installing by pip install numpy django requests) I am trying to manipulate face detection api on web using OpenCV, Numpy and Redis. But i got an exception on passing the fuctions inside the models.py I am just a newbee on Django framework and Python languages. Here is my error while running my Django server ! Unhandled exception in thread started by Traceback (most recent call last): File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/xyz/.xyz/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/xyz/.xyz/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/xyz/.xyz/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/xyz/.xyz/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/xyz/PycharmProjects/xyz_project/OpencvWeb/opencv_api/Face_detection/models.py", line 28, in class LFace: File "/home/xyz/PycharmProjects/xyz_project/OpencvWeb/opencv_api/Face_detection/models.py", line 29, in LFace def init(self, faceRect = LRect(), eyes=[], id = 0, mt = 0, vel = LVector(0,0)): NameError: name 'LRect' is not defined And Here is my code in models.py This is the class for LFace class LFace: def __init__(self, faceRect = LRect(), eyes=[], id = 0, mt = 0, vel = LVector(0,0)): … -
Django SQL get query returns a <key, value> hashmap, how to access the value?
I am using django 1.10 and python 3.6.1 when executing get_or_none(models.Character, pk=0), with SQL's get method, the query returns a hashmap i.e.: <Character: example> How can I extract the value example? I tried .values(), I tried iterating, I tried .Character nothing seems to work, and I can't find a solution in the documentation. Thank you, -
Convert to Localtime django queryset
I have this following model definition in my models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) body = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) in my settings.py I have TIME_ZONE = 'UTC' USE_TZ = True I want to get the times in specific timezone. right now if I call Blog.objects.all() it's giving all the times in UTC format. But I want the times in user timezone who requested. I know there are filters and tags available on this. But as I am doing rest_framework I think I need to be able to do in Queryset. Any help? -
editablegrid.loadXML for dynamically created files in Django project
I have been struggling with this for past week and see no light at the end of the tunnel. I am using Django version 1.11 with editablegrid (editablegrid.net) as my current preferred method to serve and edit data in tabular format. In order to use the editablegrid, I have created a generic function which will take any model object and create the required XML in editablegrid template. My media settings are as follows # media files - dynamically created as well as uploaded files ENV_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(ENV_PATH, 'media/') MEDIA_URL = '/media/' Media directory is on the same level as 'settings.py' is in the project. My static settings are as follows STATIC_URL = '/static/' ** STATIC_ROOT is not defined. Static files are stored application wise. Here is what I have tried .. A static XML stored in '/static/data/' directory is read by editablegrid and displayed as expected. A dynamically generated XML when copied in '/static/data/' is read by editablegrid and displayed as expected. Fun begins when I try to use the media_url . My dynamically generated files are stored in '/media/tmpdata' . The files are created like clockwork - however, editablegrid simply refuses to load them. The JS … -
Django Custom User Model Best Practice: User = get_user_model()?
I'm trying to create a custom user class and I'd like to know the best practice for implementing referencing the new user. After following the Django docs method of implementing the custom user as follows in models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass And settings.py AUTH_USER_MODEL = 'myapp.MyUser' And admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) The Django docs say to use settings.AUTH_USER_MODEL in place of user specifically for ForeignKeys and OnetoOneField, but it's not clear about other instances. I've seen other boilerplate code use this method as well in the beginning of views.py: from django.contrib.auth import get_user_model User = get_user_model() Are both valid and correct? Are there advantages of one over the other? -
Authorization header is missing in the request (Angular4 and Django)
I am using Django for RESTful API and Angular4 for client side. I have CORS settings in Django. From Postman everything is working fine. Same request is not working from Angular. Authentication is working. I am getting 401 Unauthorized as response for every request after getting the token. Authorization header is missing in the request even I am setting this explicitly. Could you please help me to find out what is wrong in my approach? Here I am setting the Authorization header in angular, Angular Code: public setUserData(){ var search = new URLSearchParams(); let headersObj = this.getAuthHeaders() as any; let requestOptions = new RequestOptions({ headers: headersObj }); let responseData = this.http.get(apiConfig.tokenValidateUrl ,requestOptions) .map(this.handleData) .catch(this.handleError); responseData.subscribe( response => { localStorage.setItem('user', response); }, error => { console.log(error) } ); } public getAuthHeaders():Headers{ let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json'); headers.append('Authorization', 'Bearer '+localStorage.getItem('token')); return headers; } Here is the CORS settings in Django, settings.py """ Django settings for referalsite project. Generated by 'django-admin startproject' using Django 1.11.3. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! … -
Foreign keys as QuerySet columns
So I have 3 classes, a group class, a sensor class and a value class. The classes are roughly defined like this: class SensorGroup(models.Model): name = models.CharField(max_length=100) logging_on = models.BooleanField(default=False) class Sensor(models.Model): device_id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=25, blank=False) last_updated = models.DateTimeField(auto_now=True) sensor_group = models.ForeignKey(SensorGroup, related_name='sensors') class Value(models.Model): sensor = models.ForeignKey(Sensor, related_name='values') time = models.DateTimeField(auto_now_add=True) value = models.FloatField(blank=False) The values are added for every sensor at 20 second intervals. I want to turn it into a table like this using pandas.DataFrame.from_records() say for group 1: | sensor_1 | sensor_2 | sensor_3 | timestamp | |----------+----------+----------+--------------| | 1.5 | 2.0 | 1.0 | 12:33 2/4/17 | |----------+----------+----------+--------------| | 2.0 | 1.5 | 3.3 | 12:34 2/4/17 | .... What I've tried so far: qs = Sensors.all().values('name', 'values__value') df = pd.DataFrame.from_records(list(qs)) print(df) Yields name values__value 0 sensor_1 0.0 1 sensor_1 1.0 2 sensor_1 2.0 3 sensor_2 0.0 4 sensor_2 1.0 5 sensor_2 2.0 Is there a way to make this query and convert it into a dataset? -
Django, RestFramework Selenium: How can I keep a webdriver through multiple requests?
I'm develoving web service with Django1.11, RestFramework, Selenium. I wanna keep webdriver instance through multiple requests. But I couldn't. This is my codes. from selenium import webdriver from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def first_api(request): driver = webdriver.Chrome() driver.get('#url that I keep open!') # some actions return Response(#some data) @api_view(['GET']) def second_api(request): driver.find_element_by_name('hoge') # this driver is made by first api # some actions return Response(#some data) Browser is opened when accessing first_api method. And keeping this browser open, when the time of second_api is accessed I use the browser again. How can I implement this? -
sms with api using django
Hi i had returned a code for sending sms using rpsms in python now i want to write this file in django with a text field in template import datetime import MySQLdb import urllib import urllib2 now = datetime.datetime.now() today1 = str(now)[:10] today = today1[5:] tmon=today[1] tday=today[2:] #print tmon conn = MySQLdb.connect("localhost","user","pswd","db" ) sqlcursor = conn.cursor() sqlcursor.execute("SELECT firstname,mobile FROM db.table") row = sqlcursor.fetchall() authkey = "XXXXX" # Your authentication key. url = "http://sms.rpsms.in/api/sendhttp.php" # API URL for message in row: mobiles = message[1] # gets all mobile numbers from the db print "message1:", message[1] message = "hi " ##now i want to enter this message from template sender = "XXXXXX" route = 4 # Prepare you post parameters values = { 'authkey' : authkey, 'mobiles' : mobiles, 'message' : message, 'sender' : sender, 'route' : route } print mobiles postdata = urllib.urlencode(values) # URL encoding the data here. req = urllib2.Request(url, postdata) response = urllib2.urlopen(req) output = response.read() print output now i want that message through enter from the template and my view have to get that message and send message to the members from db thanks -
Looking for tutorial for coding Continue Watching feature for videos
Context: I have a video streaming site like Netflix. Current Stack: Django, HTML5 video player, AWS -
Query from N:1 table to one
I am not really sure how should i do this but here for example i have model team and rider. So obviously team have many riders so FK is on Rider. class Team(models.Model): team_name = models.CharField(_('Team name'), max_length=100, db_index=True) bike = models.CharField(_('Bike'), max_length=100, db_index=True) slug = models.SlugField(_('Slug'), max_length=100) class Rider(models.Model): first_name = models.CharField(_('First name'), max_length=100, db_index=True) last_name = models.CharField(_('Last name'), max_length=100, db_index=True) number = models.IntegerField(_('Rider number')) team = models.ForeignKey(Team) Now in template i get all the teams and display them, but at the same time i would like to display riders per team so i use for loop to display team: {% for team in teams %} {% endfor %} Now how am i able to get riders per team since i cant pass any arguments in templates?