Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set ssh connection in Django?
I want to set and ssh connection using Django and access files on the host. I'm new to ssh and django. Can someone please explain how should I achieve this? -
what is the easiest way to strip html tags but keep its functionality?
I am using a floral editor on my text area and when I enter the value in the text area it saves the value on the table.I am using striptags.But,the problem with striptags it removes all tags. What i want to achieve is to remove all the tags and keep the data in html form in the table also.By this I mean that I want to keep the functionality of the tags on the html table html editor on text area: <textarea class="form-control fr-view" name="description" id="froala-editor" placeholder="Descriptions">{{frontend.tDescription |default_if_none:'' }}</textarea> <script> $(function() { $('textarea#froala-editor').froalaEditor() }); </script> now at templates i am calling currently like this: {{ item.tDescription |striptags}} -
How to upload images of 10k movies in one go in Django?
I am creating the website which contains 10k movies and it has an attribute called movies_logo which stores the logo of the respected movie .So is there any way so that I can upload all the logo of the respected movies in one go because uploading logo of each movie will take lot of time.This is my models.py. from django.contrib.auth.models import Permission, User from django.db import models from decimal import Decimal class Picture(models.Model): user = models.ForeignKey(User, default=1) picture_id = models.IntegerField(default=0) picture_title = models.CharField(max_length=500) genres = models.CharField(max_length=1000) ratings = models.DecimalField(max_digits=10,decimal_places=1) picture_logo = models.ImageField() def __str__(self): return self.picture_title -
django delete model in admin site - 'bool' object is not callable
When I try to delete a model in the admin panel, I get this error. I can not find where the problem is. TypeError at /admin/account/cloud/1/delete/ 'bool' object is not callable admin site Error link django: 1.10.6 postgres: 9.5.6 OS: Ubuntu server 16.04 Model with problem: class Cloud(models.Model): NAME_CHOICE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4') ) account = models.ForeignKey(Account, verbose_name='Аккаунт') name = models.CharField(choices=NAME_CHOICE, verbose_name='Название', max_length=20, default=NAME_CHOICE[0][0]) username = models.CharField(verbose_name='Пользовательское название', max_length=100, null=True, blank=True) active = models.BooleanField(verbose_name='Активный?', default=False) params = JSONField(verbose_name='Параметры', null=True, blank=True) delete = models.BooleanField(verbose_name='Удален?', default=False) def __str__(self): return 'ID: {}, облако: {}'.format(self.id, (self.username or '-')) INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'api', 'cell', 'files', 'deploy_frontend', 'rest_framework', # 'rest_framework_docs', 'rest_framework_swagger', ] How obj can be "bool", if obj = cloud-object? -
Checkbox based table data
I am beginner of learning django. I am making a simple app , which will count fruits quantity. Example: There is some checkbox as like: orange, grape , lemon, mango, blackberry. and table contains quantity of those fruits. Let assume, orange 20, grape 50, lemon 10, mango 10, blackberry 20 for user 1 --> first row of table orange 40, grape 60, lemon 70, mango 110, blackberry 220 for user 2 --> second row of table orange 40, grape 60, lemon 70, mango 110, blackberry 220 for user 3 --> third row of table When I will check in only orange, lemon, mango , then my table will show the data only for orange, mango and lemon for user1, user2, user3 without any page refreshing. Furthermore, It will calculate the average of all fruits as like orange+ lemon+ mango+ mango that means for first row of the table it will show 13.667 and a condition text 'good' if average is over 10, second and third row will follow the same procedure. My question How to make this table of onclick check box behavior by javascript in my djnago view? Should I use AngularJS for it ? Please help me. -
Unknown column 'ModelName.id' in 'field list'"
I am using Django with mysql. I have created models.py using command inspectdb from existing database in mysql. It has a model as below : class Participationdata(models.Model): userid = models.ForeignKey('Volunteer', models.DO_NOTHING, db_column='UserId') # Field name made lowercase. eventid = models.ForeignKey('Events', models.DO_NOTHING, db_column='EventId') # Field name made lowercase. ptrflag = models.IntegerField(db_column='PtrFlag', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'ParticipationData' unique_together = (('userid', 'eventid'),) I have inserted the data into database using this model successfully. But while selecting data it is showing the error like : django.db.utils.OperationalError: (1054, "Unknown column 'Participationdata.id' in 'field list'") How should I resolve this ? -
Connection to broker lost. Trying to re-establish the connection
We are using Django Rest Framework with MongoEngine, Redis, Celery and Kombu, and we are getting the following error in our logs: `[2017-03-22 06:26:01,702: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/usr/local/lib/python2.7/dist-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 594, in start c.loop(*c.loop_args()) File "/usr/local/lib/python2.7/dist-packages/celery/worker/loops.py", line 88, in asynloop next(loop) File "/usr/local/lib/python2.7/dist-packages/kombu/async/hub.py", line 345, in create_loop cb(*cbargs) File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 1039, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 337, in on_readable chan.handlerstype File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 667, in _receive ret.append(self._receive_one(c)) File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 678, in _receive_one response = c.parse_response() File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2183, in parse_response return self._execute(connection, connection.read_response) File "/usr/local/lib/python2.7/dist-packages/redis/client.py", line 2176, in _execute return command(*args) File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 577, in read_response response = self._parser.read_response() File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 238, in read_response response = self._buffer.readline() File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 168, in readline self._read_from_socket() File "/usr/local/lib/python2.7/dist-packages/redis/connection.py", line 143, in _read_from_socket (e.args,)) ConnectionError: Error while reading from socket: ('Connection closed by server.',) [2017-03-22 06:26:01,868: INFO/MainProcess] Connected to redis://:******************************/1 Versions used python==2.7.12 redis==3.2.3 kombu==4.0.2 Django==1.10.3 celery==4.0.2 amqp==2.1.1 billiard==3.5.0.2 pytz==2016.7 Django==1.10.3o We have HaProxy infront of Redis cluster and connections, everything else work without any issues. Could you please help … -
How to work with JSON object after it has been passed from views.py in django?
Consider a django model which stores the name, phone number and address of people. To allow users to edit its contents, I have created an edit form in html template using bootstrap modals. I want to provide an option to the user to 'leave the field blank to retain old information' (which is not the problem). Along with this, I would also like to display the current information of each field as present in the database (as a placeholder value of the <input> tag). In order to do that, I have created a 'context' dictionary in views.py which contains the data to be sent. My question is, how do I send this dictionary from views.py to an html template without rendering any html page and how to parse this data on the template. Note: I don't want to render any new page since I am using the bootstrap modal for the edit form. -
Django CMS app is on server's localhost
I'm setting up my app and everything is going good, no errors. I enter the command "python manage.py runserver" and everything starts normally. I then realize it says "Starting development server at https://127.0.0.1.:8000/". How do I get to the localhost that is on a server? I feel like I'm going to kick myself when I get this answer. P.S. This is in PuTTY. Not in my command prompt. -
Broken url django subsite
I am setting up my different django site(different codebase) under one domain(subsite directory hosting). Domain name is http://example.com and my sites url are like this . http://example.com/first http://example.com/second and so on The index page is loading properly, but the navigation urls are broken. ie instead of http://example.com/first/page1 it is going to http://example.com/page1 from the links. How to fix the issue. I am using django 1.8 -
Django, get form data before is_valid?
I'd like to get data supplied to forms (after dealing with form prefixes.) (I can't use cleaned_data because I want to get data regardless form is valid or not) I know I can get a single field's value by form_instance[field_name].value() So theoretically I can get all values by data = {} for field_name, field in form_instance.fields.items(): data.update({ field_name: form_instance[field_name].value() }) wonder if there's a better way? -
how to create a token using jquery with django passing variable o the front?
front end and back end are in two different servers. they are able to connect now but without using django's own template to get the user's info. How can I use jQuery to get user's info? let's say after a user log in, django does pass an object named user into front end but how can I use jquery to get it and save it as token so info does save for a period of time? Thanks in advance -
Best practice for generating a static website
I have a website which won't change too often, but is still associated with a database. I want to render the html pages (taking into account the models), using a template engine, and be able to upload the resulting html on a S3 bucket. I want to do that with django. Is there a best practice for that? I know I can do it manually, but maybe there's a built-in solution. I know about flatpages, but that's not quite what I need. -
Redundant processing in django form clean method and in view
I am working on a Django form that accepts and processes an XML file (specifically, the view will need to parse a list of bands from an XML file exported from iTunes). I plan on verifying that the XML parser runs without exceptions within the form clean() method. However, I'd then like to have access to the parsed output list of bands in my view, without having to rerun the XML parser. (The XML parser can take non-negligible time for large files, so I do not want to run it multiple times.) Is there any way I can make this happen without needing to run the parser twice? That is, can I access an arbitrary variable in the form clean() namespace from a view? (I would really like to raise the ValidationError in the view, but I understand that is not possible.) Thanks! -
Django ORM queryset to match a value that contains a suffix with the value on the database
I'm trying to match strings with unexpected additional suffix and then select the database in the string. Example Model: class Example(models.Model): name = models.CharField(max_length=100, default='abcdef', unique=True) Code: string = 'abcdef' unexpected_suffix = '_d' # This is random and can be '_e', 'eeee', '321' _string = '{0}{1}'.format(string, unexpected_suffix) x = Example.objects.get(name__lookup=_string) Then the variable x will SELECT the row with a name value of 'xxxx'. Is it possible to just use purely Django ORM with this? -
I have saved the url of image in "url" field of UserProfile..how to display the image in templates using this url?
models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile") name = models.CharField(max_length=250, null=True, blank=True) url=models.CharField(max_length=500,null=True,blank=True) def __str__(self): return u'%s profile' % self.user.username views.py def home(request): context ={'request': request, 'user': request.user} return render(request,'home.html',context) For social authentication I am using Python Social Auth and I am saving the data from social profile in UserProfile model. templates/home.html {% extends 'base.html' %} {% block main %} <div> <h1>authentication demo</h1> <p> <ul> {% if user and not user.is_anonymous %} <li> <a>Hello {{ user.get_full_name|default:user.username }}!</a> </li> <li> <a href="{% url 'auth:logout' %}?next={{ request.path }}">Logout</a> </li> {% else %} <li> <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login with Facebook</a> </li> <li> <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Login with Google</a> </li> <li> <a href="{% url 'social:begin' 'twitter' %}?next={{ request.path }}">Login with Twitter</a> </li> {% endif %} </ul> </p> </div> {% endblock %} -
Why do I add 2 + in the post_save?
The problem that at the moment of saving a value, to be inserted into the table the post save () of the model adds me 1+, why does this happen? Eg, entry 3, saves it and remains a 5. models.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') fecha_entrega = models.DateTimeField(auto_now_add=False) fecha_pedido = models.DateTimeField(auto_now_add=True,null=True, blank=True) cantidad = models.IntegerField(blank=True) estado = models.CharField(max_length=20, blank=True, default='pendiente') def __str__(self): return '{}'.format(self.especialidad, self.articulo, self.cantidad, self.estado) Function that saves and adds after inserting the data cantidad: def update_total(sender, instance, **kwargs): instance.articulo.total_pedido += instance.cantidad instance.articulo.save() # register the signal signals.post_save.connect(update_total, sender=Pedido, dispatch_uid="update_stock_count") Why are you adding 2 more? help! -
Django App Deployment with Heroku: Error H10 App Crashed
I am trying to deploy a Django web app to Heroku, but whenever I try to open the app: heroku open I am greeted by: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. on the site I am hosting it on. I checked the logs, and they read: 2017-03-23T02:13:54.254184+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=salty-wildwood-65286.herokuapp.com request_id=64adedaf-b6e3-45f4-819d-32a24b1a029f fwd="76.119.208.238" dyno= connect= service= status=503 bytes= protocol=https Procfile web: python manage.py runserver $PORT the name of my app is immitweet, or at least, that's the name of the folder I initialized the GitHub repository. I am able to run the app locally just fine, however it is when I try to deploy it and run it on the web is when I have this issue. I assume it has to do with the Procfile, but I do not know what. Thanks! (NOTE: This isn't a RoR application) -
Save all filtered objects into another model in one click
i was thinking of a "Buy" button that saves all the filtered items in models.Cart into models.Buy, where the user had saved, while adding a few more field while it's on it. can someone show me an example how to do it? do i put table in the form? <form> {% for item in Cart %} <table> </table> {% endfor %} <button> </form> i don't know how the views.py should be, or maybe there is a better way to do it? or maybe bulk or batch save? I did came across a bulk update answer on stackoverflow ModelClass.objects.filter(name='bar').update(name="foo") but is this doable? ModelClass.objects.filter(name='bar').save() Thanks in advance Cheers -
Relative Template Import
I have a template located in templates/mytemplate.html in my app and I need to reference the template file directly in code to turn it into a string to use with send_mail(). How can I do this? Here's what I've tried: from django.template import loader html_message = loader.render_to_string( 'appname/templates/mytemplate.html', { 'username': user.name, } ) -
Sending FILE to a External API REST from Django
I'm trying to send a file from a DJANGO FORM to an API REST service, if i send only the text it works but i need to send a file an i tried all that i found but i doesn't work. This is my form: class Publicacion(forms.Form): publicacion = forms.CharField(label=False, widget=forms.Textarea(attrs={'rows': '3', 'cols': '40'})) imagen = forms.FileField(required=False) This is the html of that form: <form name="publicion" enctype="multipart/form-data" id="publicacion" method="POST">{% csrf_token %} <div class="post post_form" style="padding:0;"> {{ formpublicar|crispy }} <button class="post_form_extra"></button> <input value=" " type="submit" class="post_form_submit" name="publicar"/> </div> </form> and this is my views.py method: def sesionactiva(request): if 'token' in request.session: token = request.session['token'] crearpublicacion = Publicacion(request.POST or None, request.FILES or None) if 'publicar' in request.POST and request.POST['publicar']: if crearpublicacion.is_valid(): publicacion_data = crearpublicacion.cleaned_data publicaciontexto = publicacion_data.get("publicacion") imgpublicacion = request.FILES['imagen'] apipublicar = 'http://localhost/apiSocial/publicacion/createPublication' payloadpublicacion = {'token': token, 'texto': publicaciontexto, 'imagen': imgpublicacion} responsepublicacion = requests.post(apipublicar, data=payloadpublicacion) crearpublicacion = Publicacion() -
Django QuerySet API to imrove Query Optimization
I have the below query that loops through three different tables and creates a records in the Master table. The query works, but I wanted to know how I could gain efficiency and improve the query by leveraging Django QuerySet API, if possible. Django query: s = Schedule.objects.get(pk = s_pk) order = s.ordering_set.all() days = s.dayscheduler_set.all() for z in days: for x in order: s_val = x.room.spacetype.pk s = Space.objects.get(pk = s_val) q = Group.objects.filter(space = s, is_default = True) for y in q: daySch = DayScheduler.objects.get(pk=z.pk) room = Room.objects.get(pk=x.room.pk) group = Group.objects.get(pk = y.pk) M = Master.objects.create(room = room, dayScheduler = daySch, group = group) M.save() Django Model: @python_2_unicode_compatible # only if you need to support Python 2 class Schedule(models.Model): building = models.ForeignKey(Building, on_delete = models.CASCADE) schedule_name = models.CharField(max_length=200) def __str__(self): return self.schedule_name @python_2_unicode_compatible # only if you need to support Python 2 class Ordering(models.Model): schedule = models.ForeignKey(Schedule, on_delete = models.CASCADE) order_number = models.IntegerField() room = models.ForeignKey(Room, on_delete = models.CASCADE) def __str__(self): return str(self.order_number) @python_2_unicode_compatible # only if you need to support Python 2 class Room(models.Model): building = models.ForeignKey(Building, on_delete = models.CASCADE) room_name = models.CharField(max_length=200) rmfloor_name = models.ForeignKey(Floor, on_delete = models.CASCADE) sqfootage = models.IntegerField() spacetype = models.ForeignKey(Space, on_delete = … -
How can I bypass the Language request
On each of my view I have a function that return the request language code of the browser. But when I run my unittest my views I have an error: applications\emplois\views.py:74: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <applications.emplois.views.IndexView object at 0x0000000006270048> def language(self): """Return the user default language""" > language = language_set(self.request.LANGUAGE_CODE) E AttributeError: 'WSGIRequest' object has no attribute 'LANGUAGE_CODE' applications\emplois\views.py:64: AttributeError ---------------------------- Captured stdout setup ---------------------------- Creating test database for alias 'default'... =================== 1 failed, 11 deselected in 5.97 seconds =================== views.py def language_set(language): if "-" in language: return (language.split('-')[1]).upper() else: return language.upper() class IndexView(generic.ListView): """ this is the ROOT page return a list of Jobs """ template_name='emplois/index.html' context_object_name='latest_jobs_list' paginate_by = 10 def language(self): """Return the user default language""" language = language_set(self.request.LANGUAGE_CODE) language = language.upper() return language def get_queryset(self): """ Return a list of Jobs that have an EXPIRATION DATE greater than Now() and a default Language """ #import ipdb;ipdb.set_trace() return Job.objects.filter(language=self.language(),\ EXPIRYDATE__gt=datetime.now())\ .order_by('EXPIRYDATE') tests: import pytest from django.core import mail from django.contrib.auth.models … -
Django autocomplete select does not work when deployed
I deployed an app in Pythonanywhere, and the Django autocomplete light for the admin page isn't being loaded, However when I run the app in the local host it works. For it to load, I need to set where the static files for the DAL are /home/myusername/.virtualenvs/django17/lib/python3.4/site-packages/dal/static/autocomplete_light /home/myusername/.virtualenvs/django17/lib/python3.4/site-packages/dal_select2/static/autocomplete_light I'm using django 1.10, python 3.4 -
Separate classes for different user types in Django
I'm writing application which implements three different user types: Admin user (Django Admin) Mobile user (django rest framework) External user (django rest framework) The problem is that External user and Mobile user are much different from Admin user, for example they use different type of username field for authentication (and different authentication backends too), so I can't do this: AUTH_USER_MODEL = "AdminUser" class AdminUser(DjangoAbstractUser): username = models.EmailField() class MobileUser(User) custom_field = ... class ExternalUser(User) custom_field = ... The question is, if I use three separate classes (the code is below) and three different authentication backends, will there be any consequences of that? For example request.user will store three types of classes: ExternalUser, MobileUser and AdminUser. AUTH_USER_MODEL = "AdminUser" class AdminUser(DjangoAbstractUser): username = models.EmailField() class MobileUser(DjangoAbstractUser) username = models.IntegerField() custom_field = ... class ExternalUser(DjangoAbstractUser) username = models.CharField() custom_field = ... Thank You.