Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send large number of files to back end Django
I have a requirement that i need to upload large number of files using <input type="file" ng-file-model="files" id="id_docfile" multiple> and after that it should be sent to the django backend side more efficently.I am also using angularjs for the front end.I am familiar with 2 options 1.Using django forms 2.Send files to backend using angular ajax request($http) Can i implement any kind of threading mechanism for this? Can anyone suggest a best option for this?Please keep in mind that a case of even 1000 files upload. -
How to cleanup postgres temporary tables of recursive query from django/psycopg2
When postgres run recursve query it creates temporary table for it. After query is finished, the temporary table remains on disk, until whole program competes. The program consist of main process and multiprocessing pool of workers, all with separate db connections (and I cannot close connection of main process because it holds iterating data source). Queries are executed in following way: def process_datum(datum): with db.connections['world'].cursor() as cursor: cursor.execute("SELECT ... from query_function(%s)", (datum.id,)) rows = cursor.fetchall() for row in rows: try: ... A_Model.objects.create(...) except db.IntegrityError as e: logger.warning("%s: %s", path, e) The process_datum is called from worker, the query_function is database-side table function implementing recursive query. -
PIP install shows syntax error when specified version
When tried to install any dependency with specific version using PIP I am getting following error: (myvenv) D:\Project\on-staging>pip install Fabric==1.4.3 Collecting Fabric==1.4.3 Using cached Fabric-1.4.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Admin\AppData\Local\Temp\pip-build-39la41_8\Fabric\setup.py", line 7, in <module> from fabric.version import get_version File "C:\Users\Admin\AppData\Local\Temp\pip-build-39la41_8\Fabric\fabric\version.py", line 104 print get_version('all') ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Admin\AppData\Local\Temp\pip-build-39la41_8\Fabric\ Doing pip install Fabric works fine though. -
How to pass both ListView and DetailView as parameters in views.py/urls.py?
I want to show NEXT POST and PREVIOUS POST titles under the current article. Until now I had been passing DetailView object from urls.py as : urls.py url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name = 'blog/post.html')), In post.html, I am using post object to get the title and the body of the post. <h2> {{post.title}} </h2> <p> {{post.body|safe|linebreaks}} </p> But then I realised I cannot get the list of posts to display it. So I modified urls.py to redirect to views.py which included urls.py url(r'^(?P<pk>\d+)$', views.post_details) views.py post_details (request,pk): return render(request, 'blog/post.html',{'message' : [Post.objects.all(),DetailView.as_view(model = Post)]}) Now when I tried using the dictionary in post.html, I am not getting any output. How do I pass both DetailView and ListView as parameters to post.html and how do I extract it? -
Foreign Key based dropdowns show same value in Django
Background: I'm building a Django forms based application. The form has dropdowns for which the values comes from another table(model). I read somewhere that using foreign key you can make dynamic dropdowns for which the value comes from the source table. Problem: All the dropdowns show same value. For example: If I put values in national, aetna, kaiser, bcbs,tufts as A,B,C,D,E then in all the dropdowns rendered on webpage , there is B as the option while it should have been A for first dropdown, B for second and so on. Why is this happening? Code: models.py: Model 1 from which data would be shown: class RiskBand(models.Model): """Model to store Risk band data""" national = models.CharField( 'National Risk Band', max_length=50, null=True, unique=True # Required attribute for it to be used as FK ) aetna = models.CharField( 'Aetna Risk Band', max_length=50, null=True, unique=True ) kaiser = models.CharField( 'Kaiser Risk Band', max_length=50, unique=True ) bcbs = models.CharField( 'BCBS Risk Band', max_length=50, unique=True ) tufts = models.CharField( 'TUFTS Risk Band', max_length=50, unique=True ) def __str__(self): return self.aetna Model 2 where data would be shown: class ClientRiskBand(TimeStampedModel): """Model to store Risk bands for a client set by an underwriter""" YEAR_CHOICES = [(r, r) for … -
How to redirect after signing up in django all auth?
I am signing up using django allauth but after signup it automatically redirect to user's profile page but insted of that i want to redirect user to confirmation email sent page...can any one help me to do so -
Django Noreversematch error
I have been following a simpleisbeterthancomplex.com tutorial on making a CRUD using jquery and django. I am fairly new to both of these things and so far this is the first problem I have run into that I just cannot figure out what is going on. After drowning in the deep end I am asking for a lifeline. My view.py looks like: def question_list(request, quiz_id): questions = Question.objects.filter(inquiz_id=quiz_id) return render(request, 'quiz/list_questions.html', {'questions': questions, 'quiz_id': quiz_id}) My urls.py: url(r'^quizquestions/(?P<quiz_id>[0-9]+)/$', quiz_views.question_list, name='question-list'), And my list_questions.html <button type="button" class="btn btn-primary js-create-question" data-url="{% url 'question-list' id=quiz.id %}"> <span class="glyphicon glyphicon-plus"></span> New MC-Question </button> -
How to render HTML in string with Javascript?
I have the following javascript code: var html = '<div class="col-lg-4 col-references" idreference="'+response+'"><span class="optionsRefer"><i class="glyphicon glyphicon-remove delRefer" style="color:red; cursor:pointer;" data-toggle="modal" data-target="#modalDel"></i><i class="glyphicon glyphicon-pencil editRefer" data-toggle="modal" data-target="#modalRefer" style="cursor:pointer;"></i></span><div id="contentRefer'+response+'">'+refer_summary+'</div><span id="nameRefer'+response+'">'+refer_name+'</span></div>'; $("#references").append(html); When this code runs, the refer_summary variable actually contains a string which may contain HTML tags such as <b>, <i> etc., however, those tags are displayed on the page instead of rendering their behavior. For example, on the page it would show <b> rather actually making the content bold. How can I go about rendering the HTML tags when the value is appended? In my Django template I use {% autoescape off %}{{content}}{% endautoescape %} so when I first load the page, the content is rendered correctly with bold etc. But how can I do the same thing when appending the html from javascript? Thanks for the help! -
Django Scheduler integration
I have seen this and this was asked earlier. Using the Django scheduler app with your own models and how to install django-scheduler in my project. I am getting an error saying module cannot be imported However, this really did not solve my purpose. This is my current model: class annual_calender(models.Model): start_date=models.DateTimeField(db_index=True) end_date=models.DateTimeField(db_index=True) event=models.CharField(max_length=20) event_type=models.CharField('Event type', max_length=1,choices=event_type, default='H') #key=models.CharField(db_index=True,max_length=10) slug=models.SlugField(db_index=True, max_length=75) tenant=models.ForeignKey(Tenant,db_index=True,related_name='annualCalender_genadmin_user_tenant') objects=TenantManager() # def get_absolute_url(self): # return reverse('master:detail', kwargs={'detail':self.slug}) def save(self, *args, **kwargs): if not self.id: toslug=self.tenant.key+" " +self.event+" "+str(self.start_date) self.slug=slugify(toslug) super(annual_calender, self).save(*args, **kwargs) class Meta: unique_together = (("slug", "tenant")) # ordering = ('name',) def __str__(self): return '%s: %s-%s' % (self.event, self.start_date, self.end_date) I want to integrate django scheduler: https://github.com/llazzaro/django-scheduler However, I couldn't find how my model has to change and what should my views be? Currently, I'm using fullcalendar in the front-end; my aim is to use scheduler to help/improve the db design and implement rules. Hence, it would be really helpful if a brief on the steps to be taken to store events and display the same are shown here. Thanks. -
How to keep a shared functional object in memory in Django?
I have an object that wraps some Active Directory functions which are used quite frequently in my codebase. I have a convenience function to create it, but each time it is creating an SSL connection which is slow and inefficient. The way I can improve this in some places is to pass it to functions in a loop but this is not always convenient. The class is state-free so it's thread-safe and could be shared within each Django instance. It should maintain its AD connection for at least a few minutes, and ideally not longer than an hour. There are also other non-AD objects I would like to do the same with. I have used the various cache types, including in-memory, is it appropriate to use these for functional objects? I thought they were only meant for (serializable) data. Thanks, Joel -
Django and extending templates not working?
I am using Django to build my blog site and i am unable to extand a template in my project. I have two templates: base.html post.html Base.html is my parent template and post.html is my child template extending base.html. I am unable to get Django to extend post.html. When i run the web server base.html displays but there is not text from post.html on it. I have read the Django documentation on templates and how to extend, i believe i have to syntax correct, but i am not sure why its not working? I am also using Boostrap with this project. Thank you for your help, Nermin post.html {% extends "post/base.html" %} {% block content %} <div class="blog-post"> <h2 class="blog-post-title">Sample blog post</h2> <p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p> <p>Blog text goes here.</p> </div><!-- /.blog-post --> {% endblock %} enter code here base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <!-- load static files --> {% load staticfiles %} <title>Blog Title</title> <!-- … -
use success_url to go to root directory after submit form
I have a simple class based view (in an app video) that is creating an object using a form in a template (upload_video.html). When I submit the form, I just want to redirect to the home page, or the root index. It seems like this should be so easy. I am getting an error saying there is no page. I have tried several different ways of doing this, the code i have below is just one example. views.py class UploadVideo(CreateView): model = Video fields = ['title', 'description'] template_name = 'upload_video.html' success_url = reverse_lazy('index.html') upload_video.html <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload Video"/> </form> </body> </html> root.urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^video/', include('video.urls')) Error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/video/index.html Using the URLconf defined in flash2.urls, Django tried these URL patterns, in this order: ^admin/ ^$ ^video/ ^upload [name='upload'] The current URL, video/index.html, didn't match any of these. -
django-extra-views and nested formsets
I would like to make use of a nested inline formset using django-extra-views for both create and update. I can implement a typical (non-nested) inline formset without issue. Here is a basic example of that. # forms.py class ProductForm(forms.ModelForm): class Meta: model = models.Product # for brevity, assume these fields are defined on the `Product` model fields = [ 'name', 'image', 'price', ] class VariantForm(forms.ModelForm): class Meta: model = models.Variant # for brevity, assume these fields are defined on the `Variant` model fields = [ 'price_override', 'shipping_dimensions', ] class InlineVariant(InlineFormSet): model = models.Variant form_class = VariantForm extra = 1 And # views.py class Add(CreateWithInlinesView): template_name = "products/add.html" model = models.Product form_class = forms.ProductForm inlines = [ forms.InlineVariant, ] class Edit(UpdateWithInlinesView): template_name = "products/edit.html" model = models.Product form_class = forms.ProductForm context_object_name = "product" inlines = [ forms.InlineVariant, ] But, now I want Stock to be inline for each Variant. # forms.py class StockForm(forms.ModelForm): class Meta: model = models.Stock # for brevity, assume these fields are defined on the `Stock` model fields = [ 'location', 'quantity', ] class InlineStock(InlineFormSet): model = models.Stock form_class = StockForm extra = 1 How could the views defined above be modified? There is an existing django-extra-views issue … -
Django evaluate string vs array
I am sometimes getting passed a string and sometimes getting an array and trying to figure go about displaying them. For example if string { handle string } if array { handle array } what I have come up with is the following which almost works. The problem is slicing a string just returns a character and slicing an array returns a string so I cant make any kind of comparison. Is there a way to check if something is a string vs an array? I didn't see this capability anywhere in the documentation. Is it just this primitive? {% if person|lookup:'items'|slice:":1"|length > 1 %} {{ person|lookup:'items' }}{% else %} {{ i }} {% endif %} -
how to create django edit test and update test
I have views.py like this and than how to create edit test and update test?? i want edit and update can do it by id from django.shortcuts import render, redirect from .models import People def index(request): peoples = People.objects.all() context = {'peoples': peoples} return render(request, 'people_app/index.html', context) def create(request): print(request.POST) people_app = People(name=request.POST['name'], biography=request.POST['biography']) people_app.save() return redirect('/') def edit(request, id): people = People.objects.get(id=id) context = {'people': people} return render(request, 'people_app/edit.html', context) def update(request, id): people = People.objects.get(id=id) people.name = request.POST['name'] people.biography = request.POST['biography'] people.save() return redirect('/') def destroy(request, id): people = People.objects.get(id=id) people.delete() return redirect('/') -
How to configure Stripe Connect on Django to collect fees on transactions?
After several research I've come to a conclusion that Stripe Connect documentation on Django wasn't really furnished. I've been struggling to create a simple marketplace using the Standalone Package (OAuth). The goal of the plateforme is to let users do transactions between each other and collect fees on each charges. To achieve this I'm using django-allauth and stripe. I've set up django-allauth so users can already create an account on stripe and login on my website. The problem I'm facing now is on how to charge users between each other. Here is the error I get when I'm trying to make a payment from two different accounts, UserA (customer) to UserB (publisher/seller) : stripe.error.InvalidRequestError: Request req_*************: The 'destination' param cannot be set to your own account. Here is my views customer_id = request.user.profile.stripe_id if request.method == 'POST': try: gig = Gig.objects.get(id=request.POST.get('gig_id')) except Gig.DoesNotExist: return redirect('/') token = request.POST['stripeToken'] # Create a charge: this will charge the user's card try: customer = stripe.Customer.retrieve(customer_id) customer.sources.create(source=token) destination_id = gig.user.socialaccount_set.get().uid charge = stripe.Charge.create( amount=5000, # Amount in cents currency="chf", customer=customer, description=gig.title, application_fee=123, destination=destination_id, #'acct_**************' ) except stripe.error.CardError as e: # The card has been declined pass Gig is my product model and Profile is … -
Django, abstract base class without autofield?
I'd like to define a new _id autofield in one of the derived classes. Simply specifying _id field for the derived class results in an error " A model can't have more than one AutoField." class Base(models.Model): class Meta: abstract = True class Derived(Base): _id = models.AutoField(primary_key=True) -
How can I add description of my website (How can I show page description when linked in facebook)?
I have a django application and about to deploy. But when I link my site, it shows like this: No description at all! How can I add site description? -
Django Form Input Validation
I have an input form defined as follows. class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'language', ] widgets = { 'language': forms.RadioSelect, } Inside my models.py I define the following: first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) LANGUAGE = (('AR', 'Arabic'), ('FR', 'French'), ('ES', 'Spanish')) language = models.CharField(max_length=20, choices=LANGUAGE, blank=False, default=None) The first_name and last_name are required fields, and if the user leaves these two options empty, a warning message will prompt. However, I also want the language field to be a required field. To do so, I set blank=False. While it is correct that if you submit the form without selecting an option for language, the form will be invalid. However, it does not give the user a warning about it. How can this be done? -
How do i import list of variables as choices for a charfield from outside the app?
I'm trying to make a select box in the admin that shows a list of objects in the database, outside the current app. Here is my model from typefaces.models import Typeface class Word(models.Model): text = models.CharField(max_length=200) family_select = models.CharField(max_length=100, choices=Typeface.objects.all) Unfortunately, Django tells me 'choices' must be an iterable (e.g., a list or tuple). But my attemps to make it iterable with iter() have yielded no success. -
Get email in django template
Does django have a 'user.get_email' similar to how it has 'user.get_username' for templates? Or do we have to create this as a custom function? -
Google App Engine Django Standard Environment: Error: Server Error
I am trying to deploy the most simple Django 1.10.5 project into Google App Engine and am completely stumped. Upon running gcloud app deploy I am getting the following error when navigating to /... This is the file structure of my app... This is my .yaml file... This is my appengine_config.py file... I am also getting the following errors in Google Dev Tools network tab... I am pretty certain the problem lies within my app.yaml file and am very unclear as to what url and handler are doing in this code. Can anyone see what I am doing wrong or throw me a bone? -
Special character (utf-8) in a django jsonresponse
Im using json response in django, but I have special characters (ñáé etc...) my view def get_agencies(request): qr = Agency.objects.all() qr_jason = serializers.serialize('json',qr) return JsonResponse(qr_jason, safe=False) But if I enter a special character like ñ in the json I recieve the ascii equivalent. Actually I can make a dictionary and then make the JasonResponse with the dictionary and it works, I can't find a way to use the serializers.serialize with utf-8. json recieved (the u00f1 are ñ) // 20170124165944 // http://localhost:8080/get_agencies/ "[ { \"model\": \"items.agency\", \"pk\": 1, \"fields\": { \"name\": \"asdk\\u00f1ld\", \"tipo\": \"librevile\", \"adress\": \"laslkfdli323, ls\\u00f1\\u00f1\", \"phone\": \"56549875\", \"web\": \"http: //www.systmatic.com.mx\", \"lat\": 23.514646, \"lng\": -26.152684, \"created\": \"2017-01-24T00: 56: 28.302Z\", \"last_updated\": \"2017-01-24T22: 22: 08.856Z\" } } ]" -
Django ContentType Error while submitting data from front-end. (quiz app)
i am working on a quiz app, which i have been able to create quizzes, questions and answer from the backend.(using Django/Python). but i am having issues creating the questions from the front-end. i guess the issue is coming from the Django ContentType framework, probably i am not doing something right. whenever i try to save questions it pops up error TypeError at /quiz/create/1/tf/ 'NoneType' object is not callable below is a snippet of the view.py class CreateQuestionView(TemplateView): template_name = 'quiz/create_question.html' def get_form(self): """Determines the form that should be used""" if self.kwargs.get('que_type') == 'mc': return MultiChoiceQuestionForm, MultipleAnswerFormSet, MultipleChoiceType else: return TrueFalseQuestionForm, TrueFalseAnswerForm, TrueFalseType def post(self, request, *args, **kwargs): que_form_class, ans_form_class, que_type_class = self.get_form() que_form = que_form_class(request.POST) ans_form = ans_form_class(request.POST) que_choice = que_type_class(request.POST) if que_form.is_valid() and ans_form.is_valid(): quiz_data = get_object_or_404(Quiz, pk=self.kwargs.get('quiz_id')) question = que_form.save(commit=False) question.quiz = quiz_data answers = ans_form.save(commit=False) que_choice = que_choice.save(commit=False) # Any other thing we need to do que_choice.save() que_choice_ct = ContentType.objects.get_for_model(que_choice) print(que_choice.id) if que_choice.choice == 'multiplechoice': for answer in answers: answer.question = que_choice print('multipeChoice') elif que_choice.choice == 'truefalse': answers.question = que_choice # import pdb; pdb.set_trace() print('truefasle') # import pdb; pdb.set_trace() else: print('do not tamper with the form') # import pdb; pdb.set_trace() Question(content_object=que_choice) #return redirect('index') # the form … -
"ImportError: The Python Imaging Library was not found." raised through wsgi.py in Django app using Apache
I am working on a project using Django and am trying to connect it to my Apache server. Here is the traceback for the error I am getting: mod_wsgi (pid=3325): Target WSGI script '/var/www/Project/project/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=3325): Exception occurred processing WSGI script '/var/www/Project/project/wsgi.py'. Traceback (most recent call last): File "/var/www/Project/project/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/var/www/Project/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/var/www/Project/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/Project/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/var/www/Project/venv/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/Project/venv/lib/python2.7/site-packages/filer/models/__init__.py", line 3, in <module> from .clipboardmodels import * # flake8: noqa File "/var/www/Project/venv/lib/python2.7/site-packages/filer/models/clipboardmodels.py", line 9, in <module> from . import filemodels File "/var/www/Project/venv/lib/python2.7/site-packages/filer/models/filemodels.py", line 14, in <module> from . import mixins File "/var/www/Project/venv/lib/python2.7/site-packages/filer/models/mixins.py", line 7, in <module> from ..settings import FILER_ADMIN_ICON_SIZES File "/var/www/Project/venv/lib/python2.7/site-packages/filer/settings.py", line 11, in <module> from .utils.loader import load_object File "/var/www/Project/venv/lib/python2.7/site-packages/filer/utils/loader.py", line 15, in <module> from .compatibility import import_module File "/var/www/Project/venv/lib/python2.7/site-packages/filer/utils/compatibility.py", line 95, in <module> raise ImportError("The Python Imaging Library was not found.") ImportError: The Python Imaging Library was not found. Here is my config file: WSGIPythonPath /var/www/Project:/var/www/Project/venv/lib/python2.7/site-packages WSGIScriptAlias / /var/www/Project/project/wsgi.py <Directory /var/www/Project/project> <Files wsgi.py> Require all …