Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I deleted my db.sqlite from my project including the all migrations in app (except __init__.py)
I deleted db and all migrations for resetting my database. But after the deletion when I tried to run Makemigrations it is showing the error that OperationalError: no such table : student_app_grade I have an app named student_app And in that there is a model with name Grade -
passing a variable from a django view to a template javascript
I am using django-tables2 and have a LinkColumn whih is defined and rendered as follows: class DummyTable(tables.Table): edit = tables.LinkColumn('dummy_edit', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') def render_edit(self, record): # This line attempts to pass the primary key as a javascript function parameter #return mark_safe('<a href="" onclick="return EditDialog("' + str(record.pk) +'")">Edit</a>') return mark_safe('<a href="" onclick="return EditDialog()">Edit</a>') In the function, the commented out line tries to pass the primary key as a javascript function. The uncommented line invokes a function which does not take any parameters. My javascript function in the template is as: <script> function EditDialog(pk) { $( "#dialog" ).modal({width: 500, height: 500}); return false; } </script> Now, if I invoke it without any parameters (the uncommented line), it works fine. I see my dialog box and it is ok. However, if I use this invokation: return mark_safe('<a href="" onclick="return EditDialog("' + str(record.pk) +'")">Edit</a>') The dialog does not show up. Is it not possible to pass arguments this way in django or javascript? (I am new to both of them) -
Filtering distinct items with identical M2M relations in Django
I have created a few Django models to be used for registering games in a league. Somewhat simplified, this is what it looks like. class Participant(models.Model): first_name = models.CharField(u"First name", max_length=50) last_name = models.CharField(u"Last name", max_length=50) class Match(models.Model): players = models.ManyToManyField(Participant) I decided to relate the models via M2M as I wanted to easily query for games included a certain participant, which felt cumbersome if I had opted for using two fields with "player_one" and "player_two". This also makes the system somewhat flexible in terms of adding games with more than two participants. Anyway, some leagues will allow two players to face each other more than once, and it also allows for some free form scheduling meaning one player can play 20 games when another has only played 8. Q: How would I craft a query that lets me filter all matches containing only unique matchups? I. e. Jen has played 12 games, but three of those were vs Paul, and I only want to count one of those to get a list of all the unique opponents she's faced. -
Django - User upload CSV
I am very new to Django and am trying to, 1) give users the ability to upload CSV's to my site and store the files in memory, but have only come across examples where website admin can upload. 2) allows said users to upload a CSV with an unknown structure (i.e. I won't know the header names prior to upload) Does anyone have any example code I could use or documentation I could read please? -
django allauth signup skip email field in template but update it from session in view
I have a form where users can create a guest account which does not require them to signup up (they don't have to enter password). user's email is taken to create guest account and once it is created the email address is stored in the session. Now if a user makes a purchase they are then asked to create an account since we already have their email id we do not wish to ask for it again as a matter of we prefer they do not enter a separate email id. Using allauth signup form I only added password fields for the user to enter and am inserting email to the initial value. I am using FormMixin to achieve the same. However, in the post method I receive error "This field is required" for email. Can you please suggest as to the right approach to achieve this? -
Django Rest Framework Send verification email
Is there any way to send a verification email. when an user registers through drf (Django Rest framework). I have this code in my User model: from django.core.mail import send_mail from config import settings def email_user(self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs): send_mail(subject, message, from_email, [self.email], fail_silently=False, **kwargs) and in my settings.py: EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = '`132312123' EMAIL_HOST_USER = 'mimic@gmail.com' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER But email not being sent, also I want to verification email service, so user will be activated when they click on the link. How to accomplish these? -
Assert a function is not executed in Python unittest
I am using Django for my web development framework. And now I am writing unittest. How can I assert that a function is not executed in my test code? For example, this is the use case: My test code is testing a user is typing a wrong password while signing in. I want to make sure that reset password function is not executed in this use case. Well, this doesn't really reflect the real situation but I hope you get my point. -
Getting an 'Could not import Django error' after running manage.py runcrons in crontab (MacOs Sierra)
I'm using Django-Cron to schedule some database stuff. But after I edited my crontab like so */1 * * * * /Users/apple/Documents/Django/pricecompare/manage.py runcrons >> /Users/apple/Documents/Django/pricecompare/app/log.txt" I'm getting this error sent as "mail", ""Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"" I'm not using any virtual environment by the way. But when I run the same script directly in the terminal, I don't get any error. I can import django in the terminal as well. Any solutions? I'm using python 2. and I might have copied code that was supposed to be used in python 3, so I suspect that might be giving me the error -
Django - Create Custom Database Type
I have a table function in my database (postgresql), that returns a set of records of custom type. I want the results of this function to be mapped to a django model, like this: CustomType.objects.raw('SELECT * FROM my_table_function();'): I don't want to duplicate code for the custom type creation (and future updates) between django and postgresql, so for now I just have automatic django migrations create the table for CustomType and maintain changes to it. I refer to that table in my_table_function as the return type. All this works fine, but for every such function I end up with an empty table just to represent the data type. Is there a better way to do this? -
django.db.utils.IntegrityError: NOT NULL constraint failed: app_candidato.avaliacao_id
I am trying to create an form with django framework(python3), I make the the forms.py and the template (file.html) with the necessary settings,so when I try to make the view (views.py) and I run the application I received this error: django.db.utils.IntegrityError: NOT NULL constraint failed: app_candidato.avaliacao_id Well, I search about this error, before post my specific problem, here in stackoverflow and most of users with has this problem received them when try to migrate the db, about this I don't have any problems, is just when I try to access the link of form's page below my codes: urls.py: #from .models import Candidato from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.canditato_list, name='canditato_list'), url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidato_detalhe, name='candidato_detalhe'), url(r'^cadastrar/$', views.cadastrar, name='cadastrar'), # <--! o cadastro fica num link independete url(r'^candidato/[0-9]+/avaliacao/$', views.avaliar, name='avaliar'), ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Candidato, Criterio from django import forms from .forms import CandForm def canditato_list(request): candidatos = Candidato.objects.all() return render(request, 'app/candidato_list.html', {'candidatos': candidatos}) def candidato_detalhe(request, pk): candidato = get_object_or_404(Candidato, pk=pk) return render(request, 'app/candidato_detalhe.html', {'candidato': candidato}) def avaliar(request): criterios = Criterio.objects.all() return render(request, 'app/avaliacao.html', {'criterios': criterios}) def cadastrar(request): if request.method == "POST": form = CandForm(request.POST) if form.is_valid(): post = form.save(commit=False) … -
Django Translations in static page , static text
Hello I am currently Working on Simple Django Project . All HTML files are static How to translate in to local language marathi. In my last Ionic Project i write translations into ma.json or en.json file { "TITLE":"Krantiagrani Dr. G. D. Bapu lad CO-Oprative Sugar Factory Ltd., Kundal ", "MY INFORMATION": "My Information", "NEWS" : "News", "WEATHER" : "Weather", "ABOUTUS" : "About Us", "Vilage" : "Kundal", "State": "Maharashtra", "Country":"India", } like this in HTML file i just write { 'Country' | translate } there is any easy way to same thing do in Django in statc page translation share links with me -
Using or Q() objects in limit_choices_to
Django 1.10.5 def limit_contributor_choices(): limit = Q(group__name="contributor") | Q(group__name="Group") return limit author = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, limit_choices_to=limit_contributor_choices, verbose_name=_('Author'), on_delete=models.SET_NULL, related_name='author_pages', ) With the following code, if a user is in more than one group, then the query returns that user multiple times. How do I get distinct values? -
CSRF Token missing or incorrect even though i made sure i declare them in Js , HTML and views.py
Im pretty new to Django . And here is my views.py from my articles module. I've added the csrf token here in args dict. views.py , articles function def articles(request): language = 'UTC' session_language = 'en-us' if 'lang' in request.COOKIES: language = request.COOKIES['lang'] if 'lang' in request.session: session_language = request.session['lang'] args = {} args.update(csrf(request)) args['articles'] = Article.objects.all() args['language'] = language args['session_language'] = session_language return render_to_response('articles.html',args) This is my search section in the html page. Also made sure to add a csrf token here <h3>Search</h3> {% csrf_token %} <input type = "text" id = "search" name = "search" /> <ul id = "search-results"> </ul> {% endblock %} And here is the ajax.js File , $(function(){ $('#search').keyup(function() { $.ajax({ type: "POST", url: "/articles/search/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } here is my search_titles method for that /search/ url def search_titles(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text = '' articles = Article.objects.filter(title__contains=search_text) #means filter title where it contains searchtext AMAZING ! return render_to_response('ajax_search.html',{'articles':articles}) And finally here is the ajax_search.html {% if articles.count > 0 %} {% for article in articles %} <li> <a … -
Tasty pie manual save of related models without foreignkey
I have a model like this: ModelA(models.Model): name = CharField(...) slug = CharField(...) ModelB(models.Model): model_a_slug = models.CharField() So, here I am not using foreignkey for model_a_slug. Instead simply saving a unique field(dont ask me why we cant make it primary key etc, its a big story). So, we have to save it manually, so I tried override hydrate method but when I try to save in that, it is giving some transaction error saying you cannot save here. We can also override obj_update or obj_create method to save related models. But these methods wont be called as we are not calling url for resource of the model A. Instead we have a common api where we push all the data, so obj_update(or create) of that common resource will be called but not for modelAresource. Any solution for this ? -
iOS/Django: How to perform dual authentication?
I had created an API that I use to get processed data from a postgresql db in the form of json. I am able to authenticate the user via the api using the Django Rest Framework and get an authentication token for the same. Now in some pages of my app, I need to display pages in a webview from the web app. These pages require a csrf token in order to be accessed. The csrf token is generated on the submit button of the login on the web app. I can extract the csrf token from the cookies generated after login. So here's what I'm hoping to accomplish. Whenever I login from the login screen on my app, I want to programmatically create a webview in the background, fill in the login and password and tap the submit button in the web page. I will then proceed to extract the token from the cookies. Most of the parts I have down, I am not able to figure out how to programmatically fill in the webview and hit the submit button. (The reason I want to hit the submit button is because the view checks if the request is a … -
Django Monthly Grid / Table
I have a stock portfolio with monthly returns. Currently the returns are stored in the database as the first of each month, and the year. So January 1, 2016 - 5% February 1, 2016 - 3% What's the best way to display this in a Django template? I want to have each year in a separate row, and columns being the dates so: Jan Feb Mar Apr.... 2014 2015 2016 What's the best way to put the monthly returns into their correct position? Thanks for the help! -
Python multiprocessing not reducing processing time much
In my project i am implemented python multiprocessing in order to have a increase in processing speed.And i tested it in a 4 core system.But it shows only about 25 % reduction in processing time. Here is a sample code t1 = time.time() p = Pool() p.map(functin, file_list) p.close() p.join() print '===========================================================' print 'Pool put resume took := ',time.time() - t1 print '===========================================================' Theoratically there should be a 1\4th reduction in processing time since 4 cores are executing the function instead of single one.I also checked with task manager and confirmed that 4 process are running. So anyone please explain why it does not showing a significant reduction in processing time.Am i missing any configurations? -
Django. How to iterate over option with modelchoicefield
I need really help please, I am building an app where I am trying to iterate over options but it's not working as expected. Here's my models: MODELS = ( ('A', 'A'), ('B', 'B'), ) # Create your models here. class person(models.Model): nombre = models.CharField(max_length=128) model = models.CharField(max_length=128,choices=MODELS, default=True) def __str__(self): return self.nombre class person_A(models.Model): person = models.ForeignKey(person, on_delete=models.PROTECT, null=True) hobbies = models.CharField(max_length=40, default='') def __str__(self): return self.person.nombre class person_B(models.Model): person = models.ForeignKey(person, on_delete=models.PROTECT, null=True) age = models.IntegerField(default=10) def __str__(self): return self.person.nombre class person_a_car(models.Model): person = models.ForeignKey(person_A, on_delete=models.PROTECT, null=True) model = models.CharField(max_length=40, default='') class person_b_car(models.Model): person = models.ForeignKey(person_B, on_delete=models.PROTECT, null=True) models = models.CharField(max_length=40, default='') at this place I have 2 records, one for person_A called Person 1 and other for person_B called Person 2. Here's my forms: class personForm(forms.ModelForm): nombre = forms.CharField(label='Nombre') model = forms.ChoiceField(label='Tipo de protocolo',choices=MODELS,widget=forms.Select()) class Meta: model = person fields = ["model","nombre"] class person_aForm(forms.ModelForm): class Meta: model = person_A exclude = ('person',) fields = ["hobbies"] class person_bForm(forms.ModelForm): class Meta: model = person_B exclude = ('person',) fields = ["age"] class person_car_a(forms.ModelForm): class Meta: model = person_a_car fields =["model"] class person_car_b(forms.ModelForm): class Meta: model = person_b_car fields =["models"] class select_person(forms.Form): name = forms.ModelChoiceField(queryset=person.objects.all()) model = forms.ChoiceField(label='Tipo de protocolo',choices=MODELS,widget=forms.Select()) here's … -
Celery tasks.py only does one of many subprocesses in Django
My Django app's goal is to serve as a GUI for two Python programs. So besides the landing page, I have a form wherein after submitting, the tasks.py will be called. What my tasks.py does (overview): (1) The choices or options in the form will be replaced by arguments passed to the 1st program via if-else conditions. (2) Then these args will be passed to the first program. (3) After that, it will pass to the 2nd program. (4) This program needs the Virtualbox to be opened because it is a sandbox app. (5) I will also be adding args with the input depending on its type before analysis. Since the sandbox app, doesn't terminate by itself and just stops after Ctrl+C, I use subprocess.kill() after reading its stdout and stderr if it contains strings saying it is successfully processed. (6) In the end, I'll send a subprocess to turn off the Virtualbox. So far, here is an idea about my code: @shared_task(name='tasks.process_sample_input') def process_sample_input(instance_id): try: vm_open = subprocess.Popen(["VBoxManage", "startvm", "WindowsXP", "--type", "headless"]) args = list() args = fill_args(instance_id) #this contains the if conditions for the additional arguments #some codes here for the thug_logs as log files first_process = subprocess.call((args), … -
Dynamic select box inside a modal
Wondering if any one can help me with dynamic selectbox in django I am building out an app that let's me schedule event times. I currently have the option to select start_time by clicking on a button which launches a form in a modal. The start_time is pre_populated in this form with jquery. What I am looking for is to dynamically populate the the end_time field in this form... end_time options would be half hour slots from start_time to start of the next event or day close... which ever comes first. The issue i am stuck with is... how do i get all the possible end_time options after the start_time in the form? I don't know what the start_time is till the user selects it on the page but I do have a object list of all the events coming through when the page first loads -
How to do live streaming from raspberry pi camera into django
I have a django server. Now I need to do live streaming from raspberry pi camera on that web site. Say I have an app named rasp_ main. In the views.py of rasp_main i need to pass some parameter to the template(.html file) and i believe that's going to be the jpeg frames which constantly needs to be updated. I need to do it specifically in django. So if anyone has done it, please provide me the code. THANK YOU.. -
File upload with CKEditor and Django
I am having trouble with implementing image upload in DJango and CKEditor. Here is my code: models.py from django.db import models from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class post(models.Model): title = models.CharField(max_length=100) # body = RichTextField() body = RichTextUploadingField('body') date = models.DateTimeField() image = models.ImageField(upload_to = 'posts/%Y/%m/%d', null=True, blank=True) def __str__(self): return self.title urls.py: from django.conf.urls import url, include from posts.models import post from posts import views from django.conf.urls.static import static from django.conf import settings app_name = 'posts' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^ckeditor_uploader/', include('ckeditor_uploader.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) Whenever I access Post in Admin, I get this error: NoReverseMatch at /admin/posts/post/13/change/ Reverse for 'ckeditor_upload' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] It seems like an URL error but I am not sure what went wrong. -
django registering models with many-to-many circular reference on Admin
This is how my models looks like: class GameStates(models.Model): state_code = models.CharField(max_length=20) state_name = models.CharField(max_length=100) order = models.IntegerField() allowed_states = models.ManyToManyField('GameStates', related_name='allowed_states_admin') def __str__(self): return self.state_code allowed_states has a many-to-many circular reference with GameStates. This field contains following information: Given a current state that the user is in, what are the other states that he is allowed to go. I am trying to register this model on Admin as follows: class GameStatesInline(admin.TabularInline): model = GameStates.allowed_states.through @admin.register(GameStates) class GameStatesAdmin(admin.ModelAdmin): inlines = [GameStatesInline] exclude = ('allowed_states',) However, I keep getting the following error message: GameStates_allowed_states' has more than one ForeignKey to 'GameStates'. -
Connection Error After Restarting Working Heroku Django App Behind Gunicorn?
We restarted our django app nothing seemed to change but now with every connection we're getting the following error. What does it mean? How can I fix it. I've spent all day trying everything I can think of. Any help would be greatly appreciated. 2 Mar 2017 19:38:52.529 167 <190>1 2017-03-03T01:38:52.278764+00:00 app web.1 - - [2017-03-02 19:38:52 +0000] [11] [ERROR] Socket error processing request. » 2 Mar 2017 19:38:52.529 128 <190>1 2017-03-03T01:38:52.278767+00:00 app web.1 - - Traceback (most recent call last): File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 93, in handle self.handle_request(listener, req, client, addr) File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 150, in handle_request six.reraise(exc_info[0], exc_info[1], exc_info[2]) File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 134, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/app/.heroku/python/lib/python2.7/site-packages/dj_static.py", line 83, in __call__ return self.application(environ, start_response) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 256, in handle_uncaught_exception 'request': request File "/app/.heroku/python/lib/python2.7/logging/__init__.py", line 1185, in error self._log(ERROR, msg, args, **kwargs) File "/app/.heroku/python/lib/python2.7/logging/__init__.py", line 1278, in _log self.handle(record) File "/app/.heroku/python/lib/python2.7/logging/__init__.py", line 1288, in handle self.callHandlers(record) File "/app/.heroku/python/lib/python2.7/logging/__init__.py", line 1328, in callHandlers hdlr.handle(record) File "/app/.heroku/python/lib/python2.7/logging/__init__.py", line 751, in handle self.emit(record) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/log.py", line 129, in emit self.send_mail(subject, message, fail_silently=True, html_message=html_message) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/log.py", line 132, in … -
Getting a "The SECRET_KEY setting must not be empty" error when I try to use AWS S3BotoStorage
I'm trying to follow this tutorial to store my media and static files using an AWS S3 bucket: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ Before mentioning my problem, I'll point out that I believe the issue is because of a "circulatory import" problem, as discussed here: Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty But I can't seem to figure out exactly how to fix it. This is my settings.py: import os from ebdjango.custom_storages import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secretkey%4!' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'ebdjangoapp', 'storages', ) AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_ACCESS_KEY_ID = 'SECRETKEYID' AWS_SECRET_ACCESS_KEY = 'SECRETACCESSKEY' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'ebdjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ebdjango.wsgi.application' DATABASES = { 'default': { 'ENGINE': …