Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load whole page or just section with JQuery
I may be making this more trouble for myself that it is worth but here it goes. I am using Django to build a custom DB interface application and I am trying to have two different ways to handle a form submission. The basic layout of the page is as follows: <div class="jumbotron"> My Header </div> <div class="alert"> A generic message space for posting flash messages about the success or failure of create or update actions </div> <table> My table of database records </table> <form> <div class="alert alert-danger"> A specific message area to display error messages pertaining to form use. </div> My form for creating and updating database records </form> I use JQuery to load both the form and some of the necessary data lists since I want to separate out the query requests to my DB and reduce my TTFB. When the form action is processed successfully then a complete page reload makes perfect sense and that is what I do. However, when a user fails to complete necessary fields I would like to simply reload the form along with the corresponding error message. I have comment tags in my form templates that I could use to identify them, … -
Double loop in Django template
I have been trying to do this nested loop for couple of hours, but so far none of my results worked. Here is what i have so far: index.html {% for category in categories %} <div class="col-md-12 column category list-group"> <p><b>{{ category.name }}</b></p> {% for subcategory in subcategories %} <div class="list-group-item"> <h5 class="mb-1"><a href="{% url 'subcategory_threads' subcategory.id %}">{{ subcategory.name }}</a></h5> <small>{{ subcategory.description }}</small> <small>{{ subcategory.count_threads }}</small> </div> {% endfor %} </div> {% endfor %} views.py class IndexView(ListView): template_name = 'myForum/index.html' context_object_name = 'SubCategory_list' queryset = SubCategory.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() context['subcategories'] = SubCategory.objects.all() return context models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey('Category', default=0) def __str__(self): return self.name Output Output My problem is that SubCategory - News, belongs to Infromation, category Off-Topic belongs to General. For some reason loop displays all of subcategories, and i can't figure out how to narrow it to current Category. -
How to rebuild_index in Django Haystack
I'm using Aldryn Search - a plugin for Django CMS that uses Haystack. I've read both documenations up and down and I don't understand how to properly run manage.py rebuild_index. If I run it as normal I get: SolrError: Failed to connect to server at 'http://127.0.0.1:8000/update/?commit=true', are you sure that URL is correct? So I'm guessing it's because my server is not running. But I can't run this command while my server is running. I try opening a new tab in terminal and run the command while my server is running in the other tab and I get a 403 forbidden error. Such a simple thing is not explained. Also does this command have to be reran every time a page changes content or a new page or blog post gets created? I see this as being a huge problem in production. -
Django + Neural Network
I have web-application written on Django, and i am using Neural Network in it. Separately they works perfect, but together they work very strange. So, here is the code : 1) settings.py verifier = None 2) views.py class SecurityViewSet(viewsets.ModelViewSet): ''' Contains information about inputs/outputs of a single program that may be used in Universe workflows. ''' permission_classes = (AllowAny,) def authorize_person(self, request, *args, **kwargs): if(settings.verifier is None): return Response("Train first!", status=400) X, y = load_data(140) x = np.array([X[0]]) settings.verifier.load_networks() print settings.verifier.verify(x) return Response() def train_model(self,request, *args, **kwargs): X, y = load_data(140) X, y, encoder = select_data_from_range_classes(X, y, range(0, 10)) if(settings.verifier is None): print "Not initialized" settings.verifier = Verifier(X, y, encoder, 10) settings.verifier.train() x = np.array([X[0]]) print settings.verifier.verify(x) else: print "Initialized" settings.verifier.X = X settings.verifier.y = y settings.verifier.encoder = encoder settings.verifier.train() settings.verifier.train() return Response() So, what is the best way to store verifier object?To prevent re-initializing it every time? All functions works well in desktop project, but works strange in API-service. After some test i identified that its related with lifecycle of this object. -
django channels blocked by steam package
I'm using https://github.com/ValvePython/steam https://github.com/django/channels and I'm trying to make them work together. Problem is that when SteamClient starts I cannot send any message with channels. @receiver(post_save, sender=chat_session) def on_create_users_online(sender, created, **kwargs): .... some magic and conditions .... start_bot(kwargs['instance'].match_id, group1, group2,group_name, rad_reward, dire_reward, team1, team2) and in steam.py file: def start_bot(match, group1, group2, group_name, rad_reward, dire_reward, team1, team2): client = SteamClient() client.set_credential_location("steam_credentials") dota = Dota2Client(client) .... some code .... @client.on('logged_on') def start_dota(): Group(group_name).send({ 'text': json.dumps({ 'bot': getSteamProfile(str(client.steam_id)), }), }) dota.launch() dota.wait_event('lobby_removed') ..... a lot of events and code ..... client.connect() client.run_forever() I always end up with this error: gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7fc465aabd58 epoll pending=0 ref=0 fileno=27>) How do I run steam client without blocking consumers.py thread so it can send messages to websocket and I can still pass all parameters(model object, arrays, etc..) I need? -
How to handle condition over time with Django template tags or Python
How would you handle this? I need to be able to set a condition of open or closed based on some data I'm getting from a stream gauge every hour. Very new to python and django so if this is a stupid question please forgive me. The area associated with the gauge is considered closed when the gauge exceeds 10 ft and reopens when it falls below 8ft. When an area is closed it must remain closed for 24hrs. I'd like to be able to set the logic within Django's template tags if possible. The data is populated into a readings model every hour(current condition) and the stations are another model with the logic to check against (flood stage). def close_open: if gauge > 10: closed for 24hrs if gauge > 8: open else: open This is what I had before I realized the metrics for considering an area closed where a bit more advanced. <td><a href="{% url 'record_detail' pk=item.data.pk %}"><span class="status">{% if item.data.stage_feet >= item.flood_stage %}</span> <span class="alert label">Closed</span>{% else %}<span class="success label">Open</span></a></td>{% endif %} Any help extremely appreciated!! -
Restart the process where the error has been detected
In a Django project, it is possible to create unit-tests to verify what we had done so far. The principle is simple. We have to execute the command python3 manage.py test in the shell. When an error is detected in the program, the shell will display it and stop the process. However, the procedure has a little gap. If we have several errors, we have to correct it and restart the whole process. This process could take several minutes which depends of our program. Is there a manner to restart the process where the error has been detected instead of restart the whole procedure? -
django admin enable sorting for calculated fields
I have the following two fields in my db table and model (Model Name: Order): id, branch_id, product_id, cost, quantity, status, ordered_at And I have the following code in my OrderModelAdmin: list_display = ( 'order_number', 'branch', 'product', 'cost', 'quantity', 'calculated_total', 'status', 'ordered_at', ) def calculated_total(self, obj): return obj.cost * obj.quantity calculated_total.short_description = _('Total') Now, I want to enable sorting for this field. In reality, all I need to do is to add a column in my SELECT statement: SELECT (t.cost * t.quantity) as TOTAL ORDER BY TOTAL Is there a way I can append an SQL statement for sorting in Django Admin? -
one of my few django migrations does not run
I have a django migration: 0020_delete_cesiumentity which deletes a table... then I rebuild it (this is was trying to fix a previous problem I had) with this migration I created: 0021_cesiumentity.py # -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-12-19 22:45 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('swsite', '0020_delete_cesiumentity'), ] operations = [ migrations.CreateModel( name='CesiumEntity', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('be_number', models.CharField(max_length=100)), ('image_id', models.CharField(blank=True, max_length=100, null=True)), ('mission_id', models.CharField(blank=True, max_length=100, null=True)), ('product_type', models.CharField(blank=True, max_length=100, null=True)), ('polarization', models.CharField(blank=True, max_length=256, null=True)), ('mode_id', models.CharField(blank=True, max_length=100, null=True)), ('mode_name', models.CharField(blank=True, max_length=100, null=True)), ('acquisition_type', models.CharField(blank=True, max_length=100, null=True)), ('image_size_samples', models.CharField(blank=True, max_length=100, null=True)), ('image_size_lines', models.CharField(blank=True, max_length=100, null=True)), ('sample_spacing_range', models.CharField(blank=True, max_length=100, null=True)), ('line_spacing_azimuth', models.CharField(blank=True, max_length=100, null=True)), ('pass_direction', models.CharField(blank=True, max_length=100, null=True)), ('look_direction', models.CharField(blank=True, max_length=100, null=True)), ('grazing_angle', models.CharField(blank=True, max_length=100, null=True)), ('azimuth_angle', models.CharField(blank=True, max_length=100, null=True)), ('doppler_cone_angle', models.CharField(blank=True, max_length=100, null=True)), ('file_format', models.CharField(blank=True, max_length=100, null=True)), ('name', models.CharField(max_length=100)), ('file_name', models.CharField(max_length=256)), ('country_code', models.CharField(blank=True, max_length=64, null=True)), ('collection_date', models.DateField(blank=True, null=True)), ('collection_start_time', models.CharField(blank=True, max_length=256, null=True)), ('corner_coords', models.CharField(max_length=255)), ('sensor', models.CharField(max_length=128)), ('target_name', models.CharField(blank=True, max_length=256, null=True)), ('file_size', models.IntegerField()), ('dzi_location', models.CharField(max_length=256)), ('kml_location', models.CharField(max_length=256)), ('kmz_location', models.CharField(max_length=256)), ('thumbnail_location', models.CharField(max_length=256)), ('resource_location', models.CharField(max_length=256)), ('processed', models.BooleanField(default=False)), ('created_at', models.DateField(auto_now_add=True)), ('updated_at', models.DateField(auto_now=True)), ('mpoly', django.contrib.gis.db.models.fields.PolygonField(srid=4326)), ], ), ] This migration does not run, causing my 0022 migration to … -
Set user to get automatically deleted at a certain expiry date
I would like an idea how to add a new parameter to the django user table: "expiry date", where to user will expire at that date and gets deactivated. -
Issues with accessing Django app on remote server
I've set up a CentOS7 dev environment on a remote server in order for my team to view the site as I continue to build it. Unfortunately every time I try to run python manage.py runserver, I receive the stock django IP address for the server. When I try to access the app using it, the page is routed to a Yahoo Search Engine page (which means there are usually issues finding the IP). When I try to manually set the IP address, I am still rerouted to the YSE page. The instance was created using a existing Bitbucket repo that uses my local computer instance as the the source. When the server is running, it does not inform me of any errors or issues with spinning up the app. What exactly could be the problem? Has anyone else dealt with an issue like this? Any help that you can provide is appreciated. -
Trying to remove a feature in django-pagedown
Currently using django-pagedown as my text editor, which also allows users to click the img icon in the editor bar to paste an image URL. When the user enters a URL it adds this to the editor body: ![enter image description here][1] [1]: https://www.website/imagePastedFromTheUser.jpg I want to remove the "enter image description here". Here is the documentation for MarkdownEditor.js (the main file in django-pagedown which I think will allow me to remove it): https://github.com/timmyomahony/pagedown/blob/77f33b47bc670b50a3b19947a7a434f7138feabd/Markdown.Editor.js#L38 As you can see on line 38 I can change the contents of the string. However when I remove it I get an error in my console and the img upload buttons doesn't work: Uncaught TypeError: Cannot read property 'length' of undefined at TextareaState.setChunks (Markdown.Editor.js:834) at fixupInputArea (Markdown.Editor.js:1375) at linkEnteredCallback (Markdown.Editor.js:1793) at close (Markdown.Editor.js:1123) at HTMLFormElement.form.onsubmit (Markdown.Editor.js:1149) So removing it causes a chain of errors and i'm unsure how I can remove it while not affecting the image upload function. -
In Django allow only admin user to access views
I have a dashboard app in Django 1.10. I want to restrict access to this app's views to admin user only, if user is not logged in then redirect him to admin's login page. This is where I want to apply some kind of logic so that only admin user can see links that starts with /dashboard/ url(r'^dashboard/', include('demo.dashboard.urls', namespace='dashboard')) -
Django - Should external API requests always be made through a task handler (e.g. Celery)?
I have a Django app where I have created a custom middleware. It works as follows: The middleware intercepts a token (which identifies the users) within each request, and makes a request to an external API with that token. The external API returns what permissions the user making the original request has. The middleware completes, and the user gets data returned based on its permissions This is my question: Because my app has to wait for the API request to return before it can process the request, does it still make sense to use a task queue such as celery? Wouldn't it still have to block the thread while I waiting for the response? -
Create new user registration with one model er extended to another model Profile
The problem is that I extended the User model to a Profile model and the Profile model has a ManyToMany field and I want to create a user registry but I do not know how to do it, I'm giving the ManyToMany relationship error. These are my models. class Categoria(models.Model):#Son las categorias a la que pertenecen los negocios(aplican pa todos) name = models.CharField(max_length=50) slug = models.SlugField(editable=False) imagen = fields.ImageField(upload_to = 'categorias',null=True,blank=True,dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 200, 'max_height': 150})) ]) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Categoria, self).save(*args, **kwargs) def __unicode__(self): return self.name class Perfil(models.Model):#Este es el perfil del usuario(solo existe uno por cada usuario) user = models.OneToOneField(User, related_name='profile') nombre_negocio = models.CharField(max_length=50, unique=True) encargado = models.CharField(max_length=50,null=True,blank=True) imagen = models.ImageField(upload_to = 'perfiles',null=True,blank=True) direccion = models.CharField(max_length=100) telefono = models.DecimalField(max_digits=15, decimal_places=0,null=True,blank=True) email = models.EmailField() category = models.ManyToManyField(Categoria) inicio = models.DateTimeField(null=True,blank=True) final = models.DateTimeField(null=True,blank=True) lat = models.CharField(max_length=50,null=True,blank=True) lng = models.CharField(max_length=50,null=True,blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.nombre_negocio) super(Perfil, self).save(*args, **kwargs) def __unicode__(self): return self.nombre_negocio This is the form I am creating. class UserForm(UserCreationForm): negocio = forms.CharField(max_length=30) encargado = forms.CharField(max_length=30) imagen = forms.ImageField() direccion = forms.CharField(max_length=30) telefono = forms.DecimalField(max_digits=15, decimal_places=0) email = forms.EmailField() #categoria = forms.ManyToManyField(categoria) lat = forms.CharField(max_length=30) lng … -
How to route Celery tasks based on argument?
My situation is this: I have a Listener object per user that belongs in it's own thread. These threads are created/maintained every 30 seconds in a class-based Celery task (stores references to each running thread in an instance variable), thus this task can only be executed by a single thread and a single worker (so that it has access to the Listener thread references). I want to be able to scale this by running it on multiple workers, but I need to be able to always send the same user ID to the same worker thread. What's the best way to route the task to a specific worker thread based on the user ID given as an argument to task? I thought one solution may be to have a unique queue name for each worker, and send the task to a queue based on a hash of the user ID modulo number of workers. However, the problem with this is that I don't know how many workers are running. Does anyone have any suggested architectures to solve this problem? Feel free to ask clarifying questions. -
How/best way to migrate away from an old requirement (django-json-field) with django migration?
I am currently on Django 1.7 and my database is PostgreSQL. I have the following model. # myapp/models.py from django.db import models from json_field import JSONField # using django-json-field from json_field.fields import JSONDecoder class MyModel(models.Model): the_data = JSONField( decoder_kwargs={'cls': JSONDecoder, 'parse_float': float}, default='[{}]', ) ... I am now looking to upgrade to Django 1.10 and take advantage of the new(ish) JSONField in django.contrib.postgres.fields. I change my model to look like this. # myapp/models.py from django.db import models from django.contrib.postgres.fields import JSONField # Now want to use the new JSONField class MyModel(models.Model): the_data = JSONField( default='{}', ) ... I then create a migration for the app. ./manage.py makemigrations myapp When it attempts to create a migration it complains... from json_field.forms import JSONFormField File "/Users/travismillward/Projects/amcards_env/lib/python2.7/site-packages/json_field/forms.py", line 5, in <module> from django.forms import fields, util ImportError: cannot import name util I understand why it is complaining. django-json-field is not updated for django 1.10 and it wants to import json_field in one of the original migration files. So I can either go back and modify my original migration file that imports json_field but then it won't actually modify the column data type because it thinks it is already done. Or, I have to fix … -
Django REST Framework: nested deserializer
I'm again stuck with Django REST Framework and its serializers. Basically, what I want to be able to do is stick the following incoming data into a serializers.Serializer instance: data = { "thing_id": 715, "sub_things": [ { "id": 1, "name": "bob" }, { "id": 2, "name": "mike" } ] } sub_things are handled by a serializers.ModelSerializer called SubThingSerializer. This is how it looks like. class SubThingSerializer(serializers.ModelSerializer): class Meta: model = SubThing fields = ('id', 'name') read_only_fields = ('id', 'name') Serialization of Thing is handled by a ThingSerializer, which I've for now handled as below: class ThingSerializer(serializers.Serializer): thing_id = serializers.IntegerField() sub_things= SubThingSerializer(many=True) Now, when I do serializer = ThingSerializer(data=data) I get empty OrderedDicts like: {'sub_things': [OrderedDict(), OrderedDict()], 'thing_id': 715} I guess it's wise to say that ThingSerializer will not need to get stored into a database, but it does use sub_things from database. These will not be written into db either. This is just to keep track of what sub_things the thing contains, pass this data back and forth between a browser client and a Python object for some calcualtions. And maybe store it in the session. -
Django - build a query with these models
The goal is: Admin logs in to see a list of all registered members in his association. Admin does not want to see members who are in other associations but only in his association. Example: Coach (Admin) want to see all of his players in Real Madrid (association) and are not interested in seeing other soccer clubs (associations) players in his team. I have tried for a long time and ran out of ideas, so hopefully you guys have some great ideas i can try =D Still a newbie so appreciate your help! admin\models.py class Administrator(AbstractUser): ... asoc_name = models.CharField(max_length=100) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Member(models.Model): member_no = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=100) ... class Meta: db_table = 'Member' class Association(models.Model): asocnumber = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=100) user = models.ForeignKey(Administrator) member_no = models.ForeignKey(Member) class Meta: db_table = 'Association' Let me know if you need more info! -
Filtering prefetch_related() to optimize data set
I'm hitting a performance issue on my overview page and am looking for some help. Below is my current query which is working just fine: the page gets rendered in less than 2 seconds with n=12 queries in total. Great so far. person_occurrences = Occurrence.objects\ .filter(date__year=first_day_in_month.year, date__month=first_day_in_month.month, real_time_in__isnull=False, real_time_out__isnull=False)\ .distinct('person') present_persons = Person.objects.filter(occurrence__in=person_occurrences).order_by('last_name')\ .prefetch_related('occurrence_set') \ .prefetch_related('fooindex_set') \ .prefetch_related('servicevoucher_set')\ .prefetch_related('stay_set__hospitalization_set') \ .prefetch_related('invoice_set') However I need to access one more nested model under occurrence_set: .prefetch_related('occurrence_set__meal_noon_options') \ .prefetch_related('occurrence_set__meal_noon_partner_options') When I add these two, my page takes over 25 seconds to load with n=14 queries in total. When debugging (django-debug-toolbar), I noticed the executed query for the latter is: SELECT ••• FROM "stays_mealoption" INNER JOIN "edc_occurrence_meal_noon_options" ON ("stays_mealoption"."id" = "edc_occurrence_real_meal_noon_options"."mealoption_id") WHERE "edc_occurrence_real_meal_noon_options"."occurrence_id" IN (32930, 32931, 32932, 32933, 32934, 32935, 32936, 32937, 32938, 32939, 32940, 32941, 32942, 32943, 32944, 32945, 32946, 32947, 32948, 32949, 32950, 32951, 32952, 32953, 32954, 32955, 32956, 32957, 32958, 32959, 32960, 32961, 32962, 32963, 32964, 32965, 32966, 32967, 32968, 32969, 32970, 32971, 32972, 32973, 32974, 32975, 32976, 32977, 32978, 32979, 32980, 32981, 32982, 32983, 32984, 32985, 32986, 32987, 32988, 32989, 32990, 32991, etc. The occurrence_id's are apparently all IDs that exist in my DB, currently over 10.000. Therefore the returned data … -
Django Test command fails with ImportError, but Runserver works
I've been building and running daily tests for several months now, when all of a sudden Django threw an ImportError when I called python manage.py test applicious. Nothing has changed about my directory structure, and running python manage.py runserver serves up the webpage just fine, so the Python syntax is okay. What's going on? -
'dict' object has no attribute 'all_aircraft'
I have a list of posts that the user is able to favorite and save to their to their account. However, I keep getting the error message above. Does anybody have any idea as to where the issue lies? views.py: def AircraftFavourite(request, id=None): instance = get_object_or_404(Aircraft, id=id) queryset = Aircraft.objects.all() context = {'all_aircraft':queryset} try: selected_aircraft = context.all_aircraft.get(pk=request.POST['context']) except(KeyError, Aircraft.DoesNotExist): return render(request,'aircraft.html', { "aircraft":instance, "error_message":"You did not select a valid aircraft", }) else: selected_aircraft.is_favorite = True selected_aircraft.save() return render(request,'aircraft.html', context) Urls.py urlpatterns = [ url(r'^detail/(?P<id>\d+)/$', AircraftDetail, name='AircraftDetail'), url(r'^(?P<id>\d+)/favourite/$', AircraftFavourite, name='AircraftFavourite'),] aircraft.html {% block content %} {% for a in all_aircraft %} <table> <tr> <th><a href="{% url 'AircraftDetail' id=a.id %}"> {{ a.title }}</a></th> </tr> <tr> <td> <form action="{% url 'AircraftFavourite' id=a.id %}" method="post"> {% csrf_token %} <input type="submit" id="aircraft{{ forloop.counter }}" name ="aircraft" value="{{ a.id }}"> <label for="aircraft{{ forloop.counter }}" {% if aircraft.is_favourite %} <img src="http://i.imgur.com/b9b13Rd.png" /> {% endif %} <input type="submit" value="Favourite"><br> </form> </td> </tr> </table> {% endfor %} {% endblock %} -
how to handle table row's input field value which is dynamicaly created using jq in django views.py and print data another page
when click add row button it add new row with two input field but name is different here is my view #views.py def index(request): #if post request came if request.method == 'POST': for i in range(len(request.POST.getlist())): dd = list(request.POST.getlist('name['+i+']')) ff = list(request.POST.getlist('email['+i+']')) context = { 'dataone': dd, 'datatwo': ff, } #getting our showdata template template = loader.get_template('loggedin.html') #returing the template return HttpResponse(template.render(context, request)) else: #if post request is not true #returing the form template template = loader.get_template('dynamictabel.html') return HttpResponse(template.render()) how to get all values of input field in one variable and send to the other page -
Setting Django admin display times to local time?
When I see dates and times in the admin, they are displayed in UTC. I'd like for them to be displayed in my local timezone. I checked the TIME_ZONE setting in the docs, though it doesn't look like that is quite what I want. TIME_ZONE determines the time zone for the datetimes stored in the database, which is not what I want to set -- I just want to localize the time zones for the admin, but not change how they are saved at the database level. Is there a way to do this? -
How can I compare two object classes?
I have a templatetag that returns all related objects through their tags, but I want to exclude self if the queryset looks through the same class published_projects = Project.objects.published() try: first_obj = published_projects.first() if first_obj.__class__ == obj.__class__: published_projects = published_projects.exclude(pk=obj.pk) except Exception as e: print(e) pass Is there a more pythonic way to compare two object classes?