Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting javascript error in ckeditor
My textare disaper and i get the error : 'TypeError: a is undefined' in javascript. I try to install a older version, and i get some other errors like "AttributeError: 'FilerImage' object has no attribute 'render plugin'" I think i need some other updates, or there are missing js but i am not sure. Pleasy help me. my pip freeze are: cmsplugin-contact==1.1.3 cmsplugin-filer==1.1.3 Django==1.9.7 django-appconf==1.0.2 django-classy-tags==0.8.0 django-cms==3.5.2 django-compressor==1.6 django-configurations==1.0 django-filer==1.3.2 django-formtools==1.0 django-mptt==0.8.6 django-polymorphic==1.0 django-reversion==2.0.13 django-sekizai==0.10.0 django-select2==6.1.2 django-treebeard==4.3 djangocms-admin-style==1.2.8 djangocms-attributes-field==0.3.0 djangocms-file==0.2.0 djangocms-googlemap==1.1.1 djangocms-link==1.7.0 djangocms-picture==2.0.6 djangocms-teaser==0.2.0 djangocms-text-ckeditor==3.6.0 easy-thumbnails==2.0 ecdsa==0.13 Fabric==1.8.3 gunicorn==18.0 html5lib==0.9999999 paramiko==1.12.4 Pillow==5.2.0 pkg-resources==0.0.0 psycopg2==2.7.5 psycopg2-binary==2.7.5 pycrypto==2.6.1 python-memcached==1.53 raven==3.4.1 six==1.11.0 Unidecode==0.4.21 webencodings==0.5.1 My settings are: """ Django settings for puxwebseite project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os from configurations import Configuration class Common(Configuration): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SITE_ID = 1 # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c1q)qg8+k6t1i^ii1hr^6owokjx75$i__&^gm5ow1(ys+d9onm' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # TEMPLATE_DEBUG = True ALLOWED_HOSTS = [''] … -
Is it a good practice to change your django application code by logging directly from EC2 rather than deploying it using Elastic Beanstalk?
I have uploaded an application using Elastic Beanstalk(aws service).It is working fine. Can I change application code by logging inside EC2. Is it a good practice to directly work using EC2 or You should use Elastic Beanstalk to deploy each versions ? -
django model field get default value of the id field
Hello guys I want to display labes for a layer in the map from geoserver but geoserver doesn't allow me to display the id field as a label. I created a new value no_man and would like for this field to automatically get the value of the id. If there is a way to display the id label I would remove the no_man, otherwise I would like to populate this field with the value of the id. models.py class ww_manholes(models.Model): id = models.BigIntegerField(primary_key=True) no_man = models.BigIntegerField() l_ass_obj = models.BigIntegerField() l_field_re = models.BigIntegerField() street = models.BigIntegerField() zip_code = models.BigIntegerField() regio_code = models.BigIntegerField() owner = models.BigIntegerField() ww_type = models.BigIntegerField() accuracy = models.BigIntegerField() x = models.FloatField() y = models.FloatField() x_ge = models.FloatField() y_ge = models.FloatField() z = models.FloatField() invert_el = models.FloatField() inv_start = models.FloatField() inv_end = models.FloatField() depth = models.FloatField() depth_star = models.FloatField() depth_end = models.FloatField() material = models.BigIntegerField() lining = models.BigIntegerField() coating = models.BigIntegerField() contractor = models.BigIntegerField() const_year = models.BigIntegerField() diam_nom = models.BigIntegerField() diam_inner = models.BigIntegerField() joint_type = models.BigIntegerField() cover_dim = models.BigIntegerField() cover_mat = models.BigIntegerField() access = models.BigIntegerField() rough_coef = models.FloatField() slope = models.FloatField() type = models.BigIntegerField() sc_condit = models.BigIntegerField() sc_perform = models.BigIntegerField() sc_fail_pr = models.BigIntegerField() sc_fin_imp = models.BigIntegerField() sc_soc_imp = models.BigIntegerField() … -
Stop Django From Escaping Jinja on Admin Page
I've been coding a small blog for myself using Django. There are two main models one for a Post and one for an Image, a Post can have many Images related to it. You write the content of a blog post from the Django Admin page, I have stopped the escaping of the HTML using | safe. However I'd also like to be able to reference the Image objects related to the Post from the admin page (e.g. {{post.image_set.all}}) I have tried this but Django seems to escape the Jinja code. I've searched for a while and cant seem to find an answer. Is this possible / is there an easier alternative? -
how to develop a multi currency wallet
I want to develop an iOS wallet that connects to EOS token and user can store multi currencies and cryptocurrencies and user can use mobile NFC feature to tap and pay. the front will be in the swift and back-end preferred to be in Django python. can you please introduce some resources that explain how to connect to EOShelp me with some basic information about how to do this. -
How to place a the label/description of a django char field above the textbox
I have a django form displayed like this in a template: <div> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </div> Which contains a field like this: introduction_text = forms.CharField(widget=forms.Textarea) As you can see in the screenshot below the field description (Introduction text) ends up to the left of the field, I would like it to be placed above. Is there a way to do this in the field definition in the form, without changing the projects css files and/or looping trough the elements of the form in the template? Screenshot link -
How to store an array of users in django?
I have a django model which is basically a group called Contexts.It contains some fields like name, description and a user.Below is the model defined class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = models.CharField(max_length=255, null=False) Currently there is only one user per Context.But I want to add more users to the same Context.So now I want to change the users field to an array field.By the way I am using django + postgres. So this is what I do class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = ArrayField(ArrayField(models.TextField())) But then how do I append users to the users field?This is what I do normally to add a context @csrf_exempt def context_operation(request): user_request = json.loads(request.body.decode('utf-8')) if request.method == "POST": try: if user_request.get("action") == "add": print("add") conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), users=user_request.get("user") ) except Exception as e: print("Context saving exception", e) return HttpResponse(0) return HttpResponse(1) But how do I append one user at a time to the users field in the same context (assuming same context name is passed)? -
Django Rest Framework + ReactJS: Whats wrong with my API?
I'm trying to fetch data from a django rest-framework API, using ReactJS. But I keep facing the same Error: 'SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"' I think the actual problem is is in my API, since I have already tried 3 different approaches to get the Data into React. Maybe somebody knows what I can do to my API to make it work? Im using the djangorestframework library. The API looks as following: { "questions":"http://127.0.0.1:8000/api/questions/?format=json", "choices":"http://127.0.0.1:8000/api/choices/?format=json" } And the React Component I'm using to retreive the Data is the following: import React, { Component } from 'react'; class ApiFetch extends Component { state = { data: [] }; async componentDidMount() { try { const res = await fetch('127.0.0.1:8000/api/?format=json'); const data = await res.json(); this.setState({ data }); console.log(this.state.data) } catch (e) { console.log(e); //SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" } } render() { return ( <div> {(this.state.data)} </div> ); } } export default ApiFetch; Thanks in advance for any ideas. -
Choices for a Decimal field
model.py class SomeModel(models.Model): price = models.DecimalField(decimal_places=1, max_digits=8) forms.py class SomeForm(forms.ModelForm): title = forms.CharField(label=_("Title"), required=False) price = forms.ChoiceField(choices=[], label=_("Price")) class Meta: model = SomeModel exclude = ('some_fields',) def __init__(self, min_price = 10, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) price_field = self.fields['price'] price_field.choices = ( (i, i) for i in xrange(min_price, 200, 5)) This throws an error because the value for price upon form post is a string, it is not saved on the Decimal field in the model. Typecasting for generators does not work here. What would be the solution to it? -
Django Customize many to many query
I have extended Django's default User class by adding a many to many field to another table called Algorithm. The new User class is: class User(AbstractUser): name = CharField(_("Name of User"), blank=True, max_length=255) algorithms = ManyToManyField(Algorithm, blank=True, default=None, related_name="users") def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) I want to specify if the user is_superuser or is_staff then User.algorithms.all() will get all algorithms. Otherwise, get only the records in the pivot table User_user_models. How can this be achieved? I tried to add a property method that check if superuser/staff then return all otherwise return super but it didn't work. P.S: during creating/editing the user, if user is set to superuser or staff, then there is no need to choose algorithms. -
Django: Signal/Method called after "AppConfig.ready()"
I have an AppConfig.ready() implementation which depends on the readiness of an other application. Is there a signal or method (which I could implement) which gets called after all application ready() methods have been called? -
How to display JSON task results stored via django-celery-results framework in django template?
In my project, i am using django-celery-results framework to access celery task results. The framework stores task results as JSON format. One of the results is figured out below; "{\"runs\": [{\"run_number\": 1, \"run_date\": \"2018-08-17 10:13:53.488079\", \"cycle_number\": 0, \"global_best\": {\"number_of_fitness_cases\": null, \"functions\": [{\"function\": \"<ufunc 'add'>\", \"name\": \"add\", \"arity\": 2}, {\"function\": \"<ufunc 'subtract'>\", \"name\": \"sub\", \"arity\": 2}, {\"function\": \"<ufunc 'multiply'>\", \"name\": \"mul\", \"arity\": 2}, {\"function\": {}, \"name\": \"div\", \"arity\": 2}], \"n_features\": 1, \"constants\": [{\"value\": 0.1}, {\"value\": 0.2}, {\"value\": 0.3}, {\"value\": 0.4}, {\"value\": 0.5}, {\"value\": 0.6}, {\"value\": 0.7}, {\"value\": 0.8}, {\"value\": 0.9}, {\"value\": -0.1}, {\"value\": -0.2}, {\"value\": -0.3}, {\"value\": -0.4}, {\"value\": -0.5}, {\"value\": -0.6}, {\"value\": -0.7}, {\"value\": -0.8}, {\"value\": -0.9}], \"terminals\": [{\"value\": 0.1}, {\"value\": 0.2}, {\"value\": 0.3}, {\"value\": 0.4}, {\"value\": 0.5}, {\"value\": 0.6}, {\"value\": 0.7}, {\"value\": 0.8}, {\"value\": 0.9}, {\"value\": -0.1}, {\"value\": -0.2}, {\"value\": -0.3}, {\"value\": -0.4}, {\"value\": -0.5}, {\"value\": -0.6}, {\"value\": -0.7}, {\"value\": -0.8}, {\"value\": -0.9}, 0], \"full_set\": [{\"function\": \"<ufunc 'add'>\", \"name\": \"add\", \"arity\": 2}, {\"function\": \"<ufunc 'subtract'>\", \"name\": \"sub\", \"arity\": 2}, {\"function\": \"<ufunc 'multiply'>\", \"name\": \"mul\", \"arity\": 2}, {\"function\": {}, \"name\": \"div\", \"arity\": 2}, {\"value\": 0.1}, {\"value\": 0.2}, {\"value\": 0.3}, {\"value\": 0.4}, {\"value\": 0.5}, {\"value\": 0.6}, {\"value\": 0.7}, {\"value\": 0.8}, {\"value\": 0.9}, {\"value\": -0.1}, {\"value\": -0.2}, {\"value\": -0.3}, {\"value\": -0.4}, {\"value\": … -
Show InlineModelAdmin for nested Model
I have nested models with OneToOneFields and want to have an InlineModelAdmin form in one ModelAdmin to point to a nested model... models.py: class User(models.Model): username = models.CharField(max_length=128) password = models.charField(max_length=128) class IdentityProof(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='proof') proof_identity = models.FileField(upload_to='uploads/%Y/%m/%d/') class Company(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='company') name = models.CharField(max_length=128) class Person(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='person') name = models.CharField(max_length=128) admin.py: class IdentityProofInline(admin.TabularInline): model = IdentityProof @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): inlines = [IdentityProofInline] @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = [IdentityProofInline] For CompanyAdmin or PersonAdmin, I want to show its User's IdentityProof. How can I do that ? I tried to use fk_name = 'user_proof or other combinations but it doesn't work... Thanks. -
how to write a login api in django without authentication and forms?
how to to write a login api for my users table without authentication and forms,in users table user name and password are the fields,i want to write a api to login with these fields, when they are matched? -
Custom docs with swagger
I've the following serializer for user's profile image: class UserProfileImageSerializer(serializers.ModelSerializer): profile_image = serializers.SerializerMethodField() class Meta: model = ProfileImage fields = ('profile_image',) def get_profile_image(self, obj): image = None request = self.context.get('request') if request and obj.profile_image: photo_url = obj.profile_image.image.url image = request.build_absolute_uri(photo_url) return image def create(self, validated_data): request = self.context.get('request') image = ProfileImage.objects.create(**validated_data) user = request.user if user: user.profile_image = image user.save(update_fields=['profile_image']) return image Some serializers can inherit this serializer as I want to have only one implementation of get_profile_image method. Here is my apiview: class ProfileImageAPIView(generics.CreateAPIView): serializer_class = UserProfileImageSerializer @swagger_auto_schema(**users_v1_profile_image) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(status=status.HTTP_201_CREATED) I've added custom docs for swagger: users_v1_profile_image = { 'request_body': UserProfileImageSerializer, 'responses': { status.HTTP_201_CREATED: '' } } The issue is that I'm always getting the same output even with custom docs: I want to mention that image must be provided in the body request in order to change user's profile image. Is it possible to fix this issue? -
Apache runs wsgi module (django application) twice in case of public router ip and internal server ip?
We've below netwrok setup Internal server ip : 192.168.153.20:443 Public router ip : 111.93.87.11:26060 We've port forwarding in router : 111.93.87.11:26060 to 192.168.153.20:443 So when we first access 192.168.153.20:443(Internal server ip) it runs/execute django application ( First time ) Now when we access 111.93.87.11:26060 (Public router ip) - due to port forwarding it comes to internal server ip but as apache receives host:111.93.87.11:26060,apache execute/run whole django application second time. So ulimately our application is being run two times for ip i.e internal ip and public router ip. This is creating very critical issue. This is may be due to Apache configuration. We need to run single instance for both internal and external IP. But it seems Apache parsing host name and running different instance for new external IP For reference Apache configuration attached in image -
Django filter in a View
I'm just starting on Django, and currently stuck on a seemingly simple requirement/behaviour. I want a page rendered with a filtered set of entries based on the class's ForeignKey, and called from a rendered view of that other class. A simplified version of my model.py is: from django.db import models class BookDay(models.Model): bookdate = models.DateField() bookevent = models.CharField(max_length=255) class BookTime(models.Model): booktime = models.TimeField() bookdate = models.ForeignKey(BookDay, on_delete = models.CASCADE) My view.py reads: from django.http import HttpResponse from django.views import generic from .models import BookDay, BookTime class DayView(generic.ListView): template_name = 'booking/days.html' context_object_name = 'bookdate_list' def get_queryset(self): return BookDay.objects.order_by('bookdate') class TimeView(generic.ListView): model = BookDay template_name = 'booking/booktimes.html' context_object_name = 'booktimes_list' def get_queryset(self): return BookTime.objects.filter(bookdate=bookday_id).order_by('booktime') My urls.py contains: from django.urls import path from . import views app_name = 'booking' urlpatterns = [ path('', views.DayView.as_view(), name='bookdays'), path('<int:pk>/', views.TimeView.as_view(), name='booktimes'), ] The referenced days.html renders a set of links per this fragment: {% for entry in bookdate_list %} <li><a href="{% url 'booking:teetimes' entry.id %}">{{ entry.bookevent }}</a></li> {% endfor %} On clicking any of the resulting links, the failure manifests as name 'bookday_id' is not defined. I can put a fixed integer in place of bookday_id in views.py above, and it works fine (for that ForeignKey … -
Django creating update post function
I want to create a post update/edit function but I have a problem. When I click "Update" button there is no error but there is no change. I think reason of that a mistake that I made in models.py but I can not figure it out. And here is my code models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) . . . def get_update_url(self): return reverse('post:post_update', kwargs={'slug': self.slug}) views.py def post_update(request, slug): if not request.user.is_authenticated(): return Http404() post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.save() messages.success(request, "Updated") return HttpResponseRedirect(get_absolute_url()) context = { 'form': form } return render(request, "blog/post_update.html", context) post_update.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>Form</h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <input class="btn btn-primary" type="submit" value="Create post"> </form> </div> </div> </div> {% endblock %} post_detail.html //update link <p ><a href="?P<slug>[\w-]+)/update/">update</a></p> Where is my mistake? What can I do? -
How to write optimal GraphQL Query to accumulate list of foreign keys from list of foreign keys (code options provided)
Let's say I have a DoggoDayCare. DoggoDayCare has multiple Doggo pointing at it (foreign keys) and Doggo has multiple favorite food (also foreign keys) pointing at it. Think something like this: { DoggoDayCare: [{ favFood: ['a'] }, { favFood: ['b'] }] } I want ['a', 'b']. One option for getting all the favFoods of every Doggo in the daycare: getDoggoDaycare(id: 1) { doggos { name } } On the clientside I can traverse and add them to a result array. Is there a cleaner way to do this though? I know I could have a separate query that would resolve this info as well... -
Authorization backends in Django
Does Django have "Authorization backends"? According to this page, it has them: https://djangopackages.org/grids/g/authorization/ Up to now I only know "Authentication Backend"? -
Django get table value with checkbox
I'm looking for getting table row value thanks to checkbox but I don't overcome to get variables according to selected checkbox. I have to add - I'm new with CBV ! This is my template.html : <table class="table table-bordered table-striped table-condensed table_model" style="width: 160%;"> <thead> <tr> <th style="width: 10%;">Choice</th> <th>Document title</th> </tr> </thead> <tbody> {% for document in query_document %} <tr> <td><input type="checkbox" name="DocumentChoice" value="{{ document.id }}"> </td> <td>{{ document.title }}</td> </tr> {% endfor %} </tbody> </table> In my main.py file (similar to views.py file) class Document(View): template_name = 'doc_form.html' form_class = DocumentForm success_url = 'doc_form.html' def get(self, request): form = self.form_class() query_document = None query_document_updated = None if "SearchOMCL" in request.GET: ... some things ... checkbox_id = request.POST.getlist('DocumentChoice') print(checkbox_id) context = { 'form': form, 'query_document' : query_document, 'query_document_updated' : query_document_updated } return render(request, self.template_name, context) I don't overcome to get a list of values when my checkbox is selected. I have to add someting else ? -
Django developer needed to upscale website to handle flood in kerala
I know this is a spam and not exactly what the platform should be used for but we need all the help we can get Kerala, a southern state in India is hit with the worst flood it has experienced in over a century. Nearly 180 people have lost their lives so far and a lot of people are in relief homes. Please help! rescuekerala.in needs Django developers ASAP! If you are a Django developer, please contribute to https://github.com/biswaz/rescuekerala. It is the git repository of https://www.keralarescue.in/. Currently the website is experiencing very high loads due to all the stranded and helpless people accessing it. Thousands of requests are being processed every minute and the number is all set to rise. Calling all open source enthusiasts with Django know-how to improve the load handling capabilities of the website and optimize its operation. Please help! -
ImportError: No module named 'dj_database_url' in pythonanywhere
win7 I have used pythonanywhere to build a website. In the bash console of pythonanywhere, I have installed python 3.5 and Django 2.0, and dj_database_url. However, when I import dj_database_url in settings.py , error happened in the web-page, it says: ImportError: No module named 'dj_database_url'. -
django leaflet layer control geoserver layers
Hello guys I'm trying to add a control panel of layers but don't understand why it is not working, can somebody check my code of what I have done wrong? This is my code: The layers are loaded from geoserver also I copied the three files from dist directory from: https://github.com/ismyrnow/leaflet-groupedlayercontrol. index.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p> <a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs &raquo;</a> </div> {% endblock %} {% block content %} <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Map</title> <style type="text/css"> #gis {width: 100%;height:600px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' %}"> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.js' %}" > </script> </head> <body> <script type="text/javascript"> function our_layers(map, options){ var osm = 'http://{s}.tile.openstreetmap,org/{z}{y}{x}.png'; var datasets = L.tileLayer.wms('http://localhost:8080/geoserver/geodjango/wms', { layers: 'geodjango:layer_ww_manholes', format: 'image/png', transparent: true }); var lines = L.tileLayer.wms('http://localhost:8080/geoserver/geodjango/wms', { layers: 'geodjango:layer_ww_lines', format: 'image/png', transparent: true }); datasets.addTo(map); lines.addTo(map); var baseLayers … -
Confirmation popup for a function in django
I have a function in Django that I need to create a confirmation popup for the user... The function contains lots of conditions, I need to create this popup without a huge change in the code. It took a lot of time, I found "return confirm" for the button .. but I can't change the design of the popup. The function is : def start(request): user = request.user ctx = { 'id-1': request.GET.get('id-1'), 'start_order': StartOrder.objects.filter( user=user, status='ru'), } initial = { 'email': user.email or '', 'password': user.password or '', } The initial form should be appear before the confirmation popup if request.method == 'GET': ctx['form'] = Form(initial=initial) ctx['can_create'] = user.can_create() return render(request, 'orders.html', ctx) After the confirmation popup: if request.GET.has_key('id-1'): test = get_object_or_404(Test, id=request.GET.get('id-1')) form = Form(request.POST, request=request) if form.is_valid(): if not user.can_create_order(): return Http404() ctx['form'] = Form(initial=initial) ctx['can_create'] = user.can_create_order() user.email = request.POST.get('email') user.password = request.POST.get('password') user.save() if request.GET.has_key('id-1'): send_order(test) ctx['started'] = True return render(request, 'orders.html', ctx) orders.html: {% if id-1 %} <form class="user-form " method='post'> {% csrf_token %} <div class="errors"> {{form.non_field_errors}} </div> <div class="form-group"> {% for field in form %} {{field}} {{field.errors}} {% endfor %} </div> The button where should the popup appears after click: <input type='submit' value='Start …