Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django safe method to implement tag prase into post
I want to implement the possibility of a quote tag into my users posts. I only want to allow plain-text and a [quote][/quote] tag. What is the common way to achieve this? I am using django-bleach with the following settings: BLEACH_STRIP_TAGS = False BLEACH_STRIP_COMMENTS = False BLEACH_ALLOWED_TAGS = [] BLEACH_ALLOWED_ATTRIBUTES = [] BLEACH_ALLOWED_STYLES = [] and my model looks like: class Post(models.Model): content = BleachField(max_length=10000, blank=True, null=True) I am using templatetags to convert the tag into html code @register.filter(is_safe=True) @stringfilter def quote(text): return text.replace('[quote]', '<div class="quote">').replace('[/quote]', '</div>') In the template I am using {{ post.content|safe|quote }} for output. -
How do I make a select option only required for choice submission?
So I'm using Python and Django for this task which means that the HTML is being built in a for loop which is provided in python. What I want to know is how I can make ONLY ONE select option required for each item on the loop. Have a look. {% for u in siglist %} <font size=4><b>{{ u.0 }}</b></font><br> {{ u.1 }}<br> <font size=2>{{ u.2 }}</font><br> <form method="post"> {% csrf_token %} <input type="submit" name={{ u.0 }} value="Agreed"><br> <select name="{{ u.0 }} select" required> <option disabled selected value> How important is this? </option> <option value="5">Very important</option> <option value="4">Important</option> <option value="3">Somewhat important</option> <option value="2">It would be nice</option> <option value="1">Not that important</option> </select><br><br> {% endfor %} Obviously this doesn't work because now all 32357823 of the other selections are required as well... -
not able to access and add product in admin site?-Django
i get this error in the browser Using the URLconf defined in myshop.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^admin/ ^login/$ [name='login'] ^admin/ ^logout/$ [name='logout'] ^admin/ ^password_change/$ [name='password_change'] ^admin/ ^password_change/done/$ [name='password_change_done'] ^admin/ ^jsi18n/$ [name='jsi18n'] ^admin/ ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ [name='view_on_site'] ^admin/ ^auth/group/ ^admin/ ^auth/user/ ^admin/ ^sites/site/ ^admin/ ^(?P<app_label>auth|sites)/$ [name='app_list'] The current path, admin/myshop/Product/add/, didn't match any of these. i am basically a beginner to django and creating my django shop app. i get this error by typing the url http://127.0.0.1:8000/admin/myshop/Product/add/ My admin.py looks like this from django.contrib import admin from .models import Category, Product class CategoryAdmin(admin.ModelAdmin): list_display=['name','slug'] prepopulated_fields={'slug':('name',)} admin.site.register(Category, CategoryAdmin) class ProductAdmin(admin.modelAdmin): list_display=['name','slug','category','price','stock','avialable','created','updated'] list_filter=['available','created','updated','category'] list_editable=['price','stock','available'] prepopulated_fields=['slug':('name',)} admin.site.register(Product, ProductAdmin) This is my models.py file from django.db import models # Create your models here. from django.core.urlresolvers import reverse class Category(models.Model): name = models.Charfield(max_length=200, db_index=True) slug = models.Slugfield(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) Class product(models.Model): category=models.ForeignKey(Category, related_name='products') name=models.CharField(max_length=200, db_index=True) slug=models.SlugField(max_length=200, db_index=True) image=models.ImageField(upload_to'product/%Y/%m/%d',blank=True) description=models.TextField(blank=True) price=models.DecimalField(max_digits=10, decimal_places=2) stock=models.PositiveIntegerField() available=models.BooleanField(default=True) created=models.Datetimefield(auto_now_add=True) updated=models.DatetimeField(auto_now=True) Class Meta: ordering=('-created',) index_togetther=(('id','slug'),) def__str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id,self.slug) I tried to check everything but everything looks ok to me -
status Code : 403 when connect to api by Swift
I use django and allauth, restframework, rest-auth. if i connect to my website on chrome or any browsers by rest-auth the address is ec2-52-79-82-216.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login, i can get key. but if i connect to my api on Swift, there are Status code : 403. I don't know what is problem TT could you help me? this is swift code import UIKit import Alamofire import SwiftyJSON import KeychainAccess class ViewController: UIViewController { let authLoginUrl = "http://ec2-52-79-82-216.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let params: Parameters = ["username": "username", "password": "123456!@#"] _ = Alamofire.request(self.authLoginUrl, method: .post, parameters: params) .responseJSON{ response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization let statusCode = response.response?.statusCode ?? 0 switch statusCode { case 200...299 : let jsonData = JSON(response.result.value) if let key = jsonData["key"].string{ print(key) } default : print("There was an error with your request") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } this is debug report Optional(http://ec2-52-79-82-216.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/) Optional(<NSHTTPURLResponse: 0x60800002a5e0> { URL: http://ec2-52-79-82-216.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/ } { status code: 403, headers { Allow = "POST, … -
Query for Line and Bar Graphs in Python
I have drawn line graph using python matplotlib. I want to indicate certain points on line graph in Red color which are below threshold value. Can anyone help me? Thanks in Advance. -
How to assign subject name to their proper field
I have used django-import-export package. And want to have related database from csv file of format, roll_no,student_name,subject_1_mark,subject_2_mark,....subject_n_mark i'm having difficulty of assigning subject mark to their appropriate field on django ORM example: #csv file roll_no, student_name, FOCP, IT, OS, DS, DL 201,john,56,34,65,34,68 Models.py class Student(models.Model): """ Store Student Information """ student_name = models.CharField(max_length=255) roll_no = models.IntegerField() class Subject(models.Model): """ Store Subject Information """ subject_name = models.CharField(max_length=150, null=True, blank=True) sub_code = models.CharField(max_length=255, unique=True, null=True,blank=True) class Exam(models.Model): """ Store Exam Information """ exam_type = models.CharField(max_length=150, null=True, blank=True) exam_date = models.DateField(null=True, blank=True) class Mark(models.Model): """ Store Mark Information """ subject_name = models.ForeignKey(Subject, related_name='marks', null=True, blank=True) exam = models.ForeignKey(Exam, related_name='marks', null=True, blank=True) mark = models.IntegerField(null=True, blank=True) settings.py INSTALLED_APPS = ( ... 'import_export', ) admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from import_export import resources from .models import Subject class SubjectResource(resources.ModelResource): class Meta: model = Subject class SubjectAdmin(ImportExportModelAdmin, admin.ModelAdmin): resource_class = SubjectResource admin.site.register(Subject, SubjectAdmin) -
How to add header data in ForeignKey django rest-framework
Is there a way to add header value to ForeignKey something like: current_user_header = models.ForeignKey('auth.headers', default={}, related_name='headers') this is the code i have right now in models: def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) def filename(instance, filename): return filename # Our main model: Uploaded Image class UploadedImage(models.Model): image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename) Tip = models.IntegerField("Image type") current_user = models.ForeignKey('auth.User', default=1, related_name='uploads') -
Getting error while inserting data into database using Python and Django
I need one help. I am getting below error while inserting data into database using python and Django. OperationalError at /insert/ no such table: bookingservice_service Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: 1.11.2 Exception Type: OperationalError Exception Value: no such table: bookingservice_service Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py in execute, line 328 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/opt/lampp/htdocs/carClinic', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] I am explaining my code below. bookingservice/models.py: from __future__ import unicode_literals from django.db import models from django.contrib import admin from datetime import datetime class Service(models.Model): """In this class the columns for service table has declared""" cname = models.CharField(max_length=200) date_of_service = models.DateTimeField(default=datetime.now, blank=True) vechile_no = models.CharField(max_length=200) service_type = models.CharField(max_length=200) class Personal(models.Model): """In this class the columns for Person table has declared""" name = models.CharField(max_length=200) address = models.CharField(max_length=200) phone = models.CharField(max_length=15) driving_license = models.CharField(max_length=200) email = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now, blank=True) admin.site.register(Personal) admin.site.register(Service) My views.py file is given below. from __future__ import unicode_literals from django.shortcuts import render, redirect from django.contrib.auth import login from django.views.generic import View from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm) from bookingservice.models import Service, Personal def booking(request): return render(request, 'bookingservice/booking.html', {}) def insert(request): if request.method == 'POST': company_name = request.POST.get('cname') vechicle_no = … -
GUI in web (Django) for Pyhton script
I have a program that takes 1 URL from a user, crawls all site and returns a list of all URL's with some parsed data for each URL. It all looks like: class Crawl(url_from_user): self.result = [<Page object at 1>, <Page object at 2>, <Page object at 3>] class Page(url): self.data_1 = "string_1" self.data_2 = "string_2" self.data_3 = "string_3" class Crawl - handle threading and all common inputs/data for each page. class Page - store unique data for each page and handle parsing HTML. I want to put this program in Web as a site. With Django, I can create pages that would take "url_from_user" and start crawling a site. I can store a result in SQL database or pass it around Django to different views. The question is how I can dynamically display result when Crawl isn't finished crawling a site. In the middle of Crawl, I can show the result to "stdout" in the console. Can I show not finished result in HTML page? My first thought is JQuery, but how JQuery could hook to "stdout" (or better if it would have access to a result list itself with all methods of Page - then I would be … -
Django modify css/sass with database values
I'm making a website where I want to be able to do many color and css customizations gotten from a Theme model. Right now the only way I can think of applying the colors is like the code below but it doesn't take much to see why this is bad practice. class Theme(models.Model): url_color = models.CharField(max_length=64) <a href style="color: {{ context_processor.url_color }}"> I am also using sass to generate the css file and it would be helpful if the answer could make the color values from the database work with sass's lighten and darken. -
django.db.utils.ProgrammingError: operator does not exist: character varying date
I am querying from a PostGre db in my Django project. Below is my code. flight_schedule_detail_instance = FlightScheduleDetail.objects.filter schedule_id=FlightSchedule.objects.filter(schedule_id=instance.schedule_id), flight_date=str(tomorrow_date) ) I need to filter all the instances which has a particular schedule_id and a flight_date . This works in my localhost. I am using sqlite in my localhost code. The server uses PostGre db. How do I query to get my desired results? Also, flight_date in my FlightScheduleDetail model is a DateField. And my schedule_id is a Foriegn key to another model which is a CharField in that model. I also tried without having a str wrapper to my tomorrow_date variable which is a date object. -
How to edit askbot source code preferably as a django app or project?
I cloned the askbot repo. To my surprise it was not a django project. It is a command line tool which setsup askbot projects that too importing the askbot views from the askbot package. I'm used to editing Django projects normally. I'm unable to know where the source is and what I have to do. Is it possible to edit askbot as a local django project rather than importing from the pip installed package? -
Getting error while migrating the models using Django and python
I need one help. I am getting the below error while migrating the model file using Python and Django. I am explaining the errors below. 264, in get_urls url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), AttributeError: 'Personal' object has no attribute 'urls' I am explaining my code below. models.py: from __future__ import unicode_literals from django.db import models from django.contrib import admin from datetime import datetime class Service(models.Model): """In this class the columns for service table has declared""" cname = models.CharField(max_length=200) date_of_service = models.DateTimeField(default=datetime.now, blank=True) vechile_no = models.CharField(max_length=200) service_type = models.CharField(max_length=200) class Personal(models.Model): """In this class the columns for Person table has declared""" name = models.CharField(max_length=200) address = models.CharField(max_length=200) phone = models.CharField(max_length=15) driving_license = models.CharField(max_length=200) email = models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now, blank=True) admin.site.register(Service, Personal) urls.py: from django.conf.urls import url, include from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), ] Here I need to display both classes inside admin panels. Please help me to resolve this issue. -
Get lookup_field value into update in serializer
This is django rest framework rest api. views.py class PostView(viewsets.ModelViewSet): lookup_field = 'to_user' def get_queryset(self): qs = Post.objects.filter(user=self.request.user) return qs serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' GET /post/1 is returning the intended data with pk=1 POST /post/ is also doing fine in creating a new data but PATCH /post/1 is not getting the pk 1 from lookup_field. How can I pass the lookup_field into PostSerializer's update method so that I can PATCH data with pk=1? -
How to create IPython Embedded console like Pythonanywhere in my Django Project?
I want to create Ipython console to embedded in my django project like pythonanywhere Example like this. I have installed IPython and all other requirements What i have tried it now import IPython def console(request): embed = IPython.embed() return HttpResponse(embed) I want to return emded() python shell to my web-page -
run Celery on same server as django?
I am running my Django app in a load balanced Elastic Beanstalk Environment. I want to add a Celery daemon process to do the following things: Upload files to S3 in background and send a success response to my Android app Send SMS to users to notify them about their upcoming EMIs (using celery beat) My app uses Google Cloud vision for some features, that takes 10sec to run, so I can run that in the background Now, I want to know if it is the right way to deploy celery on the same server as Django is running using Amazon SQS? If yes, how do I set that up? And if multiple servers on Elastic Beanstalk can cause duplicate tasks because of celery beat? -
django.db.utils.IntegrityError: NOT NULL constraint failed: chat_chat2.message
I try to built basic chat application in django using jquery. In my post view of views.py, I successfully get the message data but some how in c.save() i got an below error. i also try to debug passing default value but getting same error. i can't make it as a not null constraint. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Chat2(models.Model): user = models.ForeignKey(User) message = models.CharField(max_length=500) def __unicode__(self): return self.message chat.js $('#msg_f').on('submit',function(event) { event.preventDefault(); $.ajax({ datatype:"json", url : '/login/post/', type: 'POST', data:{msgbox : $('#msg_box').val()}, success : function(data){ $('#msg_box').val(''); $('#msg_b').append('<div class="msg_right"><p class="msg">'+data.msgbox+'</p></div>'); } }); }); views.py def post(request): if request.method=="POST": msg = request.POST.get('msgbox',None) c = Chat2(user=request.user,message=msg) if msg != '': c.save() return JsonResponse({'msg':msg,'user':c.user.username}) else: return HttpResponse("request must be post") Error [24/Jun/2017 09:21:45] "GET /login/login/chat_home/ HTTP/1.1" 200 3216 Internal Server Error: /login/post/ Traceback (most recent call last): File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: chat_chat2.message The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in … -
django_cron not sending email
I have just installed django_cron not django_crontab though, somehow I am trying to send an email as notification but it just wouldn't work. this is just for testing purpose so I set it to 1 minute. the code was a bit more complex before but it didn't work so I used the most simplified way to send email in order to make sure that it's not working. Also even used it as a post method to test, and it tested out working perfectly if a post method called the follow codes class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every minute schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'Email_Test' # a unique code def do(self): print('######################################') send_mail( 'Subject here from cron', 'Here is the message.', 'from@email.com', ['to@emailcom'], fail_silently=False, ) I tried running python manage.py runcrons and python manage.py runcrons --force and waited, (no errors, I also added the print because I want to see if the code even runs and good, I see the ################# got printed) can someone please give me an advise? Thanks in advance -
Logging all Django deprecation warnings
Is it possible to log deprecation warnings in Django to a lot file or something similar? I'm unsure how to setup a filter for something like this. -
Django ORM and left join - through annotate?
Asset.objects.filter( campaigns__games__pk=_version.game_id, campaigns__is_active=True, campaigns__games__active=True, is_active=True).select_related('org').all() this query returns 49 records Asset.objects.filter( campaigns__games__pk=_version.game_id, campaigns__is_active=True, campaigns__games__active=True, is_active=True, coupons__session__device_id='GUID').select_related('org').all() only ONE, because it makes INNER JOIN to Asset.coupons.session table. In reality what I want to retrieve the same 49 records as in the first query, but with additional information from session table if it exists. So I want to achieve is LEFT JOIN, so if for given asset the session exist - I then set a flag 'is_saved=True' in my API response. As far as I understand - the correct way is to use Annotate or Case/When? How to achieve? -
validation django forms with jquery
class TokenForm(forms.ModelForm): class Meta: model = Token fields =['token'] and here is the template where i used: {% block content %} <div class="row panel panel-success"> <div class="panel-heading text-center"> <h3> Crear Anuncio </h3> </div> <div class="panel-body"> <form method="POST" enctype="multipart/form-data" class="product-form">{% csrf_token %} {{ token.non_field_errors }} <div class="input-group"> {{ form.subject.errors }} <label for="{{ token.token.id_for_label }}">token: </label> {{ token.token }} </div> <div class="input-group"> <button type="submit" class="btn btn-lg btn-success btn-block">Guardar</button> </div> </form> </div> {% endblock %} i want create a validation in real time, it means that when i type in that field, and the input is the same that i have in a database change the color to green or something like that. i think i need ajax for that but i dont know how start. i appreciate your help. -
How to use Django prefetch_related
One of my listing page has an related model for providing unicode function. I tried to prefetch to prevent duplicate queries. Prefetch query is as below: SELECT "pansys_modulex"."id", "pansys_modulex"."client", "pansys_modulex"."change_date", "pansys_modulex"."changed_by_id", "pansys_modulex"."create_date", "pansys_modulex"."created_by_id", "pansys_modulex"."language_id", "pansys_modulex"."short_text", "pansys_modulex"."module_id" FROM "pansys_modulex" WHERE ("pansys_modulex"."language_id" = '3' AND "pansys_modulex"."module_id" IN ('8', '9', '10', '12', '13', '14')) Still, I get tens of duplicate queries like below: SELECT "pansys_modulex"."id", "pansys_modulex"."client", "pansys_modulex"."change_date", "pansys_modulex"."changed_by_id", "pansys_modulex"."create_date", "pansys_modulex"."created_by_id", "pansys_modulex"."language_id", "pansys_modulex"."short_text", "pansys_modulex"."module_id" FROM "pansys_modulex" WHERE ("pansys_modulex"."language_id" = '3' AND "pansys_modulex"."module_id" = '8') What is I missing here? I thought I would prefetch the query and django tries to use prefetch result if it can. -
python dev server doesn't run in production
I'm trying to deploy my Django app under a DigitalOcean VPS following this tutorial. I did each of the steps of the tutorial (I pulled my existing project from GitHub instead)up to the point where the tutorial asks me to do runserver for the first time. However, Chrome simply indicates to me the connection was refused, with no further information. I tried using http://0.0.0.0:8000, 127.0.0.1:8000, and the domain I registered. (nydkc11.org). I don't understand why it's not running, especially since I haven't integrated nginx or gunicorn yet. Below is my settings.py: import os from os import path # 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 # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0nv5*3azvk1r=vep=tzg_%4ugb!u4edl-5&$wmq*^22kku4%^d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['http://nydkc11.org','138.197.39.225','0.0.0.0:8000'] PROJECT_DIR_PATH = path.dirname(path.normpath(path.abspath(__file__))) # Application definition INSTALLED_APPS = [ 'about.apps.AboutConfig', 'forms.apps.FormsConfig', 'resources.apps.ResourcesConfig', 'contact.apps.ContactConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'embed_video', 'bootstrap3', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nydkcd11.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(BASE_DIR,'templates')),], 'APP_DIRS': True, 'OPTIONS': … -
How to set up mariadb with django/python
I am using python version 3.6.1 and django version 1.11.2 as well as mariadb server version 10.1.21, came with a xampp server install. is it possible to setup django to use this database, and if so how do i do it? brand new to django, so I know little to nothing about the language. Also, have little experience with the command prompt so I don't know what to do there either. Thanks. -
Creating more than one model to Extend Django user
How to link more than one django model to the authenticated user of a django app .And how will my view.py and html template look like if i want to display information from these models which are link to the user . Thanks in Advance .