Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nesting a multiple model serializer in django
I have the following model structure. class Notification(models.Model): name = models.CharField(max_length=50, unique=True) user = models.ForeignKey(User, related_name="+") class Route(models.Model): notification = models.ForeignKey(Notification) notifier = models.ForeignKey(Notifier) destination = models.CharField(max_length=200) class Match(models.Model): name = models.CharField(max_length=100) entity_name = models.CharField(max_length=100, null=True) metric_name = models.CharField(max_length=100, blank=True, null=True) status = models.IntegerField(blank=True, null=True) notification = models.ForeignKey( Notification, blank=True, null=True ) I want to GET a list in the following format and want my API to be able to filter on entity_name, metric_name, status_user { "routes": { "email":"abc@gmail.com", "slack":"name_of_slack_channel", }, "name": "sample", "metric":"CPU", "entity":"some_enttity", "status":WARNING "user":"ent@gmail.com" } Notifications is a mapping of the route model fields notifier: destination. Every row in route will be something of the sort <notificationID, email, "abc@gmail.com> or <notificationID, slack, "slackchannel> As of now I am getting it as { "notification": { "name": "sample" }, "name": "sample", "entity_name": "some_enttity", "metric_name": "CPU", "status": 0 } I have written a serializer on the Match model and I have included notification serializer in it. I am able to query on the user in the Notification model. But how do I get the routes to work in my MatchSerializer? My serializer is as follows. class MatchSerializer(serializers.ModelSerializer): notification = NotificationSerializer() class Meta: model = Match fields = ( 'notification', 'name', … -
Django queryset is returning empty
I have 2 models called Tournament and MatchKnockout. I set up a m2m_changed signal through teams field of the tournament that produce matches when the tournament reached the desired number of teams. The signal is like following; @receiver(m2m_changed, sender=Tournament.teams.through) def create_match_knockout(sender, **kwargs): print("signals recieved!") tournament_type = kwargs.get('instance').tournament_type num = kwargs.get('instance').teams.count() if tournament_type == 'Single Elimination' and ( kwargs.get('action') == 'pre_add' or kwargs.get('action') == 'post_add') and num == kwargs.get( 'instance').num_of_teams: teams = kwargs.get('instance').get_teams_for_knockout() schedule = determine_bracket(kwargs.get( 'instance').num_of_teams) flatten_schedule = flatten(schedule) print(teams) game_num = 1 for i in range(0, len(list(flatten_schedule)), 2): team_a = teams[i] team_b = teams[i + 1] tournament = kwargs.get('instance') match_tittle = team_a.team_name + " - " + team_b.team_name game = MatchKnockout.objects.create(match_tittle=match_tittle, team_a=team_a, team_b=team_b, tournament=tournament, game_num=game_num) game_num += 1 determine_next_rounds(kwargs.get('instance'), 1) Until last line that I was calling the determine_next_rounds method. Everything was fine. def determine_next_rounds(tournament, round): query_set = MatchKnockout.objects.filter(tournament=tournament, round=round) next_game_num = len(query_set) + 1 if (len(query_set) == 0): else: for i in range(0, len(query_set), 2): match_tittle = "Winners of Games " + str(query_set[i].game_num) + " and " + str(query_set[i + 1].game_num) game = MatchKnockout.objects.create(match_tittle=match_tittle, round=round, tournament=tournament, game_num=next_game_num) next_game_num += 1 round += 1 determine_next_rounds(tournament, round) Actually, this method is also working well until the line that I do … -
The checkbox is never showed up
class CreateNoteForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateNoteForm, self).__init__(*args, **kwargs) self.fields['assigned_to'].queryset = get_employees() self.helper = FormHelper() self.helper.layout = Layout( ModalTitle( HTML('<h5>%s</h5>' % _('Create note')), ), ModalContent( Row( Column( Field('content', css_class='s12'), css_class='s12'), ), Row( Column( Field('assigned_to', css_class='s12'), css_class='s3'), Column( Field('due_date', css_class='s12'), css_class='s3'), Column( HTML('{% load i18n %}<span class="help"><i class="material-icons">help_circle</i> {% trans "Leave unassigned to created a note, assign to create a task." %}</span>'), HTML('<script>$($("#id_due_date").datetimepicker({timepicker: false, format: "Y-m-d", formatDate:"Y-m-d", startDate: new Date()}))</script>'), HTML('{% load i18n %}<span class="help"><input type="checkbox">{% trans "Permanent note" %}</span>'), css_class='s6'), ), ), ModalFooter( Field('content_type', type='hidden'), Field('object_id', type='hidden'), HTML('{% load i18n %}'+ '<a href="#save" class="waves-effect waves-green btn-flat" data-turbolinks="false">{% trans "Create" %}</a>'+ '<a href="#cancel" class="waves-effect waves-grey btn-flat" data-turbolinks="false">{% trans "Cancel" %}</a>'), ), ) class Meta: model = Note fields = [ 'content', 'content_type', 'object_id', 'due_date', 'assigned_to', ] This class is used to create a pup-up crispyform. So far it looks like I've got a little issue to install a checkbox with <input type="checkbox"> which is not displayed. What do I have to do to fix the line HTML('{% load i18n %}<span class="help"><input type="checkbox">{% trans "Permanent note" %}</span>') so that the checkbox may be showed up? -
Django template loop where last item value is not Null
DB data: pk,text 2|null 3|foo 4|null 5|foo 6|null I intend to loop the given data, but I only want to iterate over items where text column value is NOT null. Also, I need to know which is the last value where text column is NOT null. This is my intended view once the template has rendered: 3 foo 5 bar *last* In python, such is achieved by an if condition in list comprehension, such as: [x for x in my_loop if x != None] Rendering this in the views.py is massively inconvenient due to how this data is also used in the rest of the template, and this would also gobble up too much unnecessary memory. However, is this possible to do when rendering in django template? Many thanks! -
VSTS build failing with error "Process 'msbuild.exe' exited with code '1'."
Getting that build failed error because I have 4 warnings that read the same. ##[warning]C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Python Tools\Microsoft.PythonTools.Django.targets(120,5): Warning : Errors while resolving environments: Some project interpreters failed to load: Interpreter d:\a\1\s\"name of project"\env\ has invalid value for 'Id': env Interpreter reference has invalid path: Global|PythonCore|3.4 I am using Python 3.4.4 64-bit if that makes a difference. The build is failing during the Build solution **\*.sln section of the build. Thank you in advance for any help. -
How to create fixed table headers using pivottable.js
I am using a java script plugin (pivottable.js) to create pivot tables to display large data on a django site. I want to add a fixed/sticky table head that stays at the top of my div while I scroll down. Due to the creation of the tables in the javascript I cannot easily select the pivot table headers. Does anyone know of anyway they have accomplished this in the past? A large percentage of my users use IE so it is critical it works on that as well. -
How to make some data visible in all sections of a website with django?
Am a newbie in Django and am developing my first website with this framework. Such website must have its social networks links at the top right of the screen along ALL sections. In order to accomplish that, I've made table in models.py with two fields: social network link, and fontawesome icon. Each section of the website is rendered using a template, and all templates extend from only one base template. That base template is the one who must contains the social network links The only way that I know how to show those links along ALL sections is passing them to the template in each view. That's against the DRY (Don't Repeat Yourself) rule. Is there a way to pass them only once, and make it visible to all website? Tanks in advance. -
I don't see my objects on the Django site
I try to create Django Build-in API Documentation however I can't add objects to the list on the left. When I open localhost:8000/docs/ I don't see list of my objects as at the top of the official Django REST documentation (in this case snippets and users). Currently I am trying in this way: models.py: class Object1(models.Model): user = models.ForeignKey(User) value = models.FloatField() admin.py based on https://developer.mozilla.org: from django.contrib import admin from .models import Object1 # Register your models here. admin.site.register(Object1) I also based on https://docs.djangoproject.com and I tried with this admin.py version: class Object1Admin(admin.ModelAdmin): pass admin.site.register(Object1, Object1Admin) I was using also other ways but I did not get a positive result with them, too. Any suggestions? -
Django, How can i use {% url %} template in jQuery, prepend?
$.each(data, function (index, value) { #Here is where 'value' from $("#contentsbox") .prepend( '<div><a id="URLcomes" href="{% url 'somename' value.id %}">Here comes hyperlinks</a></div>' ); }); I've got some json data and want to make div tag dynamically. I will use .prepend() but there needs plain text and i can't make string with {% url 'somename' value.id %} At that template tag, value.id is from each - function(index, value) I want {% url 'somename' value.id %} in prepend(), but I can't make it string as prepend() needs. How can i make string ? -
Django one-to-many with "overrided state"
What is the best best approach to implement one-to-many relationship in Django with "overriding" state of single object for its holders? Let's imagine we have a card game. Each card in the game deck can be in one of three states: not available available to be found (but not yet found) found. These states are unique for every player, so every player can have its own set of found, available, not available cards. Is it a good idea to make a single table with game cards and set one-to-many relation for each card and players who can use the card or still not allowed to use the card? And I suppose it is not a good idea to clone the whole deck table for every user as the cards in the table a same for everyone. Or tell me please what is the better approach to implement a good design for that problem. Thanks. -
Query data from mysql database using where statement and use in Django template
I have a db table with data like : ID epic_key issue_key status 1 JIR-1 JIR-12 TODO 2 JIR-2 JIR-13 OPEN 3 JIR-2 JIR-18 CLOSE 4 JIR-2 JIR-88 TODO 5 JIR-3 JIR-89 TODO 6 JIR-3 JIR-99 CLOSE My Views.py looks like def index(request): latest_question_list = Jirareport.objects.values('epic_key').distinct() latest_issue_list = Jirareport.objects.all() context2 = {'latest_issue_list': latest_issue_list} context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context,context2) And the piece of code in index.HTML is % for question in latest_issue_list %} <div data-role="main" class="ui-content"> <div data-role="collapsible"> <h1>{{question.epic_key}}</h1> <p>{{question.issue_key}}</p> </div> </div> {% endfor %} Question : My ask is to display unique values of column "epic_key" and all values of column "issue_key" in statement provided in the html. Just like this For the epic_key = **JIR - 2** JIR-13 JIR-18 JIR-88 -
Django-RQ Not Executing Enqueued Function
I am currently using Django-RQ to queue tasks once a Django form has been submitted. To test it out first I am trying to get it to print out the solution to two numbers being added. Here is the function in my tasks.py file: def add(x, y): print("The output is: ", x + y) And here is how I call it in my views.py: queue = django_rq.get_queue('default') queue.enqueue(tasks.add, 1, 2) However this returns nothing in my console. Additionally this is what my settings.py looks like: # Django-RQ Settings RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 8, #'PASSWORD': 'some-password', #'DEFAULT_TIMEOUT': 360, }, 'high': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'low': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, } } Any idea on where I am going wrong? Thanks -
Django migration drops and re-adds same constraint
Asking for a friend... Can anybody explain why my Django migration is dropping and re-adding the exact same constraint on my table column when I add blank=True to the model field? Here's my change in my model: # old definition class CatalogCourse(models.Model): subjects = models.ManyToManyField(CatalogSubject, related_name="catalog_course_set") # new definition with `blank=True` class CatalogCourse(models.Model): subjects = models.ManyToManyField(CatalogSubject, related_name="catalog_course_set", blank=True) When I makemigrations, I get this migration: class Migration(migrations.Migration): dependencies = [ ('homepage', '0005_previous_migration'), ] operations = [ migrations.AlterField( model_name='catalogcourse', name='subjects', field=models.ManyToManyField(blank=True, related_name='catalog_course_set', to='homepage.CatalogSubject'), ), ] The SQL for this migration is simply: BEGIN; -- -- Alter field subjects on catalogcourse -- ALTER TABLE "homepage_catalogcourse_subjects" DROP CONSTRAINT "homepa_catalogsubject_id_304824f4_fk_homepage_catalogsubject_id"; ALTER TABLE "homepage_catalogcourse_subjects" ADD CONSTRAINT "homepa_catalogsubject_id_304824f4_fk_homepage_catalogsubject_id" FOREIGN KEY ("catalogsubject_id") REFERENCES "homepage_catalogsubject" ("id") DEFERRABLE INITIALLY DEFERRED; ALTER TABLE "homepage_catalogcourse_subjects" DROP CONSTRAINT "homepage_catalogcourse_id_cc699e39_fk_homepage_catalogcourse_id"; ALTER TABLE "homepage_catalogcourse_subjects" ADD CONSTRAINT "homepage_catalogcourse_id_cc699e39_fk_homepage_catalogcourse_id" FOREIGN KEY ("catalogcourse_id") REFERENCES "homepage_catalogcourse" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; Is Django just built to drop a constraint and re-add it anytime we alter the field? I can't think of any reason why that would need to happen? Are there operations that can't be performed while a foreign key constraint exists? -
django photologue images won't display - why?
This one's really grinding my gears - and those of my friend who is equally as stuck. So basically i'm at the start of a relatively basic project and I pip installed photologue, strictly following the documentation. I have installed pillow and sorted2m + anything that the docs said was a dependency. Mostly everything is fine on the admin site, i can create a gallery, upload a photo etc and the library will create a the necessary directory structure starting from my project's root and the image ends up there as it should. The hyperlink in the admin site seems to be the right url yet when I click on it, it says it doesn't recognise the URL patterns from photologue's urls and when I click view on site, it'll take me to a page that's been created for the image (so I at least know that's working) but again, the image isn't found. I have a feeling this is to do with it not being my static media folder, but it won't allow me to set my media_root to the same thing so does anyone know what's going on? It's the latest stable build of photologue, django1.10 and python … -
multiple sets of data for each organisation
I have a Django app which I want to get businesses/organisations/schools to sign up to. The business/school/organisation should be able to manage users and user permissions but only for their own organisation. At least one of these users will be an admin for that business/school/organisation. Each business/school will have a set of data which should only be accessible to that business/school/organisation. My question is what is the best way to achieve this? Obviously I can filter the data in the views and templates but that seems to me like the wrong way to do it. For example I have a model which is recording software licenses. Should I have a ForeignKey for each entry/row that links it to the organisation and filter it in the view/template or is there a way to have a separate data sets for each organisation? -
How to display second edit form with current value in the form using django class based view
I have two forms as shown below class TicketView(ObjectEditView): form_class = forms.FirstForm form_class2 = forms.SecondForm model = First def get(self, request, pk): first = get_object_or_404(First, pk = pk) return render(request, 'my_folder/file.html', { 'first': first, 'form': self.form_class, "form2":self.form_class2 }) For the second form there is a drop down,with status as open, close and hold. I am getting the drop down well using the below code {% render_field form2.status %} but it's not displaying current value as selected. Is there anyway to assign current value of the drop to the template and then set that value as selected in the drop down using the render_field? Something like {% render_field form2.status value='close' %} -
Django - possible for users to overwrite variable in memory?
If I have list stored as a class variable that receives items throughout the course of a session, is it possible that multiple users in my Django application could be writing/overwriting the same variable in memory? -
Django, update multiple field
I have a product list, and I would like to update selected items(e. G. quantity) ProductA 2 ProductB 3 ProductC 4 Update to with a POST request ProductA 3 ProductB 4 ProductC 5 -
Django table with ChoiceField
I have a table filled with data from a model. Model: class DetalleAuditoria(models.Model): id_auditoria = models.AutoField(primary_key=True) id_control = models.ForeignKey(Control,db_column='id_control', verbose_name='Control') id_analista = models.ForeignKey(User,db_column='id', verbose_name='Analista') fecha = models.DateTimeField(verbose_name='Fecha de Proceso') id_sharepoint = models.IntegerField(verbose_name='ID SharePoint') id_tipoerror = models.ForeignKey(TipoError,db_column='id_tipoerror', verbose_name='Tipo de Error') observaciones = models.TextField(max_length=4000) id_estado = models.ForeignKey(Estado,db_column='id_estado', verbose_name='Estado') auditor = models.CharField(max_length=20,verbose_name='auditor', blank=True, null=True) Form: class DetalleAuditoriaForm(forms.ModelForm): id_control = forms.ModelChoiceField(queryset=Control.objects.all(),required=True, label='Control', widget=forms.Select(attrs={'class':'form-control'})) id_analista = UserModelNameChoiceField(queryset=User.objects.filter(is_staff=False), required = True, label='Analista', widget=forms.Select(attrs={'class':'form-control'})) fecha = forms.DateField(widget=DateInput()) id_tipoerror = forms.ModelChoiceField(queryset=TipoError.objects.all(),required=True, label='Control', widget=forms.Select(attrs={'class':'form-control'})) id_sharepoint = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control'})) observaciones = forms.CharField(widget=CKEditorWidget()) id_estado = forms.ModelChoiceField(queryset=Estado.objects.all(),required=True, label='Estado', widget=forms.Select(attrs={'class':'form-control'})) class Meta: model = DetalleAuditoria def __init__(self,*args,**kwargs): super(DetalleAuditoriaForm,self).__init__(*args,**kwargs) self.helper = FormHelper(self) How can I show all the records in table with a CHOICEFIELD for the column ID_ESTAOD. I don't need to add or delete records, only show and modified the existing records. Thanks in Advance -
Can I assign queryset to django form in views? [duplicate]
This question is an exact duplicate of: I want to create form fields in Django views.py rather then forms.py 1 answer I posted this question with other caption but I want to ask that , I want to make a dropdown . And Query to get this values I have to assign in view.py. So can I assign this query in view.py to form field ? like I have class pdftabelModelForm(forms.ModelForm): class Meta: model = pdftabel_tool_ fields = ['apn', 'owner_name'] apn = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)") owner_name = forms.ModelChoiceField(queryset= Field.objects.values_list('name', flat=True), empty_label="(Choose field)") I want to do same in views.py and assign this form field. Any help would be highly appreciated. -
Django Query a query?
Trying to speed up the performance of my app, and post some analysis with debug toolbar I can see I am doing 68 queries. I query the circuits for every showroom (68 of), I thought if I just query the circuits once, could I then requery the existing query instead of calling the DB again for each Circuit? something like adding: crData = Circuits.objects.only('circuit_preference','site_data__id') then how to query crData again? to match each statement? Current code below # get shworoom data srData = SiteData.objects.only('location','subnet').filter(is_live=True).exclude(site_type='Major Site') for sr in srData: site = SiteType() site.type = checkRoute(sr.subnet) site.location = sr.location if 'MPLS' in site.type: mpls = site.type.split('-') try: d = Circuits.objects.only('circuit_preference','site_data').filter(site_data__id=sr.id,provider=mpls[0],circuit_type__icontains=mpls[1]) site.preference = d[0].circuit_preference except: pass elif site.type == '4G': try: d = Circuits.objects.only('circuit_preference','site_data').filter(site_data__id=sr.id,provider='EE',circuit_type__icontains=site.type) site.preference = d[0].circuit_preference except: pass elif site.type == 'DSL' or site.type == 'FIBRE': try: d = Circuits.objects.only('circuit_preference','site_data').filter(site_data__id=sr.id,circuit_type__icontains=site.type) site.preference = d[0].circuit_preference except: pass -
Django Templates: Writing an if filter to get around dividing by Zero
I am using template tags to divide two numbers. The problem occurs when the denominator is zero. I am trying to use if with operators but this seems to not be working. <td class="data">${% if nnl_asof_mtdgoal %}{{ nl_mtdgoal.get_mtd_newloansgoal|div:nnl_asof_mtdgoal.get_mtd_numnewloansgoals |floatformat:"2"| intcomma }}{% endif %} This gives me this error File "C:\pycharm-virtenv\DjangoPostgres\lib\site-packages\mathfilters\templatetags\mathfilters.py" in div 72. return nvalue / narg Exception Type: ZeroDivisionError at /reports/goals/ Exception Value: float division by zero As it should since its division by zero. When I try this: <td class="data">${% if nnl_asof_mtdgoal !="0" %}{{ nl_mtdgoal.get_mtd_newloansgoal|div:nnl_asof_mtdgoal.get_mtd_numnewloansgoals |floatformat:"2"| intcomma }}{% endif %} </td> I get this error: Exception Type: TemplateSyntaxError at /reports/goals/ Exception Value: Could not parse the remainder: '!="0"' from '!="0"' I know this has to be an easy one but I cannot seem to figure out how to only draw the table if the division is True, i.e. not dividing by zero. -
Proper way to fill an html array using django/python
I encounter a small issue about filling my html array in a django template. I wanted to print one form to one row. Instead of one row to all forms ( that's what i get with the sample code juste right there ) : <thead> <!-- cétait td à la place de th --> <tr> {% for entry in headers %} <th> {{ entry }} </th> {% endfor %} </tr> </thead> <tbody> <tr> {%for entry in entries%} {%for cle, valeur in entry.all_form_entry_json%} {%for key, valor in headersLoop%} {%if key == cle%} <td> {{valeur}}</td> {% endif %} {% endif %} {% endfor %} {% endfor %} {% endfor %} </tr> </tbody> The result is such as follow : You can notice that all the datas are printed to the right corner and go beyond the array limit. How can i have a result like this ? Is this possible to do it only with html ? Or should i create a js or css file and import it to this template.html ? Thank you for your answers ! -
How can I validate my forms or views in Django so that they can only edit the User Model only to those that belong to that data?
I have 2 models that I will allow users to edit separately, one is called User(Django default auth) and the other is UserProfile. models.py (UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatar', default='avatar/default.png') header = models.ImageField(upload_to='header', default='header/default.png') bio = models.TextField(max_length=140, blank=True) website = models.URLField(max_length=200, blank=True) location = models.CharField(max_length=30, blank=True) date_birth = models.DateField(null=True, blank=True) views.py class UserUpdateView(generic.UpdateView): """ This view is for editing only the User model. /edit/ """ model = User slug_field = 'username' form_class = UserForm template_name = 'user/user_edit.html' -
MyModel.objects.update_or_create() --> Boolean wether data was updated or not?
AFAIK Django does not provide a generic way to see if data was update by update_or_create() The boolean created tells me that a row was created. But how can I know if data was altered?