Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ckeditor in django in my local view not in admin
i want to use ck editor in my project. i can install ck editor in admin view but I want to install this editor in my local form that i created in my forms. can you please tell me how to do that? i am new in this can you please tell me all of the steps although ck editor appears in admin then i have done some steps but it would be my pleasure if you tell it from first. i did this in my models.py: from ckeditor_uploader.fields import RichTextUploadingField and: text = RichTextUploadingField() i added this to my urls.py: url(r'^ckeditor/', include('ckeditor_uploader.urls')), and this is my form class for Comment model: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['text'] django 1.10 jQuery v1.11.1 python 3.5 -
Changing value type doesn't change ValueError invalid literal for int() with base 10: ''
I'm very new to Python and am building a basic blog in django. I am trying to enable editing of individual blog posts. I have to 'get' these individual blog posts so I can edit them. So far, the system isn't liking my '.get' method and shows me a ValueError. I have tried changing the value type to int, str, float, even complex. It all either returns the same or says it doesn't like 'id' or even 'pk' if I change it to that. Here is the code. views.py from django.shortcuts import render from blogs.models import BlogPost from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .forms import PostForm def index(request): """The home page for blogs""" blogposts = BlogPost.objects.order_by('date_added') context = {'blogposts': blogposts} return render(request, 'blogs/index.html', context) def blogpost(request, blogpost_id): """Show a single post""" postings = BlogPost.objects.get(id=blogpost_id) context = {'postings': postings} return render(request, 'blogs/blogpost.html', context) def new_post(request): """Writ a new post to the blog""" if request.method != 'POST': # No data submitted; create a blank form. form = PostForm() else: # POST data submitted; process data form = PostForm(data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogs:index')) context = {'form': form} return render(request, 'blogs/new_post.html', context) def edit_entry(request, entry_id): """Edit an existing entry""" entry … -
Django view variables
I'm trying create a value from two user given variables in my detail view template. I've tried using jinja to do math inside of the HTML but then found that the preferred way is to create variables inside of the apps views.py file. I've found a few conflicting ways Here's what I have currently: def meter_variables(request): GvData.incoming_meter_daily_total = (Class.incoming_meter_1_close - GvData.incoming_meter_1_open) + (GvData.incoming_meter_2_close - GvData.incoming_meter_2_close) return render(request, 'geneva/geneva_record.html', {'incoming_meter_daily_total': GvData.incoming_meter_daily_total}) in my html I have: <td><input type="number" class="form-control" placeholder="Daily Total" value="{{ object.incoming_meter_daily_total }}"/> </td> It provides no value. I think I'm accessing the values from the model object incorrectly but I'm not sure how exactly. My class in models.py is very long but all fields are a variation on: class GvData(models.Model): gv_01_open_stock = models.FloatField(default=0) gv_02_open_stock = models.FloatField(default=0) -
Can't retrieve values from a ManyToManyField in Django
I've read the documentation for the QuerySet API and some answers here but I can't seem to figure this out. I think I'm not understanding the concept behind this. So, this is my the models.py: class Categoria(models.Model): TODOS = 'Todos' VEICULO = 'Veiculo' EQUIPAMENTO = 'Equipamento' SERVICO = 'Servico' OUTRO = 'Outro' CATEOGRY_CHOICES = ( (TODOS, 'Todos'), (VEICULO, 'Veiculo'), (EQUIPAMENTO, 'Equipamento'), (SERVICO, 'Servico'), (OUTRO, 'Outro') ) tipo = models.CharField(max_length=15, choices=CATEOGRY_CHOICES, default=TODOS) def __str__(self): return self.tipo class Anuncio(models.Model): titulo = models.CharField(max_length=50) anuncio = models.TextField(max_length=200) preco = models.DecimalField(max_digits=6, decimal_places=2) contato = models.CharField(max_length=30) publicacao = models.DateTimeField() categoria = models.ManyToManyField(Categoria) def __str__(self): return self.titulo Then, I send this dictionary to the view: { 'anuncios' : Anuncio.objects.all() And this is how I display the values: {% for item in anuncios %} <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <h3>{{ item.titulo }}</h3> <p>{{ item.anuncio }}</p> <address>{{ item.contato }}</address> <h6><a href="#">{{ item.categoria.all.values }}</a></h6> </div> </div> {% endfor %} But I can't get the right value from that ManyToManyField. If I use item.categoria, I get lista.Categoria.None (lista is the name of the app). If I use item.categoria.all, I get <QuerySet [<Categoria: Servico>]>. And if I use item.categoria.all.values, I get <QuerySet [{'id': 7, 'tipo': 'Servico'}]>. All I really want, in this … -
limiting related object queryset on Django view based on permissions
I am reading Andrew Pinkham's Django Unleashed as an intro to learning Django and see an unresolved issue in the viewing of related objects in an object's views. Here's a simple explanation: Startups have related blog posts. Viewing of blog posts is limited by a permission: View_Future_Posts which restricts viewing of blog posts with pub_dates in the future to those who have this permission. I am using Generic Class Based views and when viewing Blog Posts (List or Detail) limit the queryset based on this permission by using a mixin which overrides get_allow_future method which checks the user's permission. My question is, how do I limit the list of blog posts related to a Startup when viewing a Startup using the GCBV ListView? Additionally, bc I am very new at this, where could I have looked to figure this out for myself? Many thanks! -
How do I install an older version of a django package?
I'm trying to install django-excel, but it seems like it has been upgraded to function with Django 1.9+ I'm using Django 1.8 and would like to make the package work again. I tried this, but I want to go back to a previous version(Django 1.7+): pip install django-excel -
How do you return 404 when resource is not found in Django REST Framework
When a user inputs a url that is wrong, my Django app returns an HTML error. How can I get DRF to return a json formatted error? Currently my urls is from django.conf.urls import url from snippets import views urlpatterns = [ url(r'^snippets/$', views.snippet_list), url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail), ] but if a user goes to 127.0.0.1:8000/snip They get the html formatted error rather than a json formatted error. -
HTTPS redirection with kubernetes l4 load balancer
My application does not need to respond to http requests, except to redirect them to https, but I'm having trouble configuring it for that. I have Django, behind Guincorn, behind a Google Cloud level 4 load balancer (set up through kubernetes). I'm not using nginx, because the static files are served through google cloud storage buckets so it seemed to add unnecessary complexity (is there a reason this is wrong?) When I configure guincorn for https, it doesn't respond to http requests (ok). The first idea I had was to forward port 80 and 443 through the load balancer and then let django/guincorn take care of redirection, but I can't get guincorn to serve both http and https at the same time, even when I tried exposing two ports: gunicorn --threads 2 -b :8000 --keyfile=key.txt --certfile=cert.txt myapp.wsgi The load balancer config is: apiVersion: v1 kind: Service metadata: name: xxx labels: name: xxx spec: ports: - port: 443 name: https targetPort: 8000 selector: name: app type: LoadBalancer loadBalancerIP: xx.xx.xx.xx It is possible to changes this so that gunicorn will also answer https requests? (the Django config is setup not to redirect http requests). Or have I gone about this completely wrong? … -
Password recovery + workflow alternatives in DJANGO REST
I'm developing a system that have a Django/Python backend and a native iOS and Android app. There is only an admin web interface (for few administrators), most users don't have access to the web site. The backend provides a REST API interface to the mobile apps. I'm trying to create a recovery password method for mobile users, that's is, if a user don't remember her password, she just tap over a button, write her email and her information will be sent to some REST method. The problem is that I'm not sure on how to implement the forgot password workflow under the above reality. The "classic" approach, consist in sent an email with a link, seams to be strange because user will only get a site with the reset form. On the other hand, the alternative is sent to the user some key to her email. She could copy this key into some mobile form, then, if the key is valid, the user have to reset her password (in the mobile app). Problem with this approach is that I have to implement custom password recovery (I have to store the keys in the server and create at least 2 REST … -
Django absract vs non-abstract model inheritance
Consider these two model classes Bookand Article: class Book(models.Model): title = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) Imagine this scenario: a book can have many annotations but an annotation can refer to only one book. Same thing for the article. I have developed two solutions: Non-abstract solution class Annotation(models.Model): body = models.TextField() article = models.ForeignKey(Article, blank=True) book = models.ForeignKey(Book, blank=True) class Meta: default_related_name = 'annotations' Pros Code is DRY One can access the annotations with book.annotationsor article.annotations Cons Waste database memory (one of the two fields article, book must be none) Abstract classes solution class Annotation(models.Model): body = models.TextField() class Meta: abstract = True class BookAnnotation(Annotation): book = models.ForeignKey(Book, blank=True) class Meta: default_related_name = 'book_annotations' class ArticleAnnotation(Annotation): article = models.ForeignKey(Article, blank=True) class Meta: default_related_name = 'article_annotations' Pros Clear separation for book and article annotations No memory waste Cons Does not quite match the concept of annotation (the object type should be the same) One can access the annotations with book.book_annotationsor article.article_annotations (kind of ugly isn't it?). I can not use annotations as related name because Django prohibit that, it says reverse query name for BookAnnotation clashes with field name ArticleAnnotation. Which is the best approach to deal with such situation? -
Django channels API for android app
I am currently developing a server for android social network app. I am using Django and I need to add a real-time chat to it. I decided to use django-channels, but I am not sure how to use auth tokens coming to the server from the android to make the authentication in chat. Also, will django-channels even work properly in this situation or should I consider something else? -
EB Django config commands error
I've been trying to deploy my django app on EB for few days but I keep getting an error trying to run a command. So basically, when I try to deploy the app it gives me "python: can't open file 'manage.py': [Errno 2] No such file or directory." For the full error, this is what I get after running eb deploy on my terminal. Starting environment deployment via CodeCommit --- Waiting for Application Versions to be pre-processed --- Finished processing application version app-e8a0-170203_135603 INFO: Environment update is starting. INFO: Deploying new version to instance(s). WARN: Environment health has transitioned from Severe to Degraded. 100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health. Command failed on all instances. Incorrect application version found on all instances. Expected version "app-e8a0-170203_135603" (deployment 43). Application update in progress (running for 2 seconds). ERROR: [Instance: i-05377fd0bcfa86dd6] Command failed on instance. Return code: 2 Output: python: can't open file 'HungryBoat/manage.py': [Errno 2] No such file or directory. command 03_migrate in .ebextensions/03_commands.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. INFO: Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR: Unsuccessful command … -
Change a row when "now()" is a specific datetime. Django
I've this column information_release_counter. And another one confirmed. I update my information_release_counter so : serializer_id.information_release_counter = datetime.datetime.now() + datetime.timedelta(hours=48) I would like that when datetime.datetime.now() - serializer_id.information_release_counter == 0 serializer.confirmed was "True". But it should happen automatically. I don't know if there's a "watcher" or something like that. I was reading the celery task and eta, but I don't have a clue how I can use it. :) -
Thumbnail view using bootstrap and python libraries
What's the difference between thumbnail view using bootstrap and python libraries in Django? Which is better? Why? -
Django, react and redux. Issue with generating Json response views for the Ajax request
I am new to Django and python. I am developing an application with Django as the back end and React Redux as my front end. I am not able to generate Json response for the requests.I have a model tracks class Track(models.Model): title = models.CharField(max_length=255,null=False) description = models.TextField(max_length=500,null=False) track_url = models.CharField(max_length=500,null=False) image_url = models.CharField(max_length=500,null=False) artist = models.CharField(max_length=255,null=False) user_id = models.ForeignKey(account_models.User,on_delete=models.CASCADE,null=False) class Meta: ordering = ["title"] Ajax request: export const fetchTracks = () => ( $.ajax({ method: 'GET', url: 'api/tracks' }) ); export const fetchTrack = trackId => ( $.ajax({ method: 'GET', url: `api/tracks/${trackId}` }) ); serializer: class TrackSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='email' ) class Meta: model = Track fields = ('id', 'title', 'description', 'track_url', 'image_url', 'artist', 'user_id') def create(self, validated_data): track = Track.objects.create(**validated_data) track.save() return track Track view: def index(request): print("Pass Index") return render(request, 'index.html') class TrackDataView(GenericAPIView, CreateModelMixin): authentication_classes = (JSONWebTokenAuthentication,) serializer_class = TrackSerializer queryset = Track.objects.values_list('title', 'image_url') def get(self, request): print("TrackDataView get") queryset = self.get_queryset() serializer = TrackSerializer(queryset, many=True) return Response({"track": serializer.data}, content_type="JSON") class TrackView(GenericAPIView, CreateModelMixin): authentication_classes = (JSONWebTokenAuthentication,) lookup_url_kwarg = "track_id" def perform_create(self, serializer): serializer.save(user=self.request.user) def create(self, request, *args, **kwargs): print("TrackDataView create") serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response({"track": serializer.data}, status=status.HTTP_201_CREATED, headers=headers) def get(self, … -
How does values_list django work?
I have interesting experience with value_list django and I don't know why is it acting in this way? Background I want to update any value in TestObject has value_1 to value_2 AND any value_2 to value_1. Where value_1 and value_2 from type Value and TestObject has a forignkey to Value. This is my code: def _swap(value_1, value_2): from_values_ids = TestObject.objects.filter(value=value_1).values_list('id', flat=True) to_values_ids = TestObject.objects.filter(value=value_2).values_list('id', flat=True) TestObject.objects.filter(id__in=from_values_ids).update(value=value_2) TestObject.objects.filter(id__in=to_values_ids).update(value=value_1) I tested with TestObject has value_1 but does not have any value_2. The end result was nothing happened after running this function. After investigating I found the TestObject got updated to value_2 after running:TestObject.objects.filter(id__in=from_values_ids).update(value=value_2) but it returned back after running TestObject.objects.filter(id__in=to_values_ids).update(value=value_1). I thought may be to_values_ids has lazyload that is why I added print to_values_id. def _swap(value_1, value_2): from_values_ids = TestObject.objects.filter(value=value_1).values_list('id', flat=True) to_values_ids = TestObject.objects.filter(value=value_2).values_list('id', flat=True) print to_values_ids TestObject.objects.filter(id__in=from_values_ids).update(value=value_2) TestObject.objects.filter(id__in=to_values_ids).update(value=value_1) But I got the same result. Although my print for to_values_ids has []. The way I fix it I created new lists with the ids and it worked but still needs to understand the core python how is it work? Any good explanation. Thank you in advance. -
django import_export with foreignkey of a second level model
I'm trying to import a xls with django import_export. It's ok to use widget with a direct foreignkey, like in cases of "unit" and "base". How to do the material import passing the entity_user? #Simplified Models: class Entity(models.Model): user = models.CharField(max_length=30,unique=True) class Base(models.Model): entity = models.ForeignKey(Entity) short_name = models.CharField(max_length=20) class Meta: unique_together = ('entity','short_name') class Unit(models.Model): short_name = models.CharField(max_length=10,unique=True) class Material(models.Model): base = models.ForeignKey(Base) unit = models.ForeignKey(Unit) #Resource: class MaterialResource(resources.ModelResource): unit = fields.Field( column_name='unit', attribute='unit', widget=widgets.ForeignKeyWidget(Unit,'short_name')) base = fields.Field( column_name='base', attribute='base', widget=widgets.ForeignKeyWidget(Base,'short_name')) entity_user = fields.Field( column_name='entity_user', attribute='entity_user', widget=widgets.ForeignKeyWidget(Base,'entity_user')) #########??? class Meta: model = Material -
Getting string instead of list when trying to get value of JSON response
I have the following JSON response: {"response": [100, {"name": "Bill"}, {"name": "John"}]} All I need is to iterate through the list. So my plan is to get the list first and then iterate through it. But when I tried to get the list with list_dict.json().get("response") I got the string: 100{"name": "Bill"}{"name": "John"} How could I get the list? -
All pictures adjusted automatically to left on blog
All pictures adjusted automatically to left on blog I have created page here: http://dzikuss98.pythonanywhere.com/ using django As you see all pictures are aligned to left even during creation of post they were in middle below you can see my blog template: { % extends "personal/header.html" %} {% block content %} {% for post in object_list %} {% autoescape off %} <h5>{{ post.date|date:"Y-m-d" }}<a href="{{post.id}}"> <b> {{ post.title }}</b></a></h5> {{ post.body|linebreaks|truncatechars:300 }} {% endautoescape %} {% endfor %} {% endblock %} I use WYSIWG editor -
How to search paragraph(s) for objects
I'm looking for a way to parse objects out of naturally written text. I have a database of thousands of locations (City, State). As my users write posts, I would like to intelligently find and enrich locations being written about. For example, given the post: I had a really nice trip to Portland this weekend. It was beautiful and the climbing gyms are second to none. I'd like to suggest Portland, OR and Portland, ME and ask the user to choose one. Is there a name for this kind of search? I'm not even sure where to start. -
Nginx RTMP and Django Stream Authentication
I have created an RTMP streaming server with Nginx RTMP. I would like to setup authentication so a streamer can use a streamkey like "89436jhjioug85jio" to stream and it goes to their personal channel but they cannot just stream to their personal name. So far I am looking at a tutorial. https://benwilber.github.io/streamboat.tv/nginx/rtmp/streaming/2016/10/22/implementing-stream-keys-with-nginx-rtmp-and-django.html But I cannot find out the right code for this part. # Assuming we have a model `Stream` with a foreign key # to `django.contrib.auth.models.User`, we can # lookup the stream and verify the publisher is allowed to stream. stream = get_object_or_404(Stream, key=stream_key) So far I have got this: from django.db import models from django.contrib.auth.models import User class Stream(models.Model): stream = models.CharField(max_length=255) streamkey = models.CharField(max_length=255) Thanks for the help. -
Does Python garbage collect when Heroku warns about memory quota vastly exceeded (R15)?
I have a background task running under Celery on Heroku, that is getting "Error R14 (Memory quota exceeded)" frequently and "Error R15 (Memory quota vastly exceeded)" occasionally. I am loading a lot of stuff from the database (via Django on Postgres), but it should be loading up a big object, processing it, then disposing of the reference and loading up the next big object. My question is, does the garbage collector know to run before hitting Heroku's memory limit? Should I manually run the gc? Another thing is that my task sometimes fails, and then Celery automatically retries it, and it succeeds. It should be deterministic. I wonder if something is hanging around in memory after the task is done, and still takes up space when the next task starts. Restarting the worker process clears the memory and lets it succeed. Maybe Django or the DB has some caches that are not cleared? I'm using standard-2x size. I could go to performance-m or performance-l, but trying to avoid that as it would cost more money. -
Django Rest Framework - Serializing relationship differently for GET and POST
Given 2 main models: TransportOrder and Company with a many to many relationship through TransportOrderConsumer. I would like to achieve the following. GET TransportOrder: TransportOrder fields are listed as well as a list of hyperlinks to consumers. I've accomplished this through the below relationship on the Company and serializer consumers = models.ManyToManyField(Company,through = "TransportOrderConsumer") class TransportOrderReadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TransportOrder #fields = ('id', 'producer_system_code', 'status','producer', 'created_at') fields = ('id','producer','producer_system_code','status','producer', 'created_at','updated_at','consumers') #read_only_fields = ('updated_at') POST Transport Order: In the POST serializer, I want to nest a TransportOrderConsumerSerializer but call it "consumers" so that there is consistency between the get and post calls. -
Encypting SMTP server password in Django Settings
I have a view that generates an email based on a form and sends it to three service vendors: def quote(request): if request.method == 'POST': . . . send_mail( 'Quote Request: ....', 'Message Body', 'myemail@email.com', ['vendor1@email.com, vendor2@email.com, vendor3@email.com] ) In my settings I have TLS, host, User, Password, and Port # number defined: EMAIL_USE_TLS = True EMAIL_HOST = 'stmp.office365.com' EMAIL_HOST_USER = 'myemail@email.com' EMAIL_HOST_PASSWORD = 'My Plain Text Password That I Want to Encrypt Here!' EMAIL_PORT = 587 The process works great - but I need to encrypt that plain text password. What would be the best way to go about doing so? -
How to use Django-autocomplete-light for foreign key in the admin
I've been struggling to add an autocomplete to django admin fk fields, I've come across this third party app, Django-autocomplete-light, but its docs are very confusing for beginner like me. So, I have my model, and how could I add an autocomplete for the fk fields. Class Order(models.Models) Client = models.ForeignKey(settings.AUTH_USER_MODEL)