Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django set global variable in template
I'm using a banner image that needs to change on each page, i would to set the banner in the html template, so that it is easy for person i building it for easily can add new pages. im developing it in django, but i can't figure out how to get it to work, please help! example: index.html set image url here {% extends 'base.html' %} base.html <html> <body> {% include 'top.html %} </body> </html> top.html <div> <img src="{{ image url }}"> </div> kind regards c_bb -
Save multiple files using FileField
In a existing form I use a FileField to attach differents type of files .txt, .pdf, .png, .jpg, etc and work fine but now I need that field to accept several files, so I use the propertie multiple for the input to accept more of one files but when is stored in my database only stored the path for the first selected file and in the media folder are only stored one file no the others, this is what I have: forms.py class MyForm(forms.Form): attachment = forms.FileField(required=False,widget=forms.ClearableFileInput(attrs={'multiple': True})) models.py class MyFormModel(models.Model): attachment = models.FileField(upload_to='path/', blank=True) Is posible to store in the DB all the paths separete in this way path/file1.txt,path/file2.jpg,path/file3.pdf and store the three files in the media folder? Do I need a custom FileField to procces this or the view is where I need to handle this? -
displaying other attribute values if one is known in django template
i have this app in django that i'm trying to make. this is the index.html page <html> <head> <title>The index page</title> </head> <body> <h1>Choose the name of student</h1> <form action= "{% url 'detail' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <select name="namedrop"> {% for name in student_list %} <option value={{name.stuname}}>{{name.stuname}}</option> {% endfor %} </select> <input type="submit" name="submit"> </form> </body> </html> and this is the detail.html page to which it is directed when we select a name and click submit button... <!DOCTYPE html> <html> <head> <title>Details of student </title> </head> <body> <p>hello {{name}}</p> <style type="text/css"> p { color: blue; } </style> </body> </html> but it only shows "hello neha" if the name selected is "neha"... but i want it to print all the details of this student from the table student...this is models.py... from django.db import models class course(models.Model): cid=models.IntegerField(unique=True,default=0) cname=models.CharField(max_length=50) def __unicode__(self): return self.cname class Meta: db_table= "course" class student(models.Model): stuid=models.IntegerField(default=0) stuname=models.CharField(max_length=50) cid=models.ForeignKey(course,to_field='cid',on_delete=models.CASCADE) def __unicode__(self): return self.stuname class Meta: db_table= "student" class subject(models.Model): sid=models.IntegerField(default=0) sub=models.CharField(max_length=50) cid=models.ForeignKey(course,to_field='cid',on_delete=models.CASCADE) class Meta: db_table= "subject" def __unicode__(self): return self.sub this is views.py from .models import student from django.http import Http404 from django.shortcuts import render from django.template import loader from django.http import HttpResponse def index(request): student_list=student.objects.all() template … -
Can't get form errors when using crispy forms
I' m using django-crispy-forms forms third part library in a Django project, I would to customize a form and I would to get the errors at top of the form, but I can't. This is a snippet of the code: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="col-sm-6"> <h1>Add New Task</h1> <form action="" method="post">{% csrf_token %} <div class="row"> <div class="col-sm-12">{{ form|as_crispy_errors:"bootstrap3" }}</div> <div class="col-sm-10">{{ form.project|as_crispy_field }}</div> <div class="col-sm-2" id="add-new"> <a href="{% url 'pomodoro:new-project' %}">Add new</a> </div> </div> <div class="row"> <div class="col-sm-12">{{ form.title|as_crispy_field }}</div> </div> <button class="btn btn-primary" type="submit">Add</button> </form> </div> {% endblock content %} -
Loading CSS returns 404 using django
I am building a chatbot application. The CSS for the frontend is not getting loaded by using django's static data load. path to css is - C:\Documents\Django_Workspace\bot\templates\static\bot.css path to html is - C:\Documents\Django_Workspace\bot\templates\index.html I have added STATIC_URL in my settings file as STATIC_URL = '/static/' The HTML link tag looks like {% load static %} <head> <meta charset="UTF-8"> <title>bot</title> <link rel="stylesheet" type="text/css" href="{% static "bot.css" %}" /> </head> My Urls.py looks like from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] This is how I render the html page from django.http import HttpResponse from django.template import loader from .models import User_Message def index(request): template = loader.get_template('index.html') return HttpResponse(template.render()) Can anyone help. I've even tried hardcoding the path of css file in the html tag. But, that's not working -
How do I change the display data from float to percentage in a Django scatter plot?
My data is passed to the chart in float form. I was wondering how I could display the chart data in percentage form. I researched online and try to update the label format, however, it didn't work. nv.addGraph(function() { var labelTypes = { "key" : getX(d.data), "value": getY(d.data), "percent": d3.format('%')(percent), "percent2digits": d3.format('.2%')(percent) }; } -
How to iterate over each user in database django tempting language
When you sign up for the site I am in the process of building, you pick whether you want to be a 'user' or a 'worker' and enter your location. For the workers, I want to display all the people trying to use the service('user') in the same location as the worker. I have the following model: models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) ROLE = ( ('USER', 'User'), # (value to be set on model, human readable value) ('WORKER', 'Worker'), ) role = models.CharField(max_length = 7, choices = ROLE, default = 'USER') def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I also have a form with matching fields and it works fine, everything saves correctly. forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') location = forms.CharField() ROLE = ( ('USER', 'User'), # (value to be set on model, human readable value) ('WORKER', 'Worker'), ) role = forms.ChoiceField(choices=ROLE, required = True) … -
How to integrate Django model and form with my view
How can I integrate my html to my form and model so that it can process the backend. In admin page, everything works fine but I'm unable to integrate it with my frontend. This is my models.py from django.db import models class SignUp(models.Model): name = models.CharField(max_length=120, blank=True, null=True) email = models.EmailField() timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.email This is my forms.py from django import forms from .models import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['name', 'email'] def clean_name(self): name = self.cleaned_data.get('name') return name def clean_email(self): email = self.cleaned_data.get('email') try: match = SignUp.objects.get(email=email) except SignUp.DoesNotExist: return email raise forms.ValidationError('This email address is already subscribed.') This is my view.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import SignUpForm def signUp(request): form = SignUpForm(request.POST or None) if form.is_valid(): name = form.clean_name() email = form.clean_email() instance = form.save() subject = 'Bruke Church news' from_email = settings.EMAIL_HOST_USER to_email = [email] contact_message = "%s:Thank you for signing up for our newsletter via %s. we'll be in touch" %( name, email) send_mail (subject, contact_message, from_email, to_email, fail_silently=False) context = { "form": form } return render(request, "signUp.html",context) This is my html … -
Error when closing master process - Multiprocessing
I have a real simple django app that I run using gunicorn. But in the sitecustomize(which runs before gunicorn) I use multiprocessing to start a daemon process. m_process = Process(name='side-process', target=side.start_proc) m_process.daemon = True m.start() The function start_proc does the following while True: print 'Hello' time.sleep(300) Thats all I do. But when I ctrl-c on the terminal/console I get a huge error trace. This is for gunicorn running with one worker. The trace gets bigger as the number of workers increase. ^CProcess side-process: Traceback (most recent call last): File "/usr/lib64/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib64/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python2.7/site-packages/python_agent/agent.py", line 63, in start_agent [2017-08-15 09:21:30 +0000] [78582] [INFO] Handling signal: int time.sleep(300) KeyboardInterrupt [2017-08-15 16:21:30 +0000] [78597] [INFO] Worker exiting (pid: 78597) Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib64/python2.7/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib64/python2.7/multiprocessing/util.py", line 315, in _exit_function p._popen.terminate() File "/usr/lib64/python2.7/multiprocessing/forking.py", line 171, in terminate os.kill(self.pid, signal.SIGTERM) OSError: [Errno 3] No such process Error in sys.exitfunc: Traceback (most recent call last): File "/usr/lib64/python2.7/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib64/python2.7/multiprocessing/util.py", line 315, in _exit_function p._popen.terminate() File "/usr/lib64/python2.7/multiprocessing/forking.py", line 171, in terminate os.kill(self.pid, signal.SIGTERM) OSError: [Errno 3] No … -
MultiValueDictKeyError in django detail view
i am making an app in django. this is my index.html page. <!DOCTYPE html> <html> <head> <title>The index page</title> </head> <body> <h1>Choose the name of student</h1> <form action= "{% url 'detail' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <select name="namedrop"> {% for name in student_list %} <option>{{name.stuname}}</option> {% endfor %} </select> <input type="submit" name="submit"> </form> </body> </html> this is my studinfo/urls.py from django.conf.urls import url from . import views from .models import student urlpatterns= [ url(r'^$',views.index ,name='index'), url(r'^detail/$',views.detail ,name='detail'), ] and this is views.py from .models import student from django.http import Http404 from django.shortcuts import render from django.template import loader from django.http import HttpResponse def index(request): student_list=student.objects.all() template = loader.get_template('studinfo/index.html') context= { 'student_list' : student_list, } return HttpResponse(template.render(context, request)) def detail(request): if request.method=='POST': name=request.GET['namedrop'] return render(request, 'detail.html', {'name':name}) now it is raising an error MultiValueDictKeyError at /studinfo/detail/ "'namedrop'" i have no idea why...let me know if anybody knows it. -
Add Facebook share button to Django application
I am using Facebook's share button on my Django app. I'm using Facebook's SKD instructions which tell me to place this code wherever you want the plugin to appear on your page: <div class="fb-share-button" data-href="https://my-website-full-url" data-layout="button" data-size="small" data-mobile-iframe="false"> <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&amp;src=sdkpreparse">Share </a> </div> So I placed that code in my template but how do I add the full URL of the web page with the FB share button in the data-href attribute? -
Django Microseconds Attribute Error
I am currently trying to load data from an MSSQL server. However in my models I have a couple of fields that have microseconds i.e. "2017-08-14 05:47:16.000". This causes me to get an error "Attribute Error at/ microseconds". I would like to know if anyone has encountered a similar issue and found a solution to this. Thanks -
Django-CKeditor: How to show RichTextFields in templates
The problem is that I want to show the content of a Post in the template but I don't know how The model of Post is: from ckeditor.fields import RichTextField class Post(models.Model): ... content = RichTextField(verbose_name='contenido') ... And in the template I have a for to show all the post that is like this: {% for post in posts %} ... {{ post.content }} ... {% endfor %} But when I see the page in the browser shows this: < p > Post content < /p > Instead of this: Post content -
Deleting records from backups in Postgres
I am working on a web application that will serve the legal industry. It has an odd requirement to allow users to delete information permanently EVERYWHERE. I'm planning to use a hosted DB like Heroku PG or Database Labs. I'm not sure how best to implement this feature such that records are deleted from backups as well as from the live db. Any ideas? Ty. -
Reason for update/delete field in django
I am trying to create a simple app that forces the user to enter a reason for update or delete when they are editing an existing model through a form. I have created the model and the associated form. The part of the model that asks for the update summary works fine, but when it appears, it obviously always has the last update that was entered for the model as part of the update view. Is there some way I can "blank out" the update summary every time? I am also trying to create a history of each form and I'm still in the early stages of that. I see that there are several options available, but I'm still exploring those. I'm a newbie, so any help you can offer is appreciated! Here is a copy of my current model: class Pizza(models.Model): pizza_name = models.CharField(max_length=264,unique=True) customer = models.TextField(max_length=264,unique=True) update_summary = models.TextField(max_length=264,unique=True,null=True) I have explored possible using Javascript to blank out the form in the update view but can't seem to get that to work. I have also considered trying to override the form in the form view, but can't seem to get that to work either. I ultimately want the … -
Render context data to generic.DetailView
How can i render data or redirect with context data to generic.DetailView. I have model Note class Note(models.Model): key = models.CharField(max_length=50, primary_key=True) text = models.TextField() and my view is class ShowNote(generic.DetailView): model = Note template_name = 'notes/show_note.html' def get(self, request, *args, **kwargs): try: self.object = self.get_object() except Http404: # redirect here return render(request, 'notes/index.html', {'error': 'Note doesnt exist', }) context = self.get_context_data(object=self.object) return self.render_to_response(context) url(r'^show/(?P.*)/$', views.ShowNote.as_view(), name='show_note'), The page show the key of the note and its text also there is a button which save the text if it was changed. def save_note(request): key = request.POST['key'] selected_note = Note.objects.get(pk=key) selected_note.text = request.POST['text'] selected_note.save() //back to show_note How can i render a data {'message' : 'note was saved successfully'} in 'notes/show_note.html' but with same primary key -
Can I force Django to sort admin results in Python rather than in the database?
The issue is that if the database is allowed to sort results it sorts strings according to the C locale which yields awfully wrong results in my language. For example it considers all letters with diacritics to be after all ascii letters - so, for example, ś comes after z, while it should come in between s and t. However, as long as I'm allowed to sort results in Python, I can easily tell Python how to sort according to the current locale. setlocale(LC_ALL, 'pl_PL.UTF-8') and then set the key for sorting to be the result of strxfrm applied to the model's string representation. So, how can I force Django to sort results in Admin in Python and not in the database to circumvent the above issue? -
Django Rest Framework models post_save signal is executed after post request is completed
I have the following serializer: class CreateOrderSerializer(OrderSerializer): class Meta(MetaOrder): fields = MetaOrder.fields + ('pair',) read_only_fields = MetaOrder.read_only_fields def create(self, validated_data): withdraw_address = validated_data.pop('withdraw_address') # Just making sure address = Address.objects.get(address=withdraw_address['address']) order = Order(**validated_data) if not address: address = Address(**withdraw_address) address.type = Address.WITHDRAW address.currency = order.pair.quote address.save() order.withdraw_address = address order.save() return order And the following ViewSet: class OrderListViewSet(UserResourceViewSet, ReadOnlyCacheResponseAndETAGMixin): model_class = Order lookup_field = 'unique_reference' serializer_class = OrderSerializer pagination_class = OrderPagination def get_serializer_class(self): if self.request.method == 'POST': return CreateOrderSerializer return super(OrderListViewSet, self).get_serializer_class() def get_queryset(self, filters=None, **kwargs): self.queryset = Order.objects.all() return super(OrderListViewSet, self).get_queryset() def perform_create(self, serializer): if not self.request.user.is_authenticated: _create_anonymous_user(self.request) serializer.save(user=self.request.user) return super(OrderListViewSet, self).perform_create(serializer) and the following signal: @receiver(post_save, dispatch_uid='allocate_wallets') def allocate_wallets(sender, instance=None, created=False, **kwargs): if sender.__name__ not in ALLOWED_SENDERS: # Only run on users return if not created: return order = instance user = order.user currency = order.pair.quote if user is None: return if currency.disabled or not currency.is_crypto: return card, address = clients[currency.wallet].create_user_wallet(user, currency) order.deposit_address = address order.save() I suspect that the signal is executed after the response is already sent, since I do not get the deposit_address field from the POST request([POST] /orders) but I do get it from the detail view ([GET] /orders/:id). What can be done to … -
Sparkpost suppression error and mail stops sending
I am using sparkpost for one of my django website to send mails to users. I had an update on site so sending mails to all users. However few of users have deleted their gmail id from gmail and I understand that mails cannot be sent to those ids. However problem I am facing is that in django, sparkpost stops sending mails to all users once a single mail fails because of this. Error message is this: Message generation rejected Code: 1902 Description: recipient address was suppressed due to system policy -
Wagtail serve different language on home page
From documentation: Users are forwarded to their preferred version, based on browser language, when they first visit the site. Question: Is it possible users to be forwarded not based on browser language? -
Trying to use data-importer django package
I'm trying to use data-importer django package, the documentation is extensive but does not specify about some topics. I need to upload an *.xlsx document, and enter that data into my database. First time I do this in python, and I have no idea how to do it in Django, if someone has an example that includes views, models, forms, etc. I would appreciate it if they shared it. Thank you! -
creating Django chat app with one room and two users
I want to create a very simple and basic Django chat application with one room and two users chatting to each other as one of them will be me as an ADMIN and the other is a regular user. i have thought about using Django channels but i'm a bit confused to how to incorporate with my Django project!! what is the best place to start with and if there are any examples? or should i use jQuery? Than you -
Django tutorial maximum depth recursion
I am doing the django first app tutorial. When I try access the localhost webpage, I get a maximum depth recursion error. The check method keeps on getting returned until maximum depth. The code is as follows for urls.py: from django.contrib import admin from django.conf.urls import include from django.conf.urls import url from polls import views urlpatterns = [ url(r'^$', views.index, name ='index'), url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] View.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello World. You're at the polls index") The error code: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() RecursionError: maximum recursion depth exceeded What can I do to remedy this? Thank you -
Simple Inventory App in Django, count residual
I am building some small inventory tracking app and wondering how to organize database and logic. I am fresh in Django. I came up with some basic DB scheme: DB schema for inventory App Django (Link to the Image) So I am wondering if I am going to use this arrangement than how to derive list of residual inventory, ready to be exported as JSon, probably, and represent it in a Django view properly? *One of my ideas was to create an extra model which is a list of balances on each inventory item and will be updated each time new item is received or existing is used. This approach worked to some extent but seems prone to mistakes or double entries. * -
Django Email - Define Username and Password
From the documentation, I see that the host, port, username, and password can be defined in a backend file, but I want to define all of them in my code itself. Can this be done? If so, how? from django.core.mail import EmailMessage email = EmailMessage( 'Hello', 'Body goes here', 'from@example.com', ['to1@example.com', 'to2@example.com'], ['bcc@example.com'], reply_to=['another@example.com'], headers={'Message-ID': 'foo'}, ) message.attach_file('/images/weather_map.pdf') Thanks in advance!