Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't see django markdown editor with django 1.10v
I'm using django 1.10 / python 3.6. and I'm new at django. I followed up all the details with django_markdown github First, I have a trouble with urls.py in django_markdown, but I found the answer (I'm not sure it's right, anyway) in django_markdown github issue I solve the url problem but then I can't see my editor either admin or development page. this is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'django_extensions', 'social_django', 'multiselectfield', 'django_markdown', 'blog', ] also I add my urls.py url('^markdown/', include('django_markdown.urls') I make my models with MarkdownField too. from django_markdown.models import MarkdownField class Entry(models.Model): title = models.CharField(max_length=50) #.. md_content = MarkdownField() Also adding in admin.py, too class EntryAdmin(MarkdownModelAdmin): ... admin.site.register(Entry, EntryAdmin) But I can't find markdown editer in admin, just seeing default page. Is there anything wrong with my code? Or there's no more support django 1.10 in django_markdown? -
DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x93 PDF file is not saving
This is my piece of code here in an API result = StringIO.StringIO() pdf_template = get_template( "submit_quotation.html").render(Context(ctx)) result = StringIO.StringIO() pisa.pisaDocument( StringIO.StringIO(pdf_template), dest=result) attachment = result.getvalue() notification_template = NotificationTemplate.objects.get( notification_event='submitquote') print 'bro' Communication.objects.create( entity_id=obj.id, entity_name='quotation', entity_type=ContentType.objects.get(model='quotation'), # receivers=user_ids, subject=notification_template.subject, # to=user_ids[0], content=notification_template.content, communication_type=1, attachment=attachment ) and here i am is creating a pdf file and want to save it in a FileField in model MOdel is class Communication(Timestampable): attachment = models.FileField( upload_to=file_path, blank=True, null=True, ) But getting this error DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 10: invalid start byte. You passed in '%PDF-1.4\n%\x93...... need help urgent....Thanks in advance -
AJAX: form.serialize() and csrf token together?
Can someone say whats wrong with this lane data:... inside saveForm function? I have list of tasks in my page. Every task has there own form where users can send comments. When I add new task AJAX update list of comments and then I try to send comment by form and it raise error : “CSRF token missing or incorrect”. I have {% csrf_token %} in all my forms. It seems like I need send CSRF in AJAX. Where I did mistake? function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); // TASK $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, … -
Django: What is the basic difference beween User and Anonymous user?
According to my current understanding: User model represents superusers and staff members only on the other hand normal visitors visiting site to read content belong to Anonymouse Model. Is that so ? Django docmentaion is not very clear about this. -
Displaying image onto django web directly from static directory
Is there a way I can display my images from the static directory using bootstrap? I can do it for single image, but I want to display multiple images. This is what I done so far, <div class="thumbnail"> <a href="{% url 'visual:detail' album.id %}"> <img src={% static 'visual/images/a.jpg' %} class="img-responsive"></a> I was thinking if its possible to use php, any advice? thanks -
Django Admin randomly failed to load data / css / js
My Django admin randomly failed to download the data / css / js, which forced me to refresh again then it works fine. Is this normal? I use django-filer, django-grappelli, django-ckeditor, django-tinymce. django-filer looks kinda messed up, and grappelli admin tends to fail to load some CSS / the current model data in the index page or in the update page. -
Django template inheritance not working properly
I have two kinds of templates who are inheriting from two base templates in the project. My template structure is like this -- reg/ welcome.html staff/ staff.html base.html reg.html welcome.html is supposed to inherit from reg.html. Where staff.html is supposed to inherit from base.html. My problem is welcome.html is inheriting from base.html instead of reg.html. Is there any reason for these? Welcome.html -- {% extends 'reg.html' %} {% load static %} {% block content %} <div class="wrapper"> <div class="container welcome-container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <img src="{% static 'img/logo.svg' %}"> <form method="post" action="{% url 'find_personal' %}" role="form"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}"> {{ field.label }}</label> {{ field }} </div> {% endfor %} <div class="form-group"> <button type="submit" class="btn btn-primary">Next</button> </div> </form> </div> </div> </div> </div> {% endblock %} {% block script %} {% endblock %} reg.html - {% load static %} <!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"> <title>M&amp;Q</title> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500"> <link rel="stylesheet" href="{% static 'reg/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'reg/font-awesome/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'reg/css/style.css' %}"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> … -
Authication page using Angular Js [on hold]
I want to integrate a login authentication page like Facebook and google by which users from other site can login in my site, I am using python and angular js -
Python installation along with django framework
The first problem we are facing is after installing of python the python path can't be set properly and after that please guide me the steps for installing python along with Django. -
Graphite or Django seems to be missing some templates and I don't know how to supply them
I'm following this tutorial: https://www.infoq.com/articles/graphite-intro Everything works until the end when I execute this line: tail -f /opt/graphite/storage/log/webapp/process.log I see on the terminal: django-admin.py runserver --pythonpath /opt/graphite/webapp --settings graphite.settings 0.0.0.0:8085 but then I navigate with my browser to my_ip:8085 where my_ip clearly is my otherwise working ip address. I then get this error in the browser: A server error occurred. Please contact the administrator. And in my terminal I get this error: [19/Apr/2017 03:48:03] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib64/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 153, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 228, in handle_uncaught_exception return callback(request, **param_dict) File "/opt/graphite/webapp/graphite/views.py", line 7, in server_error template = loader.get_template(template_name) File "/usr/lib/python2.7/site-packages/django/template/loader.py", line 145, in get_template template, origin = find_template(template_name) File "/usr/lib/python2.7/site-packages/django/template/loader.py", line 138, in find_template raise TemplateDoesNotExist(name) TemplateDoesNotExist: 500.html Please, someone help a rookie out! -
How to have one to one relationship but keep track of all records at the same time - Django relationships
I have this below models where PostingOrder gets created when Posting is created. When Posting gets reposted a new PostingOrder gets created. I want to have one current PostingOrder per Posting but also want to be able to track all PostingOrders per Posting. My current issue is that when I query PostingOrder with a specific Posting I'm getting multiple PostingOrder queryset. I could get the current PostingOrder by filtering for the recently created but I feel like this is not a good approach. Any suggestions would be appreciated. class Posting(models.Model): title = ... author = .... class PostingOrder(models.Model): posting = models.ForeignKey(Posting) order_date = models.DateTimeField(auto_now_add=True) payment_method = models.CharField(max_length=1, choices=PAYMENT_METHOD_CHOICES) amount = models.IntegerField() -
Django Bower Install Virtualenv
I have looked through the threads on this topic and have not been able to figure out a solution. I am attempting to use the HandsOnTable library (https://handsontable.com/) in a Django app. I am trying to install the library with django-bower but I cannot seem to configure it properly. Every time I think I have django-bower installed, the settings.py file does not find django-bower under Installed Apps. Can somebody direct me to a proper tutorial on how to install/configure django-bower in a Django virtualenv? -
suds client making POST Request to spyne django SOAP server
Im trying to build a small SOAP service using spyne, here is the code: class Person(ComplexModel): age = Integer first_name = String last_name = String class Response(ComplexModel): persons = Array(Person) class SoapService(ServiceBase): @rpc(String, _returns=Response) def GetTest(ctx, name): all_persons = Person.objects.all() retval = Response() retval.persons = [] for p in all_persons: retval.persons.append({'age': p.age, 'first_name': retval.persons, 'last_name': retval.persons}) return retval application = Application([SoapService], tns='spyne.test', in_protocol=Soap12(validator='lxml'), out_protocol=Soap12() ) test = csrf_exempt(DjangoApplication(application)) My urls.py from django.conf.urls import url from django.contrib import admin from fbi.views import * from spyne.server.django import DjangoView from spyne.protocol.soap import Soap12 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello_world/', test), url(r'^say_hello/', DjangoView.as_view( services=[SoapService], tns='spyne.test', in_protocol=Soap12(validator='lxml'), out_protocol=Soap12(validator='lxml'))), ] Im trying to test the service using suds as a soap client with the following code: hello_client = Client('http://localhost:8000/say_hello/') hello_client.service.GetPersonByName('test') But Im getting a Webfault error from suds, and weirdly my django server receives a POST request from the client. [19/Apr/2017 02:26:54] "POST /say_hello/ HTTP/1.1" 500 561 Can anyone tell me what I might be doing wrong? Im not sure about the URL, Im following tutorials but I cannot understand the difference between the hello_world url and the say_hello. What is the purpose of each URL? -
DRF, nested serializer create
Following is the example given in DRF doc, I wonder if there's a way to use ProfileSerializer's create method instead of Profile.objects.create I need a way to pass additional data such as user. Because UserSerializer's create gets too long and I can delegate creation of each class to each serializer. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user I can do serializer = ProfileSerializer(data=profile_data, extra_context={'user': user}) serializer.is_valid() serializer.create() Only downside is I suspect ProfileSerializer instance is already created and is_valid is also already performed. I suspect there might be something like... self.fields['profile'].create() -
Dict union and sum another field
So, I have 2 dict and need sum t fields where username duplicated and transform in unique dict by username, but I don't know how do it. Someone help me? I'm very confuse. {username:'unique_username', t:20} {username:'unique_username_2', t:13} {username:'unique_username', t:20} {username:'unique_username_2', t:11} I need return like this {username:'unique_username', t:40} {username:'unique_username_2', t:33} Thanks for your attention. -
how to make inner join without relation in django orm?
This is my first model class DataPribadiSiswa(models.Model): SiswaID = models.AutoField(primary_key=True) WaliKelasID = models.CharField(max_length=11, blank=True, null=True) SiswaNIS = models.CharField(max_length=7, null=True, blank=True, unique=True) and this is my second model class Transaksi(models.Model): tanggal = models.DateField(null=True, blank=True) keterangan = models.CharField(max_length=100, null=True, blank=True) nominal = models.IntegerField(null=True, blank=True) nis = models.CharField(max_length=7, null=True, blank=True) how to make inner join query from that model without relation from those models where DataPribadiSiswa.Siswanis same with Transaksi.nis. Why i do not make relation because i have to import data xls to Transaksi model. -
How to add request get parameters form get form to url continuously
I have two kind of link. <li><a href="?{% url_replace request 'location' state.pk %}">{{ state.name }}</a></li> And <form id="price_filter_form" action="" method="get"> <input id="min_price" name="min_price" type="number" placeholder="Min"> <input id="max_price" name="max_price" type="number" placeholder="Max"> <button id="price_filter_button" type="submit">Go</button> </form> I want to add get parameters to url like ?location=state.pk&min_price=0&max_price=100. So I prepared custom filter: @register.simple_tag def url_replace(request, field, value): get_params = request.GET.copy() get_params[field] = value return get_params.urlencode() And I wanted to put this to form action like action='{% url_replace request field_name value_name %}' but I can't get 'field_name' and 'value_name' right? What should I do? The reason Why I want to do this is: When I click the first one's link, the URL is ?location=state.pk And then, if I click submit button of form, the Url is ?min_price=&?max_price= The URL I wanted is ?location=state.pk&?min_price=&?max_price= Help me. -
making user post show on profile page
Hey guys I am looking to do something like what this question is but I dont see whats wrong with my code. Something like this question. I'm just trying to make a profile page for my site and I wanted to add all the user posts on the profile page but I just dont seem to be able to get it to work. I tried googling the solution and even tried other stackoverflow questions but couldnt if the right answer. If anyone could help me I would be greatly appreciated. Thanks. models.py from django.db import models from django.contrib.auth.models import User def upload_location(posts, filename): return ("%s/%s" %(posts.author, filename)) class Post(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to=upload_location, null=True, blank=True, height_field="height_field", width_field="width_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) description = models.TextField() pub_date = models.DateTimeField(auto_now=False) author = models.ForeignKey(User) votes_total = models.IntegerField(default=0) def __unicode__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %d %Y') views.py, I am importing my Post class from a different app so I did think that could be the problem. from posts.models import Post def view_profile(request): logged_in_user = request.user logged_in_user_posts = Post.objects.filter(user=author) return render(request, 'accounts/profile.html', {'posts': logged_in_user_posts}) html file <div> {% for post in posts %} Post: {{ post.author }} <br> {% endfor … -
Add model in tree order with unlimited depth from a list
I have the following Category model: class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) As you can see, the category can have parent categories and subcategories via ForeignKey. Now suppose I have this list: Magazines Magazines/Tech Magazines/Tech/Network Magazines/Tech/Programming Magazines/Tech/Programming/Python Courses Courses/Design Courses/Design/Photoshop Courses/Tech Courses/Tech/Programming I need to save each individual category related to it's parent category. Please note that only checking the first parent category isn't enough since ../Tech/Programming can be found twice, for example. Also, there's not a maximum depth for the tree. -
how do i get the filename of a duplicated saved file on django models?
When i upload a file with the same name the second one is uploaded with a different name like this: First file: file.txt Second file: file1YlQx18.txt I want to get the name of the second file on a views.py because when i get the filename by method POST i just have file.txt I'm using Django Rest Framework serializers viewsets.py from rest_framework import mixins from rest_framework.viewsets import GenericViewSet class CreateOnlyViewSet(mixins.CreateModelMixin, GenericViewSet): def pos_create(self, request): pass def dispatch(self, request, *args, **kwargs): r = super(CreateOnlyViewSet, self).dispatch(request, *args, **kwargs) if r.status_code == 200 or r.status_code == 201: return self.pos_create(request) serializers.py from rest_framework import serializers from .models import MyModel class CareerSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' views.py from rest_framework.views import APIView from models import MyModel from .serializers import MyModelSerializer from .viewsets import CreateOnlyViewSet class MyModelViewSet(CreateOnlyViewSet): model = MyModel serializer_class = MyModelSerializer def pos_create(self, request): serialized = MymodelSerializer(data=request.POST) #get name of the second file -
Solving race conditions in Django/postgres
I have a django view which sends a payment receipt, and in multi-threaded environments, this view sends the receipt multiple times if called more than once. My code which does the update looks like updated = Transaction.objects \ .filter(id=transaction_id, status='processing') \ .update(status='paid') if updated: # send email Everything I've read on the internet suggests that selecting and updating rows that need to be updated in one query as I've done here should work. What am I doing wrong? A few things I've tried: do everything in raw sql, i.e. cursor().execute('...') using select_for_update method calling transaction.commit() after the update wrapping the update in transaction.atomic() The site runs apache/mod_wsgi, Django 1.8 and Postgres 9.4, and the problem goes away if I set threads=1 processes=1 in my mod_wsgi configuration. -
Unable to connect to Mysql from Django app - AWS, EC2, RDS
My current Set up: Django 1.9+ AWS - Launched an EC2 Instance (Amazon Linux). Launched an RDS instance of MySQL (5.6.7). I created a Virtual PC (VPC) for the EC2 instance and RDS instance, and in that group created several security rules so the EC2 instance could connect to the MySQL RDS. Below are the security rules I use and associate with the VPC. Inbound Rules: (Type, Protocol, Port Range, Source) 1. Http , TCP, 80 , 0.0.0.0/0 2. SSH , TCP, 22 , <my static IP address for the EC2 instance>/32 3. HTTPS, TCP, 443, 0.0.0.0/0 4. MYSQL/Aurora, TCP, 3306, source (my created security group) Nginx - Serving my content redirecting from port 80 to port 443. I created SSL certificates in order to make my site secure. I correctly served my Django application, and the static files. Nginx serves everything great! Previously I was able to connect to my RDS instance. I did not set up an elastic IP at that point in time, as it took some time to transfer my domain over to Route53 (amazons DNS). I successfully was able to transfer it, and associate it with my WC2 instance and even start my application The … -
Django how to call a choice field in template
I have a model field with choices. Like this: CHAIN_CHOICES = ( ('P','Public'), ('N','Private') ) chain = models.CharField(max_length=1, choices=CHAIN_CHOICES, verbose_name=u"Chain") In my template I would like to call it simillary to this: <li><i class="glyphicon glyphicon-tags"></i> <span>{{mymodel.chain}}</span></li> Problem is .... this is calling 'N' or 'P' and I would like to call the 'Public' - 'Private' values. Any hint would be wellcome. Regards, J.M. -
How to read a JSON file Django
How do I read a JSON file in Django, iterate through it, and display it? Any ideas would be helpful. -
Using signal to index a model
I have followed many examples and docs, but cannot get this right. I'm trying to make my Elasticsearch index whenever I update a model. Using the 'autoindex' does not log M2M's. It should update the when I change a Tag field (eg rename, or delete one). It should update when I add or remove a Tag from Item I am using django-elasticsearch (here) which is a wrapper around elasticsearch-py. How is this correctly achieved? class Tag(models.Model): name = models.CharField(max_length=500, blank=True) taglevel = models.IntegerField(null=True, blank=True) class Item(EsIndexable, models.Model): title = models.CharField(max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) class Elasticsearch(EsIndexable.Elasticsearch): serializer_class = TaskEsSerializer fields = ['title', 'tag'] @receiver(post_save) def index_elastic(sender, instance, *args, **kwargs): Item.es.do_index(instance) print(instance)